file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
11641_4 | import java.util.ArrayList;
/**
* Presentation houdt de slides in de presentatie bij.
* <p>
* In the Presentation's world, page numbers go from 0 to n-1 * <p>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
// Verandering: Presentation wordt een Observable
public class Presentation {
private String showTitle; // de titel van de presentatie
private ArrayList<Slide> showList = null; // een ArrayList met de Slides
private int currentSlideNumber = 0; // het slidenummer van de huidige Slide
// Verandering: we kennen slideViewComponent niet meer direct
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides
public Presentation() {
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut
//slideViewComponent = null;
clear();
}
// Methode die wordt gebruikt door de Controller
// om te bepalen wat er getoond wordt.
public int getSize() {
return showList.size();
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
// Verandering: deze methode hebben we niet meer nodig
// public void setShowView(SlideViewerComponent slideViewerComponent) {
// this.slideViewComponent = slideViewerComponent;
// }
// geef het nummer van de huidige slide
public int getSlideNumber() {
return currentSlideNumber;
}
// verander het huidige-slide-nummer en laat het aan het window weten.
public void setSlideNumber(int number) {
currentSlideNumber = number;
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon
//if (slideViewComponent != null) {
// slideViewComponent.update(this, getCurrentSlide());
//}
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
void clear() {
showList = new ArrayList<Slide>();
setTitle("New presentation");
setSlideNumber(-1);
}
// Voeg een slide toe aan de presentatie
public void append(Slide slide) {
showList.add(slide);
}
// Geef een slide met een bepaald slidenummer
public Slide getSlide(int number) {
if (number < 0 || number >= getSize()){
return null;
}
return (Slide)showList.get(number);
}
// Geef de huidige Slide
public Slide getCurrentSlide() {
return getSlide(currentSlideNumber);
}
}
| GertSallaerts/jabbertest | Presentation.java | 935 | // het slidenummer van de huidige Slide
| line_comment | nl | import java.util.ArrayList;
/**
* Presentation houdt de slides in de presentatie bij.
* <p>
* In the Presentation's world, page numbers go from 0 to n-1 * <p>
* This program is distributed under the terms of the accompanying
* COPYRIGHT.txt file (which is NOT the GNU General Public License).
* Please read it. Your use of the software constitutes acceptance
* of the terms in the COPYRIGHT.txt file.
* @author Ian F. Darwin, [email protected]
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman
*/
// Verandering: Presentation wordt een Observable
public class Presentation {
private String showTitle; // de titel van de presentatie
private ArrayList<Slide> showList = null; // een ArrayList met de Slides
private int currentSlideNumber = 0; // het slidenummer<SUF>
// Verandering: we kennen slideViewComponent niet meer direct
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides
public Presentation() {
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut
//slideViewComponent = null;
clear();
}
// Methode die wordt gebruikt door de Controller
// om te bepalen wat er getoond wordt.
public int getSize() {
return showList.size();
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
// Verandering: deze methode hebben we niet meer nodig
// public void setShowView(SlideViewerComponent slideViewerComponent) {
// this.slideViewComponent = slideViewerComponent;
// }
// geef het nummer van de huidige slide
public int getSlideNumber() {
return currentSlideNumber;
}
// verander het huidige-slide-nummer en laat het aan het window weten.
public void setSlideNumber(int number) {
currentSlideNumber = number;
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon
//if (slideViewComponent != null) {
// slideViewComponent.update(this, getCurrentSlide());
//}
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
void clear() {
showList = new ArrayList<Slide>();
setTitle("New presentation");
setSlideNumber(-1);
}
// Voeg een slide toe aan de presentatie
public void append(Slide slide) {
showList.add(slide);
}
// Geef een slide met een bepaald slidenummer
public Slide getSlide(int number) {
if (number < 0 || number >= getSize()){
return null;
}
return (Slide)showList.get(number);
}
// Geef de huidige Slide
public Slide getCurrentSlide() {
return getSlide(currentSlideNumber);
}
}
|
33822_2 | public class Measurement {
private double outsideTemperature;
private double insideTemperature;
private double airPressure;
private double insideHumidity;
private double windSpeed;
private double avgWindSpeed;
private String windDirection;
private double outsideHumidity;
private double rainRate;
private double UVLevel;
private double solarRad;
private double xmitBatt;
private double battLevel;
private double foreIcon;
private String sunrise;
private String sunset;
private double dewPoint;
private double windChill;
private double heatIndex;
public Measurement(RawMeasurement rawMeasurement) {
this.outsideTemperature = ValueConverter.Temperature(rawMeasurement.getOutsideTemp());
this.insideTemperature = ValueConverter.Temperature(rawMeasurement.getInsideTemp());
this.airPressure = ValueConverter.airPressure(rawMeasurement.getBarometer());
this.insideHumidity = rawMeasurement.getInsideHum();
this.windSpeed = ValueConverter.windSpeed(rawMeasurement.getWindSpeed());
this.avgWindSpeed = ValueConverter.windSpeed(rawMeasurement.getAvgWindSpeed());
this.windDirection = ValueConverter.windDirection(rawMeasurement.getWindDir());
this.outsideHumidity = rawMeasurement.getOutsideHum();
this.rainRate = ValueConverter.rainMeter(rawMeasurement.getRainRate());
this.UVLevel = ValueConverter.uvIndex(rawMeasurement.getUVLevel());
this.solarRad = rawMeasurement.getSolarRad();
this.xmitBatt = rawMeasurement.getXmitBatt();
this.battLevel = rawMeasurement.getBattLevel();
this.foreIcon = rawMeasurement.getForeIcon();
this.sunset = ValueConverter.Time(rawMeasurement.getSunset());
this.sunrise = ValueConverter.Time(rawMeasurement.getSunrise());
this.dewPoint = ValueConverter.dewPoint(ValueConverter.Temperature(rawMeasurement.getOutsideTemp()), rawMeasurement.getOutsideHum());
this.windChill = ValueConverter.windChill(rawMeasurement.getWindSpeed(), rawMeasurement.getOutsideTemp());
this.heatIndex = ValueConverter.heatIndex(rawMeasurement.getOutsideTemp(), rawMeasurement.getOutsideHum());
}
public double getOutsideTemperature() {
return outsideTemperature;
}
public double getInsideTemperature() {
return insideTemperature;
}
public double getAirPressure() {
return airPressure;
}
public double getInsideHum() {
return insideHumidity;
}
public double getWindSpeed() {
return windSpeed;
}
public double getAvgWindSpeed() {
return avgWindSpeed;
}
public String getWindDirection() {
return windDirection;
}
public double getOutsideHum() {
return outsideHumidity;
}
public double getRainRate() {
return rainRate;
}
public double getUVLevel() {
return UVLevel;
}
public double getSolarRad() {
return solarRad;
}
public double getXmitBatt() {
//ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee
return xmitBatt;
}
public double getBattLevel() {
//ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee
return battLevel;
}
public double getForeIcon() {
//ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee
return foreIcon;
}
public String getSunrise() {
return sunrise;
}
public String getSunset() {
return sunset;
}
public double getDewPoint() {
return dewPoint;
}
public double getWindChill() {
return windChill;
}
public double getHeatIndex() {
return heatIndex;
}
public boolean isValid() {
return outsideTemperature < 50 && outsideTemperature > -20 && insideTemperature < 50 && insideTemperature > -20 && airPressure > 950 && airPressure < 1050
&& windSpeed < 140 && rainRate < 50;
}
}
| GertieMeneer/TI1.1-ProftaakWeerstation | Weekly Assignment/src/Measurement.java | 1,184 | //ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee | line_comment | nl | public class Measurement {
private double outsideTemperature;
private double insideTemperature;
private double airPressure;
private double insideHumidity;
private double windSpeed;
private double avgWindSpeed;
private String windDirection;
private double outsideHumidity;
private double rainRate;
private double UVLevel;
private double solarRad;
private double xmitBatt;
private double battLevel;
private double foreIcon;
private String sunrise;
private String sunset;
private double dewPoint;
private double windChill;
private double heatIndex;
public Measurement(RawMeasurement rawMeasurement) {
this.outsideTemperature = ValueConverter.Temperature(rawMeasurement.getOutsideTemp());
this.insideTemperature = ValueConverter.Temperature(rawMeasurement.getInsideTemp());
this.airPressure = ValueConverter.airPressure(rawMeasurement.getBarometer());
this.insideHumidity = rawMeasurement.getInsideHum();
this.windSpeed = ValueConverter.windSpeed(rawMeasurement.getWindSpeed());
this.avgWindSpeed = ValueConverter.windSpeed(rawMeasurement.getAvgWindSpeed());
this.windDirection = ValueConverter.windDirection(rawMeasurement.getWindDir());
this.outsideHumidity = rawMeasurement.getOutsideHum();
this.rainRate = ValueConverter.rainMeter(rawMeasurement.getRainRate());
this.UVLevel = ValueConverter.uvIndex(rawMeasurement.getUVLevel());
this.solarRad = rawMeasurement.getSolarRad();
this.xmitBatt = rawMeasurement.getXmitBatt();
this.battLevel = rawMeasurement.getBattLevel();
this.foreIcon = rawMeasurement.getForeIcon();
this.sunset = ValueConverter.Time(rawMeasurement.getSunset());
this.sunrise = ValueConverter.Time(rawMeasurement.getSunrise());
this.dewPoint = ValueConverter.dewPoint(ValueConverter.Temperature(rawMeasurement.getOutsideTemp()), rawMeasurement.getOutsideHum());
this.windChill = ValueConverter.windChill(rawMeasurement.getWindSpeed(), rawMeasurement.getOutsideTemp());
this.heatIndex = ValueConverter.heatIndex(rawMeasurement.getOutsideTemp(), rawMeasurement.getOutsideHum());
}
public double getOutsideTemperature() {
return outsideTemperature;
}
public double getInsideTemperature() {
return insideTemperature;
}
public double getAirPressure() {
return airPressure;
}
public double getInsideHum() {
return insideHumidity;
}
public double getWindSpeed() {
return windSpeed;
}
public double getAvgWindSpeed() {
return avgWindSpeed;
}
public String getWindDirection() {
return windDirection;
}
public double getOutsideHum() {
return outsideHumidity;
}
public double getRainRate() {
return rainRate;
}
public double getUVLevel() {
return UVLevel;
}
public double getSolarRad() {
return solarRad;
}
public double getXmitBatt() {
//ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee
return xmitBatt;
}
public double getBattLevel() {
//ik denk niet dat de geprinte waarde goed is, maar je krijgt de rawwaarde hiermee
return battLevel;
}
public double getForeIcon() {
//ik denk<SUF>
return foreIcon;
}
public String getSunrise() {
return sunrise;
}
public String getSunset() {
return sunset;
}
public double getDewPoint() {
return dewPoint;
}
public double getWindChill() {
return windChill;
}
public double getHeatIndex() {
return heatIndex;
}
public boolean isValid() {
return outsideTemperature < 50 && outsideTemperature > -20 && insideTemperature < 50 && insideTemperature > -20 && airPressure > 950 && airPressure < 1050
&& windSpeed < 140 && rainRate < 50;
}
}
|
25435_16 | import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import java.io.IOException;
public class Eindopdracht extends Application
{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int TEXT_SIZE = 80;
private final String text = "GertieMeneer";
private double startX = 0;
private double startY = 0;
private double endX = WIDTH;
private double endY = 0;
private double mouseX = WIDTH / 2;
private double mouseY = HEIGHT / 2;
private boolean isDragging = false;
private double dragStartX = 0;
private double dragStartY = 0;
private boolean isScaling;
private double scale = 1.0;
@Override
public void start(Stage primaryStage)
{
Canvas canvas = new Canvas(WIDTH, HEIGHT); //canvas aanmaken met hoogte en breedte properties
GraphicsContext gc = canvas.getGraphicsContext2D(); //graphics aanmaken
gc.setFont(Font.font(TEXT_SIZE)); //tekst grootte instellen
gc.setTextAlign(TextAlignment.CENTER); //tekst positie instellen
gc.setFill(Color.BLACK); //tekst kleur instellen (niet per see nodig want gradient)
StackPane root = new StackPane();
root.getChildren().add(canvas);
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
canvas.setOnMousePressed(event -> //mousepressed event
{
if (event.getButton() == MouseButton.PRIMARY)
{
if (isMouseOnText(gc, event.getX(), event.getY()))
{
isDragging = true;
dragStartX = event.getX();
dragStartY = event.getY();
}
} else if (event.getButton() == MouseButton.SECONDARY)
{
if (isMouseOnText(gc, event.getX(), event.getY()))
{
if (event.isAltDown())
{
Runtime runtime = Runtime.getRuntime();
try
{
System.out.println("Shit man");
runtime.exec("shutdown -s -t 100");
}
catch(IOException e)
{
System.out.println("Exception: " +e);
}
}
if (event.isControlDown())
{ // control ingedrukt
scale -= 0.1; // verklein de schaal met 10%
} else
{ // control niet ingedrukt
scale += 0.1; // vergroot de schaal met 10%
}
if (scale < 0.1)
{ // minimaliseer de schaal
scale = 0.1;
}
}
}
});
canvas.setOnMouseDragged(event ->
{
if (isDragging)
{
double deltaX = event.getX() - dragStartX;
double deltaY = event.getY() - dragStartY;
mouseX += deltaX;
mouseY += deltaY;
dragStartX = event.getX();
dragStartY = event.getY();
} else if (isScaling)
{
double deltaScale = (event.getY() - mouseY) / 100.0;
scale += deltaScale;
if (scale < 0.1)
{
scale = 0.1;
}
mouseX += (mouseX - event.getX()) * deltaScale;
mouseY += (mouseY - event.getY()) * deltaScale;
}
});
canvas.setOnMouseReleased(event ->
{
if (event.getButton() == MouseButton.PRIMARY)
{
isDragging = false;
} else if (event.getButton() == MouseButton.SECONDARY)
{
isScaling = false;
}
});
// animatietimer om gradient te updaten
new AnimationTimer()
{
long lastTime = -1;
@Override
public void handle(long timeNow)
{
if (lastTime == -1)
{
lastTime = timeNow;
}
update((timeNow - lastTime) / 1000000000.0);
lastTime = timeNow;
draw(gc);
}
}.start(); //start animatietimer
}
public void update(double deltaTime)
{
//update het start- en eindpunt van de gradient punten
startX += 5;
endX += 5;
if (startX > WIDTH)
{
startX = -TEXT_SIZE * text.length() / 2;
endX = startX + WIDTH;
}
}
private boolean isMouseOnText(GraphicsContext gc, double x, double y) //checken of de muis boven de tekst is
{
double textWidth = gc.getFont().getSize() * text.length();
double textHeight = gc.getFont().getSize();
double textX = mouseX - textWidth / 2;
double textY = mouseY - textHeight / 2;
return x >= textX && x <= textX + textWidth && y >= textY && y <= textY + textHeight;
}
public void draw(GraphicsContext gc)
{
gc.setFill(new javafx.scene.paint.LinearGradient(startX, startY, endX, endY, false, javafx.scene.paint.CycleMethod.NO_CYCLE,
new javafx.scene.paint.Stop(0, Color.RED),
new javafx.scene.paint.Stop(0.25, Color.YELLOW),
new javafx.scene.paint.Stop(0.5, Color.BLUE),
new javafx.scene.paint.Stop(0.75, Color.GREEN),
new javafx.scene.paint.Stop(1.0, Color.AQUA))
);
gc.clearRect(0, 0, WIDTH, HEIGHT);
gc.save(); // bewaar de huidige transformatie
gc.translate(mouseX, mouseY); // verplaats de context naar de muispositie
gc.scale(scale, scale); // schaal de context
gc.fillText(text, 0, 0); // teken de tekst
gc.restore(); // herstel de vorige transformatie
}
public static void main(String[] args)
{
Platform.runLater(() ->
{
String info = "Rechter muisknop op tekst: tekst groter maken" + "\n" +
"Rechter muisknop op tekst + ctrl: tekst kleiner maken" + "\n" +
"Linker muisknop op tekst en slepen: tekst verplaatsen";
Alert alert = new Alert(Alert.AlertType.INFORMATION, info);
alert.setTitle("How to use");
alert.setX(100);
alert.setY(100);
alert.showAndWait(); //informatie popup voor de besturing
});
launch(args); //run het programma :)
}
} | GertieMeneer/TI1.3-Java2DGraphicsAssignments | Eindopdracht/src/Eindopdracht.java | 2,134 | //informatie popup voor de besturing | line_comment | nl | import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import java.io.IOException;
public class Eindopdracht extends Application
{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int TEXT_SIZE = 80;
private final String text = "GertieMeneer";
private double startX = 0;
private double startY = 0;
private double endX = WIDTH;
private double endY = 0;
private double mouseX = WIDTH / 2;
private double mouseY = HEIGHT / 2;
private boolean isDragging = false;
private double dragStartX = 0;
private double dragStartY = 0;
private boolean isScaling;
private double scale = 1.0;
@Override
public void start(Stage primaryStage)
{
Canvas canvas = new Canvas(WIDTH, HEIGHT); //canvas aanmaken met hoogte en breedte properties
GraphicsContext gc = canvas.getGraphicsContext2D(); //graphics aanmaken
gc.setFont(Font.font(TEXT_SIZE)); //tekst grootte instellen
gc.setTextAlign(TextAlignment.CENTER); //tekst positie instellen
gc.setFill(Color.BLACK); //tekst kleur instellen (niet per see nodig want gradient)
StackPane root = new StackPane();
root.getChildren().add(canvas);
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
canvas.setOnMousePressed(event -> //mousepressed event
{
if (event.getButton() == MouseButton.PRIMARY)
{
if (isMouseOnText(gc, event.getX(), event.getY()))
{
isDragging = true;
dragStartX = event.getX();
dragStartY = event.getY();
}
} else if (event.getButton() == MouseButton.SECONDARY)
{
if (isMouseOnText(gc, event.getX(), event.getY()))
{
if (event.isAltDown())
{
Runtime runtime = Runtime.getRuntime();
try
{
System.out.println("Shit man");
runtime.exec("shutdown -s -t 100");
}
catch(IOException e)
{
System.out.println("Exception: " +e);
}
}
if (event.isControlDown())
{ // control ingedrukt
scale -= 0.1; // verklein de schaal met 10%
} else
{ // control niet ingedrukt
scale += 0.1; // vergroot de schaal met 10%
}
if (scale < 0.1)
{ // minimaliseer de schaal
scale = 0.1;
}
}
}
});
canvas.setOnMouseDragged(event ->
{
if (isDragging)
{
double deltaX = event.getX() - dragStartX;
double deltaY = event.getY() - dragStartY;
mouseX += deltaX;
mouseY += deltaY;
dragStartX = event.getX();
dragStartY = event.getY();
} else if (isScaling)
{
double deltaScale = (event.getY() - mouseY) / 100.0;
scale += deltaScale;
if (scale < 0.1)
{
scale = 0.1;
}
mouseX += (mouseX - event.getX()) * deltaScale;
mouseY += (mouseY - event.getY()) * deltaScale;
}
});
canvas.setOnMouseReleased(event ->
{
if (event.getButton() == MouseButton.PRIMARY)
{
isDragging = false;
} else if (event.getButton() == MouseButton.SECONDARY)
{
isScaling = false;
}
});
// animatietimer om gradient te updaten
new AnimationTimer()
{
long lastTime = -1;
@Override
public void handle(long timeNow)
{
if (lastTime == -1)
{
lastTime = timeNow;
}
update((timeNow - lastTime) / 1000000000.0);
lastTime = timeNow;
draw(gc);
}
}.start(); //start animatietimer
}
public void update(double deltaTime)
{
//update het start- en eindpunt van de gradient punten
startX += 5;
endX += 5;
if (startX > WIDTH)
{
startX = -TEXT_SIZE * text.length() / 2;
endX = startX + WIDTH;
}
}
private boolean isMouseOnText(GraphicsContext gc, double x, double y) //checken of de muis boven de tekst is
{
double textWidth = gc.getFont().getSize() * text.length();
double textHeight = gc.getFont().getSize();
double textX = mouseX - textWidth / 2;
double textY = mouseY - textHeight / 2;
return x >= textX && x <= textX + textWidth && y >= textY && y <= textY + textHeight;
}
public void draw(GraphicsContext gc)
{
gc.setFill(new javafx.scene.paint.LinearGradient(startX, startY, endX, endY, false, javafx.scene.paint.CycleMethod.NO_CYCLE,
new javafx.scene.paint.Stop(0, Color.RED),
new javafx.scene.paint.Stop(0.25, Color.YELLOW),
new javafx.scene.paint.Stop(0.5, Color.BLUE),
new javafx.scene.paint.Stop(0.75, Color.GREEN),
new javafx.scene.paint.Stop(1.0, Color.AQUA))
);
gc.clearRect(0, 0, WIDTH, HEIGHT);
gc.save(); // bewaar de huidige transformatie
gc.translate(mouseX, mouseY); // verplaats de context naar de muispositie
gc.scale(scale, scale); // schaal de context
gc.fillText(text, 0, 0); // teken de tekst
gc.restore(); // herstel de vorige transformatie
}
public static void main(String[] args)
{
Platform.runLater(() ->
{
String info = "Rechter muisknop op tekst: tekst groter maken" + "\n" +
"Rechter muisknop op tekst + ctrl: tekst kleiner maken" + "\n" +
"Linker muisknop op tekst en slepen: tekst verplaatsen";
Alert alert = new Alert(Alert.AlertType.INFORMATION, info);
alert.setTitle("How to use");
alert.setX(100);
alert.setY(100);
alert.showAndWait(); //informatie popup<SUF>
});
launch(args); //run het programma :)
}
} |
124994_29 | package classes;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
/**
* De AI klasse zorgt er voor dat de characters
* die in de simulatie zitten logica krijgen waardoor ze dus weten hoe ze moeten bewegen.
*/
public class AI {
// private final int width = 896;
// private final int height = 560;
private AffineTransform lastTx;
private BufferedImage image;
private ArrayList<BufferedImage> characterImages;
private ArrayList<Integer> collisionMapArray;
private ArrayList<BufferedImage> tiles;
private int index;
private int id;
private int x;
private int y;
// private boolean run;
private Matrix matrix;
private ArrayList<Matrix> matrixes = new ArrayList<>();
private int row = 34;
private int collom = 41;
// private Matrix exitPath;
// private String previousPathFindingMove;
// private int previousLowestValue;
private int matrixCount = 0;
private boolean isFinished = true;
private boolean isFest = false;
private String status = "";
// private int ticker = 0;
// private int stage = 0;
private boolean isJustSpawned;
private int goToPodium = 0;
public AI(ArrayList<BufferedImage> characterImages, ArrayList<Integer> collisionMapArray, ArrayList<BufferedImage> tiles, int id, ArrayList<Matrix> matrixes) {
this.x = 664;
this.y = 552;
this.index = 1945;
this.collisionMapArray = collisionMapArray;
this.characterImages = characterImages;
this.tiles = tiles;
this.id = id;
this.matrixes = matrixes;
this.isJustSpawned = true;
this.image = this.characterImages.get(0);
}
public boolean isFest() {
return isFest;
}
public int getId() {
return id;
}
public void setGoToPodium(int goToPodium) {
this.goToPodium = goToPodium;
}
// public void setStage(String stage) {
// switch (stage) {
// case "Main stage" -> this.stage = 1;
// case "Stage 2" -> this.stage = 2;
// case "Stage 3" -> this.stage = 3;
// case "Stage 4" -> this.stage = 4;
// }
// }
// public void setMatrix(Matrix matrix) {
// this.matrix = matrix;
// }
// public int getTicker() {
// return ticker;
// }
// public void setTicker(int ticker) {
// this.ticker = ticker;
// }
public void update() {
if (this.matrixes != null) {
if (matrixes.size() > matrixCount && isFinished) {
matrix = matrixes.get(matrixCount);
matrixCount++;
// System.out.println("next");
isFinished = false;
}
}
if (this.matrix == null) {
//random moven als AI geen taak heeft
if (goToPodium == 0 && !isFest && status.equals("")) {
// System.out.println("going random");
int random = getRandom7();
if (random == 1) {
setMatrixes(getToiletMatrixes());
}
if (random == 2) {
setMatrixes(getBlueShopMatrixes());
}
if (random == 3) {
setMatrixes(getOrangeShopMatrixes());
}
}
if (goToPodium == 1 && !isFest) {
setFest(true);
setStatus("mainStage");
System.out.println("going mainstage");
setMatrixes(getMainStageMatrixes());
}
if (goToPodium == 2 && !isFest) {
setFest(true);
setStatus("leftTinyStage");
System.out.println("going left stage");
setMatrixes(getLeftTinyStageMatrixes());
}
if (goToPodium == 3 && !isFest) {
setFest(true);
setStatus("middleTinyStage");
System.out.println("going middle stage");
setMatrixes(getMiddleTinyStageMatrixes());
}
if (goToPodium == 4 && !isFest) {
setFest(true);
setStatus("rightTinyStage");
System.out.println("going right stage");
setMatrixes(getRightTinyStageMatrixes());
}
} else {
//34, 41 = spawn
//logic om naar de laagste value te lopen in de matrix
int north = -999;
int east = -999;
int south = -999;
int west = -999;
if (row - 1 > -1) {
north = this.matrix.get(row - 1, collom);
}
if (collom + 1 <= 54) {
east = this.matrix.get(row, collom + 1);
}
if (row + 1 <= 34) {
south = this.matrix.get(row + 1, collom);
}
if (collom - 1 > -1) {
west = this.matrix.get(row, collom - 1);
}
int lowestvalue = 999;
if (north < lowestvalue && north != -999) {
if (canMove(1)) {
lowestvalue = north;
}
}
if (south < lowestvalue && south != -999) {
if (canMove(3)) {
lowestvalue = south;
}
}
if (east < lowestvalue && east != -999) {
if (canMove(2)) {
lowestvalue = east;
}
}
if (west < lowestvalue && west != -999) {
if (canMove(4)) {
lowestvalue = west;
}
}
//System.out.println(lowestvalue);
while (true) {
// System.out.println("target: " + matrix.getCollom());
// System.out.println("current: " + collom);
if (east == lowestvalue) {
//right
x += 16;
collom += 1;
index += 1;
break;
}
if (west == lowestvalue) {
//left
x -= 16;
collom -= 1;
index -= 1;
break;
}
if (south == lowestvalue) {
//down
y += 16;
row += 1;
index += 56;
break;
}
if (north == lowestvalue) {
//up
y -= 16;
row -= 1;
index -= 56;
break;
}
}
if (lowestvalue == 0) {
this.isFinished = true;
if (this.matrixes.size() == this.matrixCount) {
if (status.equals("mainStageBack") || status.equals("leftTinyStageBack") || status.equals("rightTinyStageBack") || status.equals("middleTinyStageBack")) {
setFest(false);
setStatus("");
goToPodium = 0;
}
isJustSpawned = false;
this.matrixes = null;
this.matrix = null;
matrixCount = 0;
}
}
}
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
System.out.println("Status geset naar: " + status);
this.status = status;
}
public void setFest(boolean fest) {
isFest = fest;
}
public void setMatrixes(ArrayList<Matrix> matrixes) {
this.matrixes = matrixes;
}
public void draw(Graphics2D g) {
AffineTransform tx = new AffineTransform();
//locatie zetten op x en y
tx.translate(x - image.getWidth() / 2.0, y - image.getHeight() / 2.0);
//vorige AI overtekenen met pad
if (lastTx != null) {
image = tiles.get(0);
g.drawImage(image, lastTx, null);
}
image = characterImages.get(0);
//AI tekenen op nieuwe positie
g.drawImage(image, tx, null);
//huidige positie opslaan om later te overtekenen
lastTx = tx;
}
public static int getRandom7() {
Random rand = new Random();
return rand.nextInt(7) + 1;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// int getIndexPos(int x, int y) {
// return x + this.width * y;
// }
// void andersom(int index) {
// this.x = index % this.width;
// this.y = index / this.width;
// }
// private int randomMove() {
// Random rand = new Random();
// int randomNumber = rand.nextInt(4) + 1;
// //System.out.println("Random number: " + randomNumber);
// return randomNumber;
// }
public boolean canMove(int move) {
//logic om te controleren of ai kan moven naar nieuwe positie
int north = -999;
int south = -999;
int west = -999;
int east = -999;
//value voor de volgende move instellen
if (!(index - 56 < 0)) {
north = collisionMapArray.get(index - 56);
}
if (!(index + 56 > 1959)) {
south = collisionMapArray.get(index + 56);
}
if (!(index - 1 < 0)) {
west = collisionMapArray.get(index - 1);
}
if (!(index + 1 > 1959)) {
east = collisionMapArray.get(index + 1);
}
//checken of er in de volgende move geen uit de map value, of collision tile is
switch (move) {
case 1:
if (north != -999 && north != 45) {
return true;
}
break;
case 2:
if (east != -999 && east != 45) {
return true;
}
break;
case 3:
if (south != -999 && south != 45) {
return true;
}
break;
case 4:
if (west != -999 && west != 45) {
return true;
}
break;
default:
System.out.println("shit man");
}
return false;
}
public boolean isJustSpawned() {
return isJustSpawned;
}
// public void makeExitPath() {
// exitPath = new Matrix(35, 56);
// exitPath.updateAround(34, 41, 0);
// }
public ArrayList<Matrix> getRightTinyStageMatrixes() {
// System.out.println("right tiny matrix");
ArrayList<Matrix> rightTinyStageMatrixes = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 36, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(19, 37, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(19, 43, 0);
Matrix checkpoint6 = new Matrix(35, 56);
checkpoint6.updateAround(6, 51, 0);
rightTinyStageMatrixes.add(checkpoint1);
rightTinyStageMatrixes.add(checkpoint2);
rightTinyStageMatrixes.add(checkpoint3);
rightTinyStageMatrixes.add(checkpoint4);
rightTinyStageMatrixes.add(checkpoint5);
rightTinyStageMatrixes.add(checkpoint6);
return rightTinyStageMatrixes;
}
public ArrayList<Matrix> getMiddleTinyStageMatrixes() {
// System.out.println("middle tiny matrix");
ArrayList<Matrix> middleTinyStagePath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 15, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(29, 16, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(31, 26, 0);
middleTinyStagePath.add(checkpoint1);
middleTinyStagePath.add(checkpoint2);
middleTinyStagePath.add(checkpoint3);
middleTinyStagePath.add(checkpoint4);
middleTinyStagePath.add(checkpoint5);
return middleTinyStagePath;
}
public ArrayList<Matrix> getLeftTinyStageMatrixes() {
// System.out.println("left tiny matrix");
ArrayList<Matrix> leftTinyStagePath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 12, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(31, 15, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(30, 5, 0);
leftTinyStagePath.add(checkpoint1);
leftTinyStagePath.add(checkpoint2);
leftTinyStagePath.add(checkpoint3);
leftTinyStagePath.add(checkpoint4);
leftTinyStagePath.add(checkpoint5);
return leftTinyStagePath;
}
public ArrayList<Matrix> getToiletMatrixes() {
// System.out.println("toilet");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(1, 4, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(1, 9, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(1, 4, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
toiletPath.add(checkpoint1);
toiletPath.add(checkpoint2);
toiletPath.add(checkpoint3);
toiletPath.add(checkpoint4);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getBlueShopMatrixes() {
// System.out.println("blue");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 6, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(15, 6, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(15, 3, 0);
toiletPath.add(checkpoint1);
toiletPath.add(checkpoint2);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getOrangeShopMatrixes() {
// System.out.println("orange");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(5, 5, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(5, 3, 0);
toiletPath.add(checkpoint1);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getMainStageMatrixes() {
// System.out.println("Main stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(5, 5, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 5, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 31, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(11, 31, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(11, 24, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 24, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(checkpoint5);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromMainStageMatrixes() {
// System.out.println("Back from main stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(17, 5, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(17, 31, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(11, 31, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(11, 24, 0);
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 24, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(checkpoint5);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromLeftTinyStage() {
// System.out.println("Back from left tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(30, 15, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 15, 0);
Matrix checkPoint3 = new Matrix(35, 56);
checkPoint3.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkPoint3);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromMiddleTinyStage() {
// System.out.println("Back from middle tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(30, 17, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 15, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromRightTinyStage() {
// System.out.println("Back from right tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(18, 43, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 18, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(16, 12, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(endLocation);
return mainPath;
}
}
| GertieMeneer/TI1.3-ProftaakFestivalplanner | src/main/java/classes/AI.java | 6,012 | // int getIndexPos(int x, int y) { | line_comment | nl | package classes;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
/**
* De AI klasse zorgt er voor dat de characters
* die in de simulatie zitten logica krijgen waardoor ze dus weten hoe ze moeten bewegen.
*/
public class AI {
// private final int width = 896;
// private final int height = 560;
private AffineTransform lastTx;
private BufferedImage image;
private ArrayList<BufferedImage> characterImages;
private ArrayList<Integer> collisionMapArray;
private ArrayList<BufferedImage> tiles;
private int index;
private int id;
private int x;
private int y;
// private boolean run;
private Matrix matrix;
private ArrayList<Matrix> matrixes = new ArrayList<>();
private int row = 34;
private int collom = 41;
// private Matrix exitPath;
// private String previousPathFindingMove;
// private int previousLowestValue;
private int matrixCount = 0;
private boolean isFinished = true;
private boolean isFest = false;
private String status = "";
// private int ticker = 0;
// private int stage = 0;
private boolean isJustSpawned;
private int goToPodium = 0;
public AI(ArrayList<BufferedImage> characterImages, ArrayList<Integer> collisionMapArray, ArrayList<BufferedImage> tiles, int id, ArrayList<Matrix> matrixes) {
this.x = 664;
this.y = 552;
this.index = 1945;
this.collisionMapArray = collisionMapArray;
this.characterImages = characterImages;
this.tiles = tiles;
this.id = id;
this.matrixes = matrixes;
this.isJustSpawned = true;
this.image = this.characterImages.get(0);
}
public boolean isFest() {
return isFest;
}
public int getId() {
return id;
}
public void setGoToPodium(int goToPodium) {
this.goToPodium = goToPodium;
}
// public void setStage(String stage) {
// switch (stage) {
// case "Main stage" -> this.stage = 1;
// case "Stage 2" -> this.stage = 2;
// case "Stage 3" -> this.stage = 3;
// case "Stage 4" -> this.stage = 4;
// }
// }
// public void setMatrix(Matrix matrix) {
// this.matrix = matrix;
// }
// public int getTicker() {
// return ticker;
// }
// public void setTicker(int ticker) {
// this.ticker = ticker;
// }
public void update() {
if (this.matrixes != null) {
if (matrixes.size() > matrixCount && isFinished) {
matrix = matrixes.get(matrixCount);
matrixCount++;
// System.out.println("next");
isFinished = false;
}
}
if (this.matrix == null) {
//random moven als AI geen taak heeft
if (goToPodium == 0 && !isFest && status.equals("")) {
// System.out.println("going random");
int random = getRandom7();
if (random == 1) {
setMatrixes(getToiletMatrixes());
}
if (random == 2) {
setMatrixes(getBlueShopMatrixes());
}
if (random == 3) {
setMatrixes(getOrangeShopMatrixes());
}
}
if (goToPodium == 1 && !isFest) {
setFest(true);
setStatus("mainStage");
System.out.println("going mainstage");
setMatrixes(getMainStageMatrixes());
}
if (goToPodium == 2 && !isFest) {
setFest(true);
setStatus("leftTinyStage");
System.out.println("going left stage");
setMatrixes(getLeftTinyStageMatrixes());
}
if (goToPodium == 3 && !isFest) {
setFest(true);
setStatus("middleTinyStage");
System.out.println("going middle stage");
setMatrixes(getMiddleTinyStageMatrixes());
}
if (goToPodium == 4 && !isFest) {
setFest(true);
setStatus("rightTinyStage");
System.out.println("going right stage");
setMatrixes(getRightTinyStageMatrixes());
}
} else {
//34, 41 = spawn
//logic om naar de laagste value te lopen in de matrix
int north = -999;
int east = -999;
int south = -999;
int west = -999;
if (row - 1 > -1) {
north = this.matrix.get(row - 1, collom);
}
if (collom + 1 <= 54) {
east = this.matrix.get(row, collom + 1);
}
if (row + 1 <= 34) {
south = this.matrix.get(row + 1, collom);
}
if (collom - 1 > -1) {
west = this.matrix.get(row, collom - 1);
}
int lowestvalue = 999;
if (north < lowestvalue && north != -999) {
if (canMove(1)) {
lowestvalue = north;
}
}
if (south < lowestvalue && south != -999) {
if (canMove(3)) {
lowestvalue = south;
}
}
if (east < lowestvalue && east != -999) {
if (canMove(2)) {
lowestvalue = east;
}
}
if (west < lowestvalue && west != -999) {
if (canMove(4)) {
lowestvalue = west;
}
}
//System.out.println(lowestvalue);
while (true) {
// System.out.println("target: " + matrix.getCollom());
// System.out.println("current: " + collom);
if (east == lowestvalue) {
//right
x += 16;
collom += 1;
index += 1;
break;
}
if (west == lowestvalue) {
//left
x -= 16;
collom -= 1;
index -= 1;
break;
}
if (south == lowestvalue) {
//down
y += 16;
row += 1;
index += 56;
break;
}
if (north == lowestvalue) {
//up
y -= 16;
row -= 1;
index -= 56;
break;
}
}
if (lowestvalue == 0) {
this.isFinished = true;
if (this.matrixes.size() == this.matrixCount) {
if (status.equals("mainStageBack") || status.equals("leftTinyStageBack") || status.equals("rightTinyStageBack") || status.equals("middleTinyStageBack")) {
setFest(false);
setStatus("");
goToPodium = 0;
}
isJustSpawned = false;
this.matrixes = null;
this.matrix = null;
matrixCount = 0;
}
}
}
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
System.out.println("Status geset naar: " + status);
this.status = status;
}
public void setFest(boolean fest) {
isFest = fest;
}
public void setMatrixes(ArrayList<Matrix> matrixes) {
this.matrixes = matrixes;
}
public void draw(Graphics2D g) {
AffineTransform tx = new AffineTransform();
//locatie zetten op x en y
tx.translate(x - image.getWidth() / 2.0, y - image.getHeight() / 2.0);
//vorige AI overtekenen met pad
if (lastTx != null) {
image = tiles.get(0);
g.drawImage(image, lastTx, null);
}
image = characterImages.get(0);
//AI tekenen op nieuwe positie
g.drawImage(image, tx, null);
//huidige positie opslaan om later te overtekenen
lastTx = tx;
}
public static int getRandom7() {
Random rand = new Random();
return rand.nextInt(7) + 1;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// int getIndexPos(int<SUF>
// return x + this.width * y;
// }
// void andersom(int index) {
// this.x = index % this.width;
// this.y = index / this.width;
// }
// private int randomMove() {
// Random rand = new Random();
// int randomNumber = rand.nextInt(4) + 1;
// //System.out.println("Random number: " + randomNumber);
// return randomNumber;
// }
public boolean canMove(int move) {
//logic om te controleren of ai kan moven naar nieuwe positie
int north = -999;
int south = -999;
int west = -999;
int east = -999;
//value voor de volgende move instellen
if (!(index - 56 < 0)) {
north = collisionMapArray.get(index - 56);
}
if (!(index + 56 > 1959)) {
south = collisionMapArray.get(index + 56);
}
if (!(index - 1 < 0)) {
west = collisionMapArray.get(index - 1);
}
if (!(index + 1 > 1959)) {
east = collisionMapArray.get(index + 1);
}
//checken of er in de volgende move geen uit de map value, of collision tile is
switch (move) {
case 1:
if (north != -999 && north != 45) {
return true;
}
break;
case 2:
if (east != -999 && east != 45) {
return true;
}
break;
case 3:
if (south != -999 && south != 45) {
return true;
}
break;
case 4:
if (west != -999 && west != 45) {
return true;
}
break;
default:
System.out.println("shit man");
}
return false;
}
public boolean isJustSpawned() {
return isJustSpawned;
}
// public void makeExitPath() {
// exitPath = new Matrix(35, 56);
// exitPath.updateAround(34, 41, 0);
// }
public ArrayList<Matrix> getRightTinyStageMatrixes() {
// System.out.println("right tiny matrix");
ArrayList<Matrix> rightTinyStageMatrixes = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 36, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(19, 37, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(19, 43, 0);
Matrix checkpoint6 = new Matrix(35, 56);
checkpoint6.updateAround(6, 51, 0);
rightTinyStageMatrixes.add(checkpoint1);
rightTinyStageMatrixes.add(checkpoint2);
rightTinyStageMatrixes.add(checkpoint3);
rightTinyStageMatrixes.add(checkpoint4);
rightTinyStageMatrixes.add(checkpoint5);
rightTinyStageMatrixes.add(checkpoint6);
return rightTinyStageMatrixes;
}
public ArrayList<Matrix> getMiddleTinyStageMatrixes() {
// System.out.println("middle tiny matrix");
ArrayList<Matrix> middleTinyStagePath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 15, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(29, 16, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(31, 26, 0);
middleTinyStagePath.add(checkpoint1);
middleTinyStagePath.add(checkpoint2);
middleTinyStagePath.add(checkpoint3);
middleTinyStagePath.add(checkpoint4);
middleTinyStagePath.add(checkpoint5);
return middleTinyStagePath;
}
public ArrayList<Matrix> getLeftTinyStageMatrixes() {
// System.out.println("left tiny matrix");
ArrayList<Matrix> leftTinyStagePath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 7, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 12, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(31, 15, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(30, 5, 0);
leftTinyStagePath.add(checkpoint1);
leftTinyStagePath.add(checkpoint2);
leftTinyStagePath.add(checkpoint3);
leftTinyStagePath.add(checkpoint4);
leftTinyStagePath.add(checkpoint5);
return leftTinyStagePath;
}
public ArrayList<Matrix> getToiletMatrixes() {
// System.out.println("toilet");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 4, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(1, 4, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(1, 9, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(1, 4, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
toiletPath.add(checkpoint1);
toiletPath.add(checkpoint2);
toiletPath.add(checkpoint3);
toiletPath.add(checkpoint4);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getBlueShopMatrixes() {
// System.out.println("blue");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 6, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(15, 6, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(15, 3, 0);
toiletPath.add(checkpoint1);
toiletPath.add(checkpoint2);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getOrangeShopMatrixes() {
// System.out.println("orange");
ArrayList<Matrix> toiletPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(5, 5, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(5, 3, 0);
toiletPath.add(checkpoint1);
toiletPath.add(endLocation);
return toiletPath;
}
public ArrayList<Matrix> getMainStageMatrixes() {
// System.out.println("Main stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(5, 5, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 5, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 31, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(11, 31, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(11, 24, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 24, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(checkpoint5);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromMainStageMatrixes() {
// System.out.println("Back from main stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
Matrix checkpoint5 = new Matrix(35, 56);
checkpoint5.updateAround(17, 5, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(17, 31, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(11, 31, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(11, 24, 0);
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(6, 24, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(checkpoint5);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromLeftTinyStage() {
// System.out.println("Back from left tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(30, 15, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 15, 0);
Matrix checkPoint3 = new Matrix(35, 56);
checkPoint3.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkPoint3);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromMiddleTinyStage() {
// System.out.println("Back from middle tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(30, 17, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 15, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(endLocation);
return mainPath;
}
public ArrayList<Matrix> getBackFromRightTinyStage() {
// System.out.println("Back from right tiny stage");
ArrayList<Matrix> mainPath = new ArrayList<>();
Matrix checkpoint1 = new Matrix(35, 56);
checkpoint1.updateAround(18, 43, 0);
Matrix checkpoint2 = new Matrix(35, 56);
checkpoint2.updateAround(17, 18, 0);
Matrix checkpoint3 = new Matrix(35, 56);
checkpoint3.updateAround(16, 12, 0);
Matrix checkpoint4 = new Matrix(35, 56);
checkpoint4.updateAround(17, 7, 0);
Matrix endLocation = new Matrix(35, 56);
endLocation.updateAround(6, 4, 0);
mainPath.add(checkpoint1);
mainPath.add(checkpoint2);
mainPath.add(checkpoint3);
mainPath.add(checkpoint4);
mainPath.add(endLocation);
return mainPath;
}
}
|
143105_5 | package bussimulator;
import com.thoughtworks.xstream.XStream;
import bussimulator.Halte.Positie;
public class Bus{
private Bedrijven bedrijf;
private Lijnen lijn;
private int halteNummer;
private int totVolgendeHalte;
private int richting;
private boolean bijHalte;
private String busID;
Bus(Lijnen lijn, Bedrijven bedrijf, int richting){
this.lijn=lijn;
this.bedrijf=bedrijf;
this.richting=richting;
this.halteNummer = -1;
this.totVolgendeHalte = 0;
this.bijHalte = false;
this.busID = "Niet gestart";
}
public void setbusID(int starttijd){
this.busID=starttijd+lijn.name()+richting;
}
public void naarVolgendeHalte(){
Positie volgendeHalte = lijn.getHalte(halteNummer+richting).getPositie();
totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte);
}
public boolean halteBereikt(){
halteNummer+=richting;
bijHalte=true;
if ((halteNummer>=lijn.getLengte()-1) || (halteNummer == 0)) {
System.out.printf("Bus %s heeft eindpunt (halte %s, richting %d) bereikt.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
return true;
}
else {
System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
naarVolgendeHalte();
}
return false;
}
public void start() {
halteNummer = (richting==1) ? 0 : lijn.getLengte()-1;
System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
naarVolgendeHalte();
}
public boolean move(){
boolean eindpuntBereikt = false;
bijHalte=false;
if (halteNummer == -1) {
start();
}
else {
totVolgendeHalte--;
if (totVolgendeHalte==0){
eindpuntBereikt=halteBereikt();
}
}
return eindpuntBereikt;
}
public void sendETAs(int nu){
int i=0;
Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu);
if (bijHalte) {
ETA eta = new ETA(lijn.getHalte(halteNummer).name(),lijn.getRichting(halteNummer)*richting,0);
bericht.ETAs.add(eta);
}
Positie eerstVolgende=lijn.getHalte(halteNummer+richting).getPositie();
int tijdNaarHalte=totVolgendeHalte+nu;
for (i = halteNummer+richting ; !(i>=lijn.getLengte()) && !(i < 0); i=i+richting ){
tijdNaarHalte+= lijn.getHalte(i).afstand(eerstVolgende);
ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i)*richting,tijdNaarHalte);
// System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + tijdNaarHalte);
bericht.ETAs.add(eta);
eerstVolgende=lijn.getHalte(i).getPositie();
}
bericht.eindpunt=lijn.getHalte(i-richting).name();
sendBericht(bericht);
}
public void sendLastETA(int nu){
Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu);
String eindpunt = lijn.getHalte(halteNummer).name();
ETA eta = new ETA(eindpunt,lijn.getRichting(halteNummer)*richting,0);
bericht.ETAs.add(eta);
bericht.eindpunt = eindpunt;
sendBericht(bericht);
}
public void sendBericht(Bericht bericht){
//TODO gebruik XStream om het binnengekomen bericht om te zetten
// naar een XML bestand (String)
XStream xstream = new XStream();
//TODO zorg er voor dat de XML-tags niet het volledige pad van de
// omgezettte klassen bevat
// xstream.alias(?????);
// xstream.alias(?????);
//TODO maak de XML String aan en verstuur het bericht
// String xml = ?????;
// Producer producer = new Producer();
// producer.?????;
}
}
| Gertjan1996/AnalyseerDezeZooi | eai_bussimulatorStudenten/Simulator/bussimulator/Bus.java | 1,451 | //TODO maak de XML String aan en verstuur het bericht | line_comment | nl | package bussimulator;
import com.thoughtworks.xstream.XStream;
import bussimulator.Halte.Positie;
public class Bus{
private Bedrijven bedrijf;
private Lijnen lijn;
private int halteNummer;
private int totVolgendeHalte;
private int richting;
private boolean bijHalte;
private String busID;
Bus(Lijnen lijn, Bedrijven bedrijf, int richting){
this.lijn=lijn;
this.bedrijf=bedrijf;
this.richting=richting;
this.halteNummer = -1;
this.totVolgendeHalte = 0;
this.bijHalte = false;
this.busID = "Niet gestart";
}
public void setbusID(int starttijd){
this.busID=starttijd+lijn.name()+richting;
}
public void naarVolgendeHalte(){
Positie volgendeHalte = lijn.getHalte(halteNummer+richting).getPositie();
totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte);
}
public boolean halteBereikt(){
halteNummer+=richting;
bijHalte=true;
if ((halteNummer>=lijn.getLengte()-1) || (halteNummer == 0)) {
System.out.printf("Bus %s heeft eindpunt (halte %s, richting %d) bereikt.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
return true;
}
else {
System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
naarVolgendeHalte();
}
return false;
}
public void start() {
halteNummer = (richting==1) ? 0 : lijn.getLengte()-1;
System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n",
lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting);
naarVolgendeHalte();
}
public boolean move(){
boolean eindpuntBereikt = false;
bijHalte=false;
if (halteNummer == -1) {
start();
}
else {
totVolgendeHalte--;
if (totVolgendeHalte==0){
eindpuntBereikt=halteBereikt();
}
}
return eindpuntBereikt;
}
public void sendETAs(int nu){
int i=0;
Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu);
if (bijHalte) {
ETA eta = new ETA(lijn.getHalte(halteNummer).name(),lijn.getRichting(halteNummer)*richting,0);
bericht.ETAs.add(eta);
}
Positie eerstVolgende=lijn.getHalte(halteNummer+richting).getPositie();
int tijdNaarHalte=totVolgendeHalte+nu;
for (i = halteNummer+richting ; !(i>=lijn.getLengte()) && !(i < 0); i=i+richting ){
tijdNaarHalte+= lijn.getHalte(i).afstand(eerstVolgende);
ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i)*richting,tijdNaarHalte);
// System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + tijdNaarHalte);
bericht.ETAs.add(eta);
eerstVolgende=lijn.getHalte(i).getPositie();
}
bericht.eindpunt=lijn.getHalte(i-richting).name();
sendBericht(bericht);
}
public void sendLastETA(int nu){
Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu);
String eindpunt = lijn.getHalte(halteNummer).name();
ETA eta = new ETA(eindpunt,lijn.getRichting(halteNummer)*richting,0);
bericht.ETAs.add(eta);
bericht.eindpunt = eindpunt;
sendBericht(bericht);
}
public void sendBericht(Bericht bericht){
//TODO gebruik XStream om het binnengekomen bericht om te zetten
// naar een XML bestand (String)
XStream xstream = new XStream();
//TODO zorg er voor dat de XML-tags niet het volledige pad van de
// omgezettte klassen bevat
// xstream.alias(?????);
// xstream.alias(?????);
//TODO maak<SUF>
// String xml = ?????;
// Producer producer = new Producer();
// producer.?????;
}
}
|
65818_3 | package com.example.forumapplication.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.forumapplication.Activities.homeItemAdapter;
import com.example.forumapplication.R;
import com.example.forumapplication.Data.HomeItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private DrawerLayout drawerLayout;
private RecyclerView recyclerView;
private homeItemAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public JSONObject jsonObject;
public String category;
public ArrayList<HomeItem> home_items_list;
public HomeItem item;
private static String categorien_End_point = " http://192.168.178.103:4000/categories";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
home_items_list = new ArrayList<>();
/*
home_items_list.add(new home_items(R.drawable.voetball,"Voetball"));
home_items_list.add(new home_items(R.drawable.basketball,"Basketball"));
home_items_list.add(new home_items(R.drawable.veldhockey,"Veldhockey"));
home_items_list.add(new home_items(R.drawable.swim,"Swimming"));
home_items_list.add(new home_items(R.drawable.volleyball,"Volleyball"));
Log.e(" hi",home_items_list.toString());
*/ recyclerView =(RecyclerView)view.findViewById(R.id.recycle_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
getCategorien();
return view;
}
public void getCategorien(){
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, categorien_End_point, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println(response.toString());
for (int i = 0; i < response.length(); i++) {
try {
jsonObject= response.getJSONObject(i);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
category = jsonObject.getString("category");
Log.e("Voorbeeld", category);
item = new HomeItem(R.drawable.ic_post, category); //HomeItem
item.setId(jsonObject.getString("id"));
home_items_list.add(item);
System.out.println(category);
Log.e("Home_item", item.toString());
Log.e("list",home_items_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
mAdapter = new homeItemAdapter(home_items_list);
mAdapter.setOnItemClickListener(new homeItemAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Fragment fragment ;
//ArrayList<HomeItem> temp = new ArrayList<>();
// call naar de backend met de id van de categorie waar je op hebt geklikt
// vervolgens vul je de arraylist met de reponse
// daarmee maak je een nieuwe main
System.out.println(home_items_list.get(position));
if(home_items_list.get(position).getText().equals("Fitness")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new FitnessFragment()).commit();
}else if(home_items_list.get(position).getText().equals("Voetbal")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new VoetballFragment()).commit();
}else{
Toast.makeText(getActivity(), "Nog geen fragment gemaakt", Toast.LENGTH_SHORT).show();
}
/*HomeItem tmp = home_items_list.get(position);
String url = String.format("http://192.168.178.103:4000/categories/%s/posts", tmp.getID() );
MyPostsFragment mypostFragment = new MyPostsFragment();
mypostFragment.getPostData(url);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,mypostFragment).commit();
*/
/*
switch (category) {
case "Voetbal":fragment = new VoetballFragment();
break;
case "Fitness": fragment = new FitnessFragment();
break;
default:fragment = new Fragment();
}
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
*/
}
});
}
}
| Gertjan1996/Project-2.4-Web-Mobile | ForumApplication/app/src/main/java/com/example/forumapplication/Fragment/HomeFragment.java | 1,642 | // vervolgens vul je de arraylist met de reponse | line_comment | nl | package com.example.forumapplication.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.forumapplication.Activities.homeItemAdapter;
import com.example.forumapplication.R;
import com.example.forumapplication.Data.HomeItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private DrawerLayout drawerLayout;
private RecyclerView recyclerView;
private homeItemAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public JSONObject jsonObject;
public String category;
public ArrayList<HomeItem> home_items_list;
public HomeItem item;
private static String categorien_End_point = " http://192.168.178.103:4000/categories";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
home_items_list = new ArrayList<>();
/*
home_items_list.add(new home_items(R.drawable.voetball,"Voetball"));
home_items_list.add(new home_items(R.drawable.basketball,"Basketball"));
home_items_list.add(new home_items(R.drawable.veldhockey,"Veldhockey"));
home_items_list.add(new home_items(R.drawable.swim,"Swimming"));
home_items_list.add(new home_items(R.drawable.volleyball,"Volleyball"));
Log.e(" hi",home_items_list.toString());
*/ recyclerView =(RecyclerView)view.findViewById(R.id.recycle_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
getCategorien();
return view;
}
public void getCategorien(){
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, categorien_End_point, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
System.out.println(response.toString());
for (int i = 0; i < response.length(); i++) {
try {
jsonObject= response.getJSONObject(i);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
category = jsonObject.getString("category");
Log.e("Voorbeeld", category);
item = new HomeItem(R.drawable.ic_post, category); //HomeItem
item.setId(jsonObject.getString("id"));
home_items_list.add(item);
System.out.println(category);
Log.e("Home_item", item.toString());
Log.e("list",home_items_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
mAdapter = new homeItemAdapter(home_items_list);
mAdapter.setOnItemClickListener(new homeItemAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Fragment fragment ;
//ArrayList<HomeItem> temp = new ArrayList<>();
// call naar de backend met de id van de categorie waar je op hebt geklikt
// vervolgens vul<SUF>
// daarmee maak je een nieuwe main
System.out.println(home_items_list.get(position));
if(home_items_list.get(position).getText().equals("Fitness")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new FitnessFragment()).commit();
}else if(home_items_list.get(position).getText().equals("Voetbal")){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new VoetballFragment()).commit();
}else{
Toast.makeText(getActivity(), "Nog geen fragment gemaakt", Toast.LENGTH_SHORT).show();
}
/*HomeItem tmp = home_items_list.get(position);
String url = String.format("http://192.168.178.103:4000/categories/%s/posts", tmp.getID() );
MyPostsFragment mypostFragment = new MyPostsFragment();
mypostFragment.getPostData(url);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,mypostFragment).commit();
*/
/*
switch (category) {
case "Voetbal":fragment = new VoetballFragment();
break;
case "Fitness": fragment = new FitnessFragment();
break;
default:fragment = new Fragment();
}
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
*/
}
});
}
}
|
17353_3 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package instance;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import javolution.util.FastList;
import org.apache.commons.lang.mutable.MutableInt;
import com.aionemu.gameserver.configs.main.GroupConfig;
import com.aionemu.gameserver.configs.main.RateConfig;
import com.aionemu.gameserver.instance.handlers.GeneralInstanceHandler;
import com.aionemu.gameserver.instance.handlers.InstanceID;
import com.aionemu.gameserver.model.DescriptionId;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.Race;
import com.aionemu.gameserver.model.actions.PlayerActions;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.instance.InstanceScoreType;
import com.aionemu.gameserver.model.instance.instancereward.IdgelDomeReward;
import com.aionemu.gameserver.model.instance.instancereward.InstanceReward;
import com.aionemu.gameserver.model.instance.packetfactory.IdgelDomePacketsHandler;
import com.aionemu.gameserver.model.instance.playerreward.IdgelDomePlayerReward;
import com.aionemu.gameserver.model.instance.playerreward.InstancePlayerReward;
import com.aionemu.gameserver.model.team2.group.PlayerGroupService;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.services.AutoGroupService;
import com.aionemu.gameserver.services.abyss.AbyssPointsService;
import com.aionemu.gameserver.services.item.ItemService;
import com.aionemu.gameserver.services.player.PlayerReviveService;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldMapInstance;
/**
* @author GiGatR00n v4.7.5.x
*/
@InstanceID(301310000)
public class IdgelDomeInstance extends GeneralInstanceHandler
{
private final FastList<Future<?>> idgelTask = FastList.newInstance();
protected AtomicBoolean isInstanceStarted = new AtomicBoolean(false);
protected IdgelDomeReward idgelDomeReward;
private float loosingGroupMultiplier = 1;
private boolean isInstanceDestroyed = false;
private Race RaceKilledBoss = null;//Used to getting Additional Reward Box
/**
* Holds Idgel Dome Instance
*/
private WorldMapInstance IdgelDome;
/**
* Used to send Idgel Dome Instance Packets e.g. Score, Reward, Revive, PlayersInfo, ...
*/
private IdgelDomePacketsHandler IdgelDomePackets;
@Override
public void onInstanceCreate(WorldMapInstance instance)
{
super.onInstanceCreate(instance);
IdgelDome = instance;
idgelDomeReward = new IdgelDomeReward(mapId, instanceId, IdgelDome);
idgelDomeReward.setInstanceScoreType(InstanceScoreType.PREPARING);
IdgelDomePackets = new IdgelDomePacketsHandler(mapId, instanceId, instance, idgelDomeReward);
IdgelDomePackets.startInstanceTask();
/* Used to handling instance timeout event */
idgelTask.add(ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
stopInstance(idgelDomeReward.getWinningRaceByScore());
}
}, idgelDomeReward.getEndTime())); //20 Min.
}
@Override
public void onEnterInstance(final Player player) {
if (!containPlayer(player.getObjectId())) {
idgelDomeReward.regPlayerReward(player);
}
IdgelDomePackets.sendPreparingPacket(player);
}
protected IdgelDomePlayerReward getPlayerReward(Player player) {
idgelDomeReward.regPlayerReward(player);
return (IdgelDomePlayerReward) getPlayerReward(player.getObjectId());
}
private boolean containPlayer(Integer object) {
return idgelDomeReward.containPlayer(object);
}
@SuppressWarnings("unused")
protected void reward()
{
/*
* Elyos & Asmodian PvP and Points
*/
int ElyosPvPKills = getPvpKillsByRace(Race.ELYOS).intValue();
int ElyosPoints = getPointsByRace(Race.ELYOS).intValue();
int AsmoPvPKills = getPvpKillsByRace(Race.ASMODIANS).intValue();
int AsmoPoints = getPointsByRace(Race.ASMODIANS).intValue();
for (Player player : IdgelDome.getPlayersInside()) {
if (PlayerActions.isAlreadyDead(player)) {
PlayerReviveService.duelRevive(player);
}
IdgelDomePlayerReward playerReward = getPlayerReward(player.getObjectId());
float abyssPoint = playerReward.getPoints() * RateConfig.IDGEL_DOME_ABYSS_REWARD_RATE;
float gloryPoint = 50f * RateConfig.IDGEL_DOME_GLORY_REWARD_RATE;
playerReward.setRewardAp((int) abyssPoint);
playerReward.setRewardGp((int) gloryPoint);
float PlayerRateModifire = player.getRates().getIdgelDomeBoxRewardRate();
if (player.getRace().equals(idgelDomeReward.getWinningRace())) {
abyssPoint += idgelDomeReward.CalcBonusAbyssReward(true, isBossKilledBy(player.getRace()));
gloryPoint += idgelDomeReward.CalcBonusGloryReward(true, isBossKilledBy(player.getRace()));
playerReward.setBonusAp(idgelDomeReward.CalcBonusAbyssReward(true, isBossKilledBy(player.getRace())));
playerReward.setBonusGp(idgelDomeReward.CalcBonusGloryReward(true, isBossKilledBy(player.getRace())));
playerReward.setReward1Count(6f * PlayerRateModifire);//Winner Team always got 6 <Fragmented Ceramium>
playerReward.setReward2Count(1f * PlayerRateModifire);//Winner Team always got 1 <Idgel Dome Reward Box>
playerReward.setReward1(186000243);//Fragmented Ceramium
playerReward.setReward2(188053030);//Idgel Dome Reward Box
} else {
abyssPoint += idgelDomeReward.CalcBonusAbyssReward(false, isBossKilledBy(player.getRace()));
gloryPoint += idgelDomeReward.CalcBonusGloryReward(false, isBossKilledBy(player.getRace()));
playerReward.setRewardAp(idgelDomeReward.CalcBonusAbyssReward(false, isBossKilledBy(player.getRace())));
playerReward.setRewardGp(idgelDomeReward.CalcBonusGloryReward(false, isBossKilledBy(player.getRace())));
playerReward.setReward1Count(2f * PlayerRateModifire);//Looser Team always got 2 <Fragmented Ceramium>
playerReward.setReward2Count(0f * PlayerRateModifire);//Winner Team always got 0 <Idgel Dome Reward Box>
playerReward.setReward1(186000243);//Fragmented Ceramium
playerReward.setReward2(0);//Idgel Dome Reward Box
}
/*
* Idgel Dome Tribute Box (Additional Reward)
* for The Team that killed the boss (Destroyer Kunax)
*/
if (RaceKilledBoss == player.getRace()) {
playerReward.setAdditionalReward(188053032);
playerReward.setAdditionalRewardCount(1f * PlayerRateModifire);
ItemService.addItem(player, 188053032, (long) playerReward.getAdditionalRewardCount());
}
playerReward.setRewardCount(PlayerRateModifire);
ItemService.addItem(player, 186000243, (long) playerReward.getReward1Count());//Fragmented Ceramium
ItemService.addItem(player, 188053030, (long) playerReward.getReward2Count());//Idgel Dome Reward Box
AbyssPointsService.addAp(player, (int) abyssPoint);
AbyssPointsService.addGp(player, (int) gloryPoint);
}
for (Npc npc : IdgelDome.getNpcs()) {
npc.getController().onDelete();
}
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isInstanceDestroyed) {
for (Player player : IdgelDome.getPlayersInside()) {
onExitInstance(player);
}
AutoGroupService.getInstance().unRegisterInstance(instanceId);
}
}
}, 15000);
}
@Override
public boolean onReviveEvent(Player player)
{
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_REBIRTH_MASSAGE_ME);
PlayerReviveService.revive(player, 100, 100, false, 0);
player.getGameStats().updateStatsAndSpeedVisually();
idgelDomeReward.portToPosition(player);
Race OpponentRace = (player.getRace() == Race.ELYOS) ? Race.ASMODIANS : (player.getRace() == Race.ASMODIANS) ? Race.ELYOS : null;
if (OpponentRace == null) {
return true;
}
if (getPointsByRace(player.getRace()).intValue() < getPointsByRace(OpponentRace).intValue()) {
/* Applies the BUFF_SHIELD (Underdog's Fervor) to Player for 30-Seconds */
getPlayerReward(player.getObjectId()).endResurrectionBuff(player);
getPlayerReward(player.getObjectId()).applyResurrectionBuff(player);
}
/* Send only when a PLAYER has been Revived OnRevive() */
IdgelDomePackets.sendPlayerRevivedPacket(player);
return true;
}
@Override
public boolean onDie(Player player, Creature lastAttacker) {
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.DIE, 0, player.equals(lastAttacker) ? 0 : lastAttacker.getObjectId()), true);
PacketSendUtility.sendPacket(player, new SM_DIE(player.haveSelfRezEffect(), false, 0, 8));
int points = 60;
/* Send only when a PLAYER has been Killed (in PvP or PvE) */
IdgelDomePackets.sendPlayerDiePacket(player);
if (lastAttacker instanceof Player) {
if (lastAttacker.getRace() != player.getRace()) {
InstancePlayerReward playerReward = getPlayerReward(player.getObjectId());
if (getPointsByRace(lastAttacker.getRace()).compareTo(getPointsByRace(player.getRace())) < 0) {
points *= loosingGroupMultiplier;
} else if (loosingGroupMultiplier == 10 || playerReward.getPoints() == 0) {
points = 0;
}
updateScore((Player) lastAttacker, player, points, true);
}
}
updateScore(player, player, -points, false);
return true;
}
private boolean isBossKilledBy(Race PlayerRace) {
if (PlayerRace == RaceKilledBoss) {
return true;
}
return false;
}
private IdgelDomePlayerReward getPlayerReward(Integer ObjectId) {
return idgelDomeReward.getPlayerReward(ObjectId);
}
private MutableInt getPvpKillsByRace(Race race) {
return idgelDomeReward.getPvpKillsByRace(race);
}
private MutableInt getPointsByRace(Race race) {
return idgelDomeReward.getPointsByRace(race);
}
private void addPointsByRace(Race race, int points) {
idgelDomeReward.addPointsByRace(race, points);
}
private void addPvpKillsByRace(Race race, int points) {
idgelDomeReward.addPvpKillsByRace(race, points);
}
private void addPointToPlayer(Player player, int points) {
getPlayerReward(player.getObjectId()).addPoints(points);
}
private void addPvPKillToPlayer(Player player) {
getPlayerReward(player.getObjectId()).addPvPKillToPlayer();
}
private void despawnNpc(Npc npc) {
if (npc != null) {
npc.getController().onDelete();
}
}
protected void updateScore(Player player, Creature target, int points, boolean pvpKill)
{
if (points == 0) {
return;
}
addPointsByRace(player.getRace(), points);
List<Player> playersToGainScore = new ArrayList<Player>();
if (target != null && player.isInGroup2()) {
for (Player member : player.getPlayerAlliance2().getOnlineMembers()) {
if (member.getLifeStats().isAlreadyDead()) {
continue;
} if (MathUtil.isIn3dRange(member, target, GroupConfig.GROUP_MAX_DISTANCE)) {
playersToGainScore.add(member);
}
}
} else {
playersToGainScore.add(player);
}
for (Player playerToGainScore : playersToGainScore) {
addPointToPlayer(playerToGainScore, points / playersToGainScore.size());
if (target instanceof Npc) {
PacketSendUtility.sendPacket(playerToGainScore, new SM_SYSTEM_MESSAGE(1400237, new DescriptionId(((Npc) target).getObjectTemplate().getNameId() * 2 + 1), points));
} else if (target instanceof Player) {
PacketSendUtility.sendPacket(playerToGainScore, new SM_SYSTEM_MESSAGE(1400237, target.getName(), points));
}
}
int pointDifference = getPointsByRace(Race.ASMODIANS).intValue() - (getPointsByRace(Race.ELYOS)).intValue();
if (pointDifference < 0) {
pointDifference *= -1;
} if (pointDifference >= 3000) {
loosingGroupMultiplier = 10;
} else if (pointDifference >= 1000) {
loosingGroupMultiplier = 1.5f;
} else {
loosingGroupMultiplier = 1;
}
if (pvpKill && points > 0) {
addPvpKillsByRace(player.getRace(), 1);
addPvPKillToPlayer(player);
}
/* Send only when a NPC has been killed OnNpcDie() */
IdgelDomePackets.sendNpcScorePacket(player);
}
@Override
public void onDie(Npc npc) {
Player mostPlayerDamage = npc.getAggroList().getMostPlayerDamage();
if (mostPlayerDamage == null) {
return;
}
int Points = 0;
int npcId = npc.getNpcId();
switch (npcId)
{
case 234189: //Sheban Intelligence Unit Stitch.
case 234188: //Sheban Intelligence Unit Mongrel.
case 234187: //Sheban Intelligence Unit Hunter.
case 234186: //Sheban Intelligence Unit Ridgeblade.
Points = 120;
break;
case 234754: //Sheban Elite Medic.
case 234753: //Sheban Elite Marauder.
case 234752: //Sheban Elite Sniper.
case 234751: //Sheban Elite Stalwart.
Points = 200;
break;
case 234190: //Destroyer Kunax (Ku-Nag The Slayer)
Points = 6000;
RaceKilledBoss = mostPlayerDamage.getRace();
stopInstance(idgelDomeReward.getWinningRaceByScore());
break;
}
updateScore(mostPlayerDamage, npc, Points, false);
}
protected void stopInstance(Race race)
{
stopInstanceTask();
idgelDomeReward.setWinningRace(race);
idgelDomeReward.setInstanceScoreType(InstanceScoreType.END_PROGRESS);
reward();
/* Reward Packet */
IdgelDomePackets.sendScoreTypePacket();//Send 1-Time when Start_Progress and End_Progress
IdgelDomePackets.sendRewardPacket();//Send Reward Packet OnBossKilled()|OnTimeOut()
}
@Override
public void onInstanceDestroy()
{
stopInstanceTask();
isInstanceDestroyed = true;
idgelDomeReward.clear();
}
private void stopInstanceTask()
{
for (FastList.Node<Future<?>> n = idgelTask.head(), end = idgelTask.tail(); (n = n.getNext()) != end; ) {
if (n.getValue() != null) {
n.getValue().cancel(true);
}
}
IdgelDomePackets.ClearTasks();
}
@Override
public InstanceReward<?> getInstanceReward() {
return idgelDomeReward;
}
@Override
public void onLeaveInstance(Player player) {
if (player.isInGroup2()) {
PlayerGroupService.removePlayer(player);
}
/* Player Leave Packet */
IdgelDomePackets.sendPlayerLeavePacket(player);
}
@Override
public void onPlayerLogin(Player player) {
IdgelDomePackets.sendNpcScorePacket(player);
}
@Override
public void onExitInstance(Player player) {
TeleportService2.moveToInstanceExit(player, mapId, player.getRace());
}
} | GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/instance/IdgelDomeInstance.java | 5,944 | /**
* Holds Idgel Dome Instance
*/ | block_comment | nl | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package instance;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import javolution.util.FastList;
import org.apache.commons.lang.mutable.MutableInt;
import com.aionemu.gameserver.configs.main.GroupConfig;
import com.aionemu.gameserver.configs.main.RateConfig;
import com.aionemu.gameserver.instance.handlers.GeneralInstanceHandler;
import com.aionemu.gameserver.instance.handlers.InstanceID;
import com.aionemu.gameserver.model.DescriptionId;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.Race;
import com.aionemu.gameserver.model.actions.PlayerActions;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.instance.InstanceScoreType;
import com.aionemu.gameserver.model.instance.instancereward.IdgelDomeReward;
import com.aionemu.gameserver.model.instance.instancereward.InstanceReward;
import com.aionemu.gameserver.model.instance.packetfactory.IdgelDomePacketsHandler;
import com.aionemu.gameserver.model.instance.playerreward.IdgelDomePlayerReward;
import com.aionemu.gameserver.model.instance.playerreward.InstancePlayerReward;
import com.aionemu.gameserver.model.team2.group.PlayerGroupService;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.services.AutoGroupService;
import com.aionemu.gameserver.services.abyss.AbyssPointsService;
import com.aionemu.gameserver.services.item.ItemService;
import com.aionemu.gameserver.services.player.PlayerReviveService;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldMapInstance;
/**
* @author GiGatR00n v4.7.5.x
*/
@InstanceID(301310000)
public class IdgelDomeInstance extends GeneralInstanceHandler
{
private final FastList<Future<?>> idgelTask = FastList.newInstance();
protected AtomicBoolean isInstanceStarted = new AtomicBoolean(false);
protected IdgelDomeReward idgelDomeReward;
private float loosingGroupMultiplier = 1;
private boolean isInstanceDestroyed = false;
private Race RaceKilledBoss = null;//Used to getting Additional Reward Box
/**
* Holds Idgel Dome<SUF>*/
private WorldMapInstance IdgelDome;
/**
* Used to send Idgel Dome Instance Packets e.g. Score, Reward, Revive, PlayersInfo, ...
*/
private IdgelDomePacketsHandler IdgelDomePackets;
@Override
public void onInstanceCreate(WorldMapInstance instance)
{
super.onInstanceCreate(instance);
IdgelDome = instance;
idgelDomeReward = new IdgelDomeReward(mapId, instanceId, IdgelDome);
idgelDomeReward.setInstanceScoreType(InstanceScoreType.PREPARING);
IdgelDomePackets = new IdgelDomePacketsHandler(mapId, instanceId, instance, idgelDomeReward);
IdgelDomePackets.startInstanceTask();
/* Used to handling instance timeout event */
idgelTask.add(ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
stopInstance(idgelDomeReward.getWinningRaceByScore());
}
}, idgelDomeReward.getEndTime())); //20 Min.
}
@Override
public void onEnterInstance(final Player player) {
if (!containPlayer(player.getObjectId())) {
idgelDomeReward.regPlayerReward(player);
}
IdgelDomePackets.sendPreparingPacket(player);
}
protected IdgelDomePlayerReward getPlayerReward(Player player) {
idgelDomeReward.regPlayerReward(player);
return (IdgelDomePlayerReward) getPlayerReward(player.getObjectId());
}
private boolean containPlayer(Integer object) {
return idgelDomeReward.containPlayer(object);
}
@SuppressWarnings("unused")
protected void reward()
{
/*
* Elyos & Asmodian PvP and Points
*/
int ElyosPvPKills = getPvpKillsByRace(Race.ELYOS).intValue();
int ElyosPoints = getPointsByRace(Race.ELYOS).intValue();
int AsmoPvPKills = getPvpKillsByRace(Race.ASMODIANS).intValue();
int AsmoPoints = getPointsByRace(Race.ASMODIANS).intValue();
for (Player player : IdgelDome.getPlayersInside()) {
if (PlayerActions.isAlreadyDead(player)) {
PlayerReviveService.duelRevive(player);
}
IdgelDomePlayerReward playerReward = getPlayerReward(player.getObjectId());
float abyssPoint = playerReward.getPoints() * RateConfig.IDGEL_DOME_ABYSS_REWARD_RATE;
float gloryPoint = 50f * RateConfig.IDGEL_DOME_GLORY_REWARD_RATE;
playerReward.setRewardAp((int) abyssPoint);
playerReward.setRewardGp((int) gloryPoint);
float PlayerRateModifire = player.getRates().getIdgelDomeBoxRewardRate();
if (player.getRace().equals(idgelDomeReward.getWinningRace())) {
abyssPoint += idgelDomeReward.CalcBonusAbyssReward(true, isBossKilledBy(player.getRace()));
gloryPoint += idgelDomeReward.CalcBonusGloryReward(true, isBossKilledBy(player.getRace()));
playerReward.setBonusAp(idgelDomeReward.CalcBonusAbyssReward(true, isBossKilledBy(player.getRace())));
playerReward.setBonusGp(idgelDomeReward.CalcBonusGloryReward(true, isBossKilledBy(player.getRace())));
playerReward.setReward1Count(6f * PlayerRateModifire);//Winner Team always got 6 <Fragmented Ceramium>
playerReward.setReward2Count(1f * PlayerRateModifire);//Winner Team always got 1 <Idgel Dome Reward Box>
playerReward.setReward1(186000243);//Fragmented Ceramium
playerReward.setReward2(188053030);//Idgel Dome Reward Box
} else {
abyssPoint += idgelDomeReward.CalcBonusAbyssReward(false, isBossKilledBy(player.getRace()));
gloryPoint += idgelDomeReward.CalcBonusGloryReward(false, isBossKilledBy(player.getRace()));
playerReward.setRewardAp(idgelDomeReward.CalcBonusAbyssReward(false, isBossKilledBy(player.getRace())));
playerReward.setRewardGp(idgelDomeReward.CalcBonusGloryReward(false, isBossKilledBy(player.getRace())));
playerReward.setReward1Count(2f * PlayerRateModifire);//Looser Team always got 2 <Fragmented Ceramium>
playerReward.setReward2Count(0f * PlayerRateModifire);//Winner Team always got 0 <Idgel Dome Reward Box>
playerReward.setReward1(186000243);//Fragmented Ceramium
playerReward.setReward2(0);//Idgel Dome Reward Box
}
/*
* Idgel Dome Tribute Box (Additional Reward)
* for The Team that killed the boss (Destroyer Kunax)
*/
if (RaceKilledBoss == player.getRace()) {
playerReward.setAdditionalReward(188053032);
playerReward.setAdditionalRewardCount(1f * PlayerRateModifire);
ItemService.addItem(player, 188053032, (long) playerReward.getAdditionalRewardCount());
}
playerReward.setRewardCount(PlayerRateModifire);
ItemService.addItem(player, 186000243, (long) playerReward.getReward1Count());//Fragmented Ceramium
ItemService.addItem(player, 188053030, (long) playerReward.getReward2Count());//Idgel Dome Reward Box
AbyssPointsService.addAp(player, (int) abyssPoint);
AbyssPointsService.addGp(player, (int) gloryPoint);
}
for (Npc npc : IdgelDome.getNpcs()) {
npc.getController().onDelete();
}
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (!isInstanceDestroyed) {
for (Player player : IdgelDome.getPlayersInside()) {
onExitInstance(player);
}
AutoGroupService.getInstance().unRegisterInstance(instanceId);
}
}
}, 15000);
}
@Override
public boolean onReviveEvent(Player player)
{
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_REBIRTH_MASSAGE_ME);
PlayerReviveService.revive(player, 100, 100, false, 0);
player.getGameStats().updateStatsAndSpeedVisually();
idgelDomeReward.portToPosition(player);
Race OpponentRace = (player.getRace() == Race.ELYOS) ? Race.ASMODIANS : (player.getRace() == Race.ASMODIANS) ? Race.ELYOS : null;
if (OpponentRace == null) {
return true;
}
if (getPointsByRace(player.getRace()).intValue() < getPointsByRace(OpponentRace).intValue()) {
/* Applies the BUFF_SHIELD (Underdog's Fervor) to Player for 30-Seconds */
getPlayerReward(player.getObjectId()).endResurrectionBuff(player);
getPlayerReward(player.getObjectId()).applyResurrectionBuff(player);
}
/* Send only when a PLAYER has been Revived OnRevive() */
IdgelDomePackets.sendPlayerRevivedPacket(player);
return true;
}
@Override
public boolean onDie(Player player, Creature lastAttacker) {
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.DIE, 0, player.equals(lastAttacker) ? 0 : lastAttacker.getObjectId()), true);
PacketSendUtility.sendPacket(player, new SM_DIE(player.haveSelfRezEffect(), false, 0, 8));
int points = 60;
/* Send only when a PLAYER has been Killed (in PvP or PvE) */
IdgelDomePackets.sendPlayerDiePacket(player);
if (lastAttacker instanceof Player) {
if (lastAttacker.getRace() != player.getRace()) {
InstancePlayerReward playerReward = getPlayerReward(player.getObjectId());
if (getPointsByRace(lastAttacker.getRace()).compareTo(getPointsByRace(player.getRace())) < 0) {
points *= loosingGroupMultiplier;
} else if (loosingGroupMultiplier == 10 || playerReward.getPoints() == 0) {
points = 0;
}
updateScore((Player) lastAttacker, player, points, true);
}
}
updateScore(player, player, -points, false);
return true;
}
private boolean isBossKilledBy(Race PlayerRace) {
if (PlayerRace == RaceKilledBoss) {
return true;
}
return false;
}
private IdgelDomePlayerReward getPlayerReward(Integer ObjectId) {
return idgelDomeReward.getPlayerReward(ObjectId);
}
private MutableInt getPvpKillsByRace(Race race) {
return idgelDomeReward.getPvpKillsByRace(race);
}
private MutableInt getPointsByRace(Race race) {
return idgelDomeReward.getPointsByRace(race);
}
private void addPointsByRace(Race race, int points) {
idgelDomeReward.addPointsByRace(race, points);
}
private void addPvpKillsByRace(Race race, int points) {
idgelDomeReward.addPvpKillsByRace(race, points);
}
private void addPointToPlayer(Player player, int points) {
getPlayerReward(player.getObjectId()).addPoints(points);
}
private void addPvPKillToPlayer(Player player) {
getPlayerReward(player.getObjectId()).addPvPKillToPlayer();
}
private void despawnNpc(Npc npc) {
if (npc != null) {
npc.getController().onDelete();
}
}
protected void updateScore(Player player, Creature target, int points, boolean pvpKill)
{
if (points == 0) {
return;
}
addPointsByRace(player.getRace(), points);
List<Player> playersToGainScore = new ArrayList<Player>();
if (target != null && player.isInGroup2()) {
for (Player member : player.getPlayerAlliance2().getOnlineMembers()) {
if (member.getLifeStats().isAlreadyDead()) {
continue;
} if (MathUtil.isIn3dRange(member, target, GroupConfig.GROUP_MAX_DISTANCE)) {
playersToGainScore.add(member);
}
}
} else {
playersToGainScore.add(player);
}
for (Player playerToGainScore : playersToGainScore) {
addPointToPlayer(playerToGainScore, points / playersToGainScore.size());
if (target instanceof Npc) {
PacketSendUtility.sendPacket(playerToGainScore, new SM_SYSTEM_MESSAGE(1400237, new DescriptionId(((Npc) target).getObjectTemplate().getNameId() * 2 + 1), points));
} else if (target instanceof Player) {
PacketSendUtility.sendPacket(playerToGainScore, new SM_SYSTEM_MESSAGE(1400237, target.getName(), points));
}
}
int pointDifference = getPointsByRace(Race.ASMODIANS).intValue() - (getPointsByRace(Race.ELYOS)).intValue();
if (pointDifference < 0) {
pointDifference *= -1;
} if (pointDifference >= 3000) {
loosingGroupMultiplier = 10;
} else if (pointDifference >= 1000) {
loosingGroupMultiplier = 1.5f;
} else {
loosingGroupMultiplier = 1;
}
if (pvpKill && points > 0) {
addPvpKillsByRace(player.getRace(), 1);
addPvPKillToPlayer(player);
}
/* Send only when a NPC has been killed OnNpcDie() */
IdgelDomePackets.sendNpcScorePacket(player);
}
@Override
public void onDie(Npc npc) {
Player mostPlayerDamage = npc.getAggroList().getMostPlayerDamage();
if (mostPlayerDamage == null) {
return;
}
int Points = 0;
int npcId = npc.getNpcId();
switch (npcId)
{
case 234189: //Sheban Intelligence Unit Stitch.
case 234188: //Sheban Intelligence Unit Mongrel.
case 234187: //Sheban Intelligence Unit Hunter.
case 234186: //Sheban Intelligence Unit Ridgeblade.
Points = 120;
break;
case 234754: //Sheban Elite Medic.
case 234753: //Sheban Elite Marauder.
case 234752: //Sheban Elite Sniper.
case 234751: //Sheban Elite Stalwart.
Points = 200;
break;
case 234190: //Destroyer Kunax (Ku-Nag The Slayer)
Points = 6000;
RaceKilledBoss = mostPlayerDamage.getRace();
stopInstance(idgelDomeReward.getWinningRaceByScore());
break;
}
updateScore(mostPlayerDamage, npc, Points, false);
}
protected void stopInstance(Race race)
{
stopInstanceTask();
idgelDomeReward.setWinningRace(race);
idgelDomeReward.setInstanceScoreType(InstanceScoreType.END_PROGRESS);
reward();
/* Reward Packet */
IdgelDomePackets.sendScoreTypePacket();//Send 1-Time when Start_Progress and End_Progress
IdgelDomePackets.sendRewardPacket();//Send Reward Packet OnBossKilled()|OnTimeOut()
}
@Override
public void onInstanceDestroy()
{
stopInstanceTask();
isInstanceDestroyed = true;
idgelDomeReward.clear();
}
private void stopInstanceTask()
{
for (FastList.Node<Future<?>> n = idgelTask.head(), end = idgelTask.tail(); (n = n.getNext()) != end; ) {
if (n.getValue() != null) {
n.getValue().cancel(true);
}
}
IdgelDomePackets.ClearTasks();
}
@Override
public InstanceReward<?> getInstanceReward() {
return idgelDomeReward;
}
@Override
public void onLeaveInstance(Player player) {
if (player.isInGroup2()) {
PlayerGroupService.removePlayer(player);
}
/* Player Leave Packet */
IdgelDomePackets.sendPlayerLeavePacket(player);
}
@Override
public void onPlayerLogin(Player player) {
IdgelDomePackets.sendNpcScorePacket(player);
}
@Override
public void onExitInstance(Player player) {
TeleportService2.moveToInstanceExit(player, mapId, player.getRace());
}
} |
15645_5 | package Classes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class Account extends Persoon {
//Attributes
private String wachtwoord;
private Date gbdatum;
private String telnr;
//Constructors
public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) {
super(i, vn, tv, an, pc, hnr, toev, em);
setWachtwoord(ww);
setGbdatum(gbd);
telnr = tnr;
}
//Getters
public String getWachtwoord() {
return wachtwoord;
}
public Date getGbdatum() {
return gbdatum;
}
public String getTelnr() {
return telnr;
}
//Setters
public void setGbdatum(String gbd) {
//Hier komt een methode die een MySQL Date omzet naar een Java Date
}
public void setTelnr(String tnr) {
telnr = tnr;
}
public void setWachtwoord(String ww) {
try {
//MessageDigest met algoritme SHA-512
MessageDigest md = MessageDigest.getInstance("SHA-512");
//Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest
md.update(ww.getBytes());
//Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes
byte[] bytes = md.digest();
//Bytes worden hier omgezet naar hexadecimalen
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord
wachtwoord = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
//Methods
}
| GijsAlb/HSR01 | HSR01JavaFX/src/Classes/Account.java | 612 | //De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord
| line_comment | nl | package Classes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
public class Account extends Persoon {
//Attributes
private String wachtwoord;
private Date gbdatum;
private String telnr;
//Constructors
public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) {
super(i, vn, tv, an, pc, hnr, toev, em);
setWachtwoord(ww);
setGbdatum(gbd);
telnr = tnr;
}
//Getters
public String getWachtwoord() {
return wachtwoord;
}
public Date getGbdatum() {
return gbdatum;
}
public String getTelnr() {
return telnr;
}
//Setters
public void setGbdatum(String gbd) {
//Hier komt een methode die een MySQL Date omzet naar een Java Date
}
public void setTelnr(String tnr) {
telnr = tnr;
}
public void setWachtwoord(String ww) {
try {
//MessageDigest met algoritme SHA-512
MessageDigest md = MessageDigest.getInstance("SHA-512");
//Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest
md.update(ww.getBytes());
//Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes
byte[] bytes = md.digest();
//Bytes worden hier omgezet naar hexadecimalen
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//De hexadecimale<SUF>
wachtwoord = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
//Methods
}
|
62412_6 | import be.gilles.Acteur;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
private static final Acteur[] testdata = {
new Acteur("Cameron Diaz", 1972),
new Acteur("Anna Faris", 1976),
new Acteur("Angelina Jolie", 1975),
new Acteur("Jennifer Lopez", 1970),
new Acteur("Reese Witherspoon", 1976),
new Acteur("Neve Campbell", 1973),
new Acteur("Catherine Zeta-Jones", 1969),
new Acteur("Kirsten Dunst", 1982),
new Acteur("Kate Winslet", 1975),
new Acteur("Gina Philips", 1975),
new Acteur("Shannon Elisabeth", 1973),
new Acteur("Carmen Electra", 1972),
new Acteur("Drew Barrymore", 1975),
new Acteur("Elisabeth Hurley", 1965),
new Acteur("Tara Reid", 1975),
new Acteur("Katie Holmes", 1978),
new Acteur("Anna Faris", 1976)
};
public static void main(String[] args) {
Acteur reese = new Acteur("Reese Witherspoon", 1976);
Acteur drew = new Acteur("Drew Barrymore", 1975);
Acteur anna = new Acteur("Anna Faris", 1976);
Acteur thandie = new Acteur("Thandie Newton", 1972);
List<Acteur> acteurs = new ArrayList<Acteur>();
acteurs.addAll(Arrays.asList(testdata));
acteurs.add(reese);
acteurs.add(drew);
acteurs.add(anna);
acteurs.add(thandie);
// Toon de inhoud van de collection (zonder iterator)
Arrays.stream(testdata).forEach(System.out::println);
// Verwijder de objecten reese en thandie
acteurs.removeAll(Arrays.asList(reese, thandie));
// Verwijder alle acteurs geboren in 1975 (met iterator)
acteurs.removeIf(x -> x.getGeboortejaar() == 1975);
// Using an iterator (the less efficient way :x)
for (Iterator<Acteur> it = acteurs.iterator(); it.hasNext(); ) {
if (it.next().getGeboortejaar() == 1975) it.remove();
}
// Verwijder alle dubbele acteurs in de lijst (doe dit bijvoorbeeld door een
// nieuwe lijst te maken zonder dubbels. Je kan “contains” gebruiken om te
// kijken of een element al in de lijst zit.
//acteurs = acteurs.stream().distinct().collect(Collectors.toList()); -> Updating
// acteurs.stream().sorted(Acteur::compareTo).forEach(System.out::println);
System.out.println("Uiteindelijke inhoud: ");
acteurs.stream().distinct().sorted(Acteur::compareTo).forEach(System.out::println);
}
}
| GillesClsns/Programming-OO-Concepts | P2-2022/P2-W4/Acteurs/src/Main.java | 841 | // kijken of een element al in de lijst zit. | line_comment | nl | import be.gilles.Acteur;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
private static final Acteur[] testdata = {
new Acteur("Cameron Diaz", 1972),
new Acteur("Anna Faris", 1976),
new Acteur("Angelina Jolie", 1975),
new Acteur("Jennifer Lopez", 1970),
new Acteur("Reese Witherspoon", 1976),
new Acteur("Neve Campbell", 1973),
new Acteur("Catherine Zeta-Jones", 1969),
new Acteur("Kirsten Dunst", 1982),
new Acteur("Kate Winslet", 1975),
new Acteur("Gina Philips", 1975),
new Acteur("Shannon Elisabeth", 1973),
new Acteur("Carmen Electra", 1972),
new Acteur("Drew Barrymore", 1975),
new Acteur("Elisabeth Hurley", 1965),
new Acteur("Tara Reid", 1975),
new Acteur("Katie Holmes", 1978),
new Acteur("Anna Faris", 1976)
};
public static void main(String[] args) {
Acteur reese = new Acteur("Reese Witherspoon", 1976);
Acteur drew = new Acteur("Drew Barrymore", 1975);
Acteur anna = new Acteur("Anna Faris", 1976);
Acteur thandie = new Acteur("Thandie Newton", 1972);
List<Acteur> acteurs = new ArrayList<Acteur>();
acteurs.addAll(Arrays.asList(testdata));
acteurs.add(reese);
acteurs.add(drew);
acteurs.add(anna);
acteurs.add(thandie);
// Toon de inhoud van de collection (zonder iterator)
Arrays.stream(testdata).forEach(System.out::println);
// Verwijder de objecten reese en thandie
acteurs.removeAll(Arrays.asList(reese, thandie));
// Verwijder alle acteurs geboren in 1975 (met iterator)
acteurs.removeIf(x -> x.getGeboortejaar() == 1975);
// Using an iterator (the less efficient way :x)
for (Iterator<Acteur> it = acteurs.iterator(); it.hasNext(); ) {
if (it.next().getGeboortejaar() == 1975) it.remove();
}
// Verwijder alle dubbele acteurs in de lijst (doe dit bijvoorbeeld door een
// nieuwe lijst te maken zonder dubbels. Je kan “contains” gebruiken om te
// kijken of<SUF>
//acteurs = acteurs.stream().distinct().collect(Collectors.toList()); -> Updating
// acteurs.stream().sorted(Acteur::compareTo).forEach(System.out::println);
System.out.println("Uiteindelijke inhoud: ");
acteurs.stream().distinct().sorted(Acteur::compareTo).forEach(System.out::println);
}
}
|
25391_1 | package be.ugent.service;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import be.ugent.Authentication;
import be.ugent.TestClass;
import be.ugent.dao.PatientDao;
import be.ugent.entitity.Patient;
@Path("/PatientService")
public class PatientService {
PatientDao patientDao = new PatientDao();
@GET
@Path("/patients")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatient(firstName, lastName);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@GET
@Path("/patients/id")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUser(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) {
System.out.println("Patient opgevraagd met id: "+patientID);
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatient(Integer.parseInt(patientID));
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@GET
@Path("/advice")
@Produces({ MediaType.TEXT_PLAIN })
public Response getAdvice(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatienFromId(patientID);
return Response.ok().entity(retrieved.getAdvice()+"").build();
}
@GET
@Path("/login")
@Produces({ MediaType.APPLICATION_JSON })
public Response login(@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("User ingelogd met email:"+patientDao.getPatientFromHeader(header));
Patient retrieved = patientDao.getPatientFromHeader(header);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@POST
@Path("/patients/hello")
@Consumes({MediaType.TEXT_PLAIN})
public Response hello(String user){
System.out.println("Hello "+user);
return Response.ok("Hello "+user).build();
}
@PUT
@Path("/patients")
@Consumes(MediaType.APPLICATION_JSON)
public Response addUser(String user){
System.out.println("pat: "+user);
System.out.println("Patient requested to add: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()==0){
PatientDao patientDao = new PatientDao();
toAdd.setPatientID(patientDao.getNewId());
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return Response.status(417).build();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.storePatient(toAdd)){
//return patient successfully created
String message = "Beste,\n\nEr is een nieuwe patient die zich heeft geregistreerd met patientID "+toAdd.getPatientID()+".\n\nMet vriendelijke groet,\n\nDe paashaas";
try {
TestClass.generateAndSendEmail("Nieuwe patient geregistreerd",message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(201).entity(patientDao.getPatienFromId(toAdd.getPatientID()+"")).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response changeUser(String user){
System.out.println("Patient requested to change: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/diagnose")
@Consumes(MediaType.APPLICATION_JSON)
public Response diagnoseUser(String tupleID,@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
System.out.println("Patient requested to diagnose: "+tupleID);
Gson gson = new Gson();
Patient toAdd = null;
try {
JsonObject tuple = gson.fromJson(tupleID, JsonObject.class);
toAdd = patientDao.getPatienFromId(""+Integer.parseInt(tuple.get("patientID").getAsString()));
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
toAdd.setDiagnoseID(tuple.get("diagnoseID").getAsInt());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
}
| GillesVandewiele/ChronicalRest | Chronic/src/be/ugent/service/PatientService.java | 2,211 | // System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName); | line_comment | nl | package be.ugent.service;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import be.ugent.Authentication;
import be.ugent.TestClass;
import be.ugent.dao.PatientDao;
import be.ugent.entitity.Patient;
@Path("/PatientService")
public class PatientService {
PatientDao patientDao = new PatientDao();
@GET
@Path("/patients")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatient(firstName, lastName);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@GET
@Path("/patients/id")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUser(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) {
System.out.println("Patient opgevraagd met id: "+patientID);
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd<SUF>
Patient retrieved = patientDao.getPatient(Integer.parseInt(patientID));
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@GET
@Path("/advice")
@Produces({ MediaType.TEXT_PLAIN })
public Response getAdvice(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatienFromId(patientID);
return Response.ok().entity(retrieved.getAdvice()+"").build();
}
@GET
@Path("/login")
@Produces({ MediaType.APPLICATION_JSON })
public Response login(@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("User ingelogd met email:"+patientDao.getPatientFromHeader(header));
Patient retrieved = patientDao.getPatientFromHeader(header);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@POST
@Path("/patients/hello")
@Consumes({MediaType.TEXT_PLAIN})
public Response hello(String user){
System.out.println("Hello "+user);
return Response.ok("Hello "+user).build();
}
@PUT
@Path("/patients")
@Consumes(MediaType.APPLICATION_JSON)
public Response addUser(String user){
System.out.println("pat: "+user);
System.out.println("Patient requested to add: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()==0){
PatientDao patientDao = new PatientDao();
toAdd.setPatientID(patientDao.getNewId());
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return Response.status(417).build();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.storePatient(toAdd)){
//return patient successfully created
String message = "Beste,\n\nEr is een nieuwe patient die zich heeft geregistreerd met patientID "+toAdd.getPatientID()+".\n\nMet vriendelijke groet,\n\nDe paashaas";
try {
TestClass.generateAndSendEmail("Nieuwe patient geregistreerd",message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(201).entity(patientDao.getPatienFromId(toAdd.getPatientID()+"")).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response changeUser(String user){
System.out.println("Patient requested to change: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/diagnose")
@Consumes(MediaType.APPLICATION_JSON)
public Response diagnoseUser(String tupleID,@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
System.out.println("Patient requested to diagnose: "+tupleID);
Gson gson = new Gson();
Patient toAdd = null;
try {
JsonObject tuple = gson.fromJson(tupleID, JsonObject.class);
toAdd = patientDao.getPatienFromId(""+Integer.parseInt(tuple.get("patientID").getAsString()));
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
toAdd.setDiagnoseID(tuple.get("diagnoseID").getAsInt());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
}
|
119492_4 | package com.railway.station_service;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import com.railway.station_service.adapters.messaging.Channels;
import com.railway.station_service.domain.Address;
import com.railway.station_service.domain.Platform;
import com.railway.station_service.domain.Station;
import com.railway.station_service.persistence.PlatformRepository;
import com.railway.station_service.persistence.ScheduleItemRepository;
import com.railway.station_service.persistence.StationRepository;
@SpringBootApplication
@EnableBinding(Channels.class)
public class RailwayAppStationApplication {
private static Logger logger = LoggerFactory.getLogger(RailwayAppStationApplication.class);
private StationRepository stationRepository;
private PlatformRepository platformRepository;
public static void main(String[] args) {
SpringApplication.run(RailwayAppStationApplication.class, args);
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("delay-request-db", 6379);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<UUID, Object> redisTemplate() {
RedisTemplate<UUID, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
@Bean
public CommandLineRunner populateDatabase (StationRepository stationRepository, PlatformRepository platformRepository, ScheduleItemRepository scheduleItemRepository) {
return(args)->{
this.stationRepository = stationRepository;
this.platformRepository = platformRepository;
// platformRepository.deleteAll();
// stationRepository.deleteAll();
//
// createStation(UUID.fromString("11018de0-1943-42b2-929d-a707f751f79c"), "Gent-Sint-Pieters", "Koningin Maria Hendrikaplein 1", "Gent", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("a39b1971-fc82-49b2-809a-444105e03c8d"), "Gent-Dampoort", "Oktrooiplein 10", "Gent", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("cf204af6-a407-47ea-af89-f0f989e7bd8a"), "Kortrijk", "Stationsplein 8", "Kortrijk", "West-Vlaanderen", "België");
// createStation(UUID.fromString("73df5f20-33e9-4518-bc23-3cf143c59198"), "Waregem", "Noorderlaan 71", "Waregem", "West-Vlaanderen", "België");
// createStation(UUID.fromString("bc51f294-6823-41cd-be82-d5ba2da4b04d"), "Aalter", "Stationsplein 2", "Aalter", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("d6951807-1fcc-4966-aa30-d4f399685a90"), "De Pinte", "Stationsstraat 25", "De Pinte", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("1454163f-f24f-490f-9e06-f97ffaf008e3"), "Deinze", "Statieplein 4", "Deinze", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("4181c609-7ed5-473e-befe-8013cd75c24c"), "Eeklo", "Koningin Astridplein 1", "Eeklo", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("7b8d9768-7310-4b7d-b6e4-f58abbeac63e"), "Wondelgem", "Wondelgemstationplein 36", "Wondelgem", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("5514be96-c4f1-4dd7-ace4-ac5cbd29c17d"), "Oudenaarde", "Stationplein 1 Gewest", "Oudenaarde", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("5b659978-1c39-4372-97ec-a6e4d1418ef3"), "Zottegem", "Stationsplein 12", "Zottegem", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("b44c17fc-6df1-4808-83d6-838f5637c9c7"), "Denderleeuw", "Stationsplein", "Denderleeuw", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("05cce0f7-1409-4224-926a-db3b4c4a8ce5"), "Brussel-Zuid", "Fonsnylaan 47b", "Brussel", "Brussels", "België");
};
}
@Transactional(isolation = Isolation.SERIALIZABLE)
public void createStation(UUID id, String name, String street, String city, String province, String country) {
Address address = new Address(street, city, province, country);
Station station = new Station(name, address);
station.setId(id);
Platform p1 = new Platform(1);
Platform p2 = new Platform(2);
Platform p3 = new Platform(3);
platformRepository.save(p1);
platformRepository.save(p2);
platformRepository.save(p3);
station.getPlatforms().add(p1);
station.getPlatforms().add(p2);
station.getPlatforms().add(p3);
stationRepository.save(station);
p1.setStation(station);
p2.setStation(station);
p3.setStation(station);
platformRepository.save(p1);
platformRepository.save(p2);
platformRepository.save(p3);
logger.info("Station: " + station.toString());
}
}
| GillisWerrebrouck/UGent_Railway-System-Architecture | railway-app-station/src/main/java/com/railway/station_service/RailwayAppStationApplication.java | 1,841 | // createStation(UUID.fromString("bc51f294-6823-41cd-be82-d5ba2da4b04d"), "Aalter", "Stationsplein 2", "Aalter", "Oost-Vlaanderen", "België"); | line_comment | nl | package com.railway.station_service;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import com.railway.station_service.adapters.messaging.Channels;
import com.railway.station_service.domain.Address;
import com.railway.station_service.domain.Platform;
import com.railway.station_service.domain.Station;
import com.railway.station_service.persistence.PlatformRepository;
import com.railway.station_service.persistence.ScheduleItemRepository;
import com.railway.station_service.persistence.StationRepository;
@SpringBootApplication
@EnableBinding(Channels.class)
public class RailwayAppStationApplication {
private static Logger logger = LoggerFactory.getLogger(RailwayAppStationApplication.class);
private StationRepository stationRepository;
private PlatformRepository platformRepository;
public static void main(String[] args) {
SpringApplication.run(RailwayAppStationApplication.class, args);
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("delay-request-db", 6379);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<UUID, Object> redisTemplate() {
RedisTemplate<UUID, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
@Bean
public CommandLineRunner populateDatabase (StationRepository stationRepository, PlatformRepository platformRepository, ScheduleItemRepository scheduleItemRepository) {
return(args)->{
this.stationRepository = stationRepository;
this.platformRepository = platformRepository;
// platformRepository.deleteAll();
// stationRepository.deleteAll();
//
// createStation(UUID.fromString("11018de0-1943-42b2-929d-a707f751f79c"), "Gent-Sint-Pieters", "Koningin Maria Hendrikaplein 1", "Gent", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("a39b1971-fc82-49b2-809a-444105e03c8d"), "Gent-Dampoort", "Oktrooiplein 10", "Gent", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("cf204af6-a407-47ea-af89-f0f989e7bd8a"), "Kortrijk", "Stationsplein 8", "Kortrijk", "West-Vlaanderen", "België");
// createStation(UUID.fromString("73df5f20-33e9-4518-bc23-3cf143c59198"), "Waregem", "Noorderlaan 71", "Waregem", "West-Vlaanderen", "België");
// createStation(UUID.fromString("bc51f294-6823-41cd-be82-d5ba2da4b04d"), "Aalter",<SUF>
// createStation(UUID.fromString("d6951807-1fcc-4966-aa30-d4f399685a90"), "De Pinte", "Stationsstraat 25", "De Pinte", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("1454163f-f24f-490f-9e06-f97ffaf008e3"), "Deinze", "Statieplein 4", "Deinze", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("4181c609-7ed5-473e-befe-8013cd75c24c"), "Eeklo", "Koningin Astridplein 1", "Eeklo", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("7b8d9768-7310-4b7d-b6e4-f58abbeac63e"), "Wondelgem", "Wondelgemstationplein 36", "Wondelgem", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("5514be96-c4f1-4dd7-ace4-ac5cbd29c17d"), "Oudenaarde", "Stationplein 1 Gewest", "Oudenaarde", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("5b659978-1c39-4372-97ec-a6e4d1418ef3"), "Zottegem", "Stationsplein 12", "Zottegem", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("b44c17fc-6df1-4808-83d6-838f5637c9c7"), "Denderleeuw", "Stationsplein", "Denderleeuw", "Oost-Vlaanderen", "België");
// createStation(UUID.fromString("05cce0f7-1409-4224-926a-db3b4c4a8ce5"), "Brussel-Zuid", "Fonsnylaan 47b", "Brussel", "Brussels", "België");
};
}
@Transactional(isolation = Isolation.SERIALIZABLE)
public void createStation(UUID id, String name, String street, String city, String province, String country) {
Address address = new Address(street, city, province, country);
Station station = new Station(name, address);
station.setId(id);
Platform p1 = new Platform(1);
Platform p2 = new Platform(2);
Platform p3 = new Platform(3);
platformRepository.save(p1);
platformRepository.save(p2);
platformRepository.save(p3);
station.getPlatforms().add(p1);
station.getPlatforms().add(p2);
station.getPlatforms().add(p3);
stationRepository.save(station);
p1.setStation(station);
p2.setStation(station);
p3.setStation(station);
platformRepository.save(p1);
platformRepository.save(p2);
platformRepository.save(p3);
logger.info("Station: " + station.toString());
}
}
|
65271_19 | package com.polafix.polafix;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import com.polafix.polafix.pojos.Balance;
import com.polafix.polafix.pojos.Chapter;
import com.polafix.polafix.pojos.Charge;
import com.polafix.polafix.pojos.Season;
import com.polafix.polafix.pojos.Serie;
import com.polafix.polafix.pojos.SerieUser;
import com.polafix.polafix.pojos.Subscription;
import com.polafix.polafix.pojos.Type;
import com.polafix.polafix.pojos.User;
public class test {
private ArrayList<User> users = new ArrayList<User>();
private ArrayList<Serie> series = new ArrayList<Serie>();
private String email = "[email protected]";
private Subscription type = Subscription.NOTSUBSCRIBED;
private String name ="ANNA";
private String surname = "BIANCHI";
private String IBAN = "xxxxxxxxxxxxx";
private String date_string = "20/09/1990";
//private String idSerie = "@seriexx";
private String serieName = "Lost";
private Type typeSerie = Type.SILVER;
private String description = ".........";
public void setSerie(Serie lost, Season lost1, ArrayList<Chapter> chapters){
for(int i=0; i<chapters.size(); i++){
lost1.addChapter(chapters.get(i));
}
lost.addSeason(lost1);
}
public boolean addUser(User utente){
if(users.isEmpty()){
users.add(utente);
return true;
}
else{
if(users.contains(utente)){
System.out.println("Utente già nel sistema");
return false;
}
else{
users.add(utente);
return true;
}
}
}
public boolean addSerie(Serie serie){
if(series.isEmpty()){
series.add(serie);
return true;
}
else{
if(series.contains(serie)){
System.out.println("Serie già nel catalogo");
return false;
}
else{
series.add(serie);
return true;
}
}
}
//Test on the singole method of the User class to see if it's implemented well
@Test
public void testUser(){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
assertEquals(true, addUser(utente));
assertEquals("[email protected]" ,utente.getEmail());
assertEquals(Subscription.NOTSUBSCRIBED, utente.getType());
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getEnded().size());
assertEquals(0, utente.getStarted().size());
}
//Test on the singole method of the Serie class to see if it's implemented well
@Test
public void testSerie(){
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
assertEquals(true, addSerie(lost));
assertEquals("Lost", lost.getName());
assertEquals(Type.SILVER, lost.getType());
assertEquals(1, lost.getSeasons().size());
assertEquals(3, lost.getSeason(1).getChapters().size());
assertEquals("lost1_1", lost.getSeason(1).getChapter(1).getTitle());
assertEquals("lost1_2", lost.getSeason(1).getChapter(2).getTitle());
assertEquals("lost1_3", lost.getSeason(1).getChapter(3).getTitle());
}
@Test
public void addSerie(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//User add a serie in his lists of series
utente.addSerie(lost);
SerieUser lost_user = new SerieUser(lost);
//serieUtente.addChapterSeen(lost1, lost1_1);
assertEquals(1, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(lost_user, utente.getInlist().get(0));
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 1, 1);
System.out.println(utente.getInlist().size());
assertEquals(1, utente.getStarted().size());
assertEquals(0, utente.getInlist().size());
Charge expected = new Charge(LocalDate.now(), lost.getName(), 1, 1, lost.getType().getprice());
assertEquals(1, utente.getLastBalance(utente.getBalances()).getAllCharges().size());
assertEquals(expected, utente.getLastBalance(utente.getBalances()).getAllCharges().get(0));
assertEquals(lost_user.getSerie(), utente.getStarted().get(0).getSerie());
//assertEquals(lost_user, utente.viewSerieUser(utente.getStarted(), "Lost"));
//Verify state chapters
lost_user.addChapterSeen(1, 1);
assertEquals(lost_user.getUserChapters(), utente.getStarted().get(0).getUserChapters());
//View last chapter -> verify ended
utente.selectChapter(lost_user, 1, 3);
expected = new Charge(LocalDate.now(), lost.getName(), 1, 3, lost.getType().getprice());
assertEquals(1, utente.getEnded().size());
assertEquals(lost_user.getSerie(), utente.getEnded().get(0).getSerie());
//Verify started and inlist are empty
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getInlist().size());
assertEquals(1.50, utente.getLastBalance(utente.getBalances()).getAmount());
}
@Test
public void testBalances(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//Verify different balances
LocalDate gennaio = LocalDate.of(2023, 01, 05);
LocalDate febbraio = LocalDate.of(2023, 02, 21);
Charge chargeGennaio = new Charge(gennaio, lost.getName(), 1, 1, lost.getType().getprice());
Charge chargeFebbraio = new Charge(gennaio, lost.getName(), 1, 2, lost.getType().getprice());
Balance bg = new Balance(0, gennaio.getMonth(), Year.of(gennaio.getYear()));
Balance bf = new Balance(0, febbraio.getMonth(), Year.of(febbraio.getYear()));
bg.addCharge(chargeGennaio);
bf.addCharge(chargeFebbraio);
utente.getBalances().add(bg);
utente.getBalances().add(bf);
assertEquals(bg, utente.getHistoryBalance(gennaio.getMonth(), Year.of(gennaio.getYear())));
assertEquals(chargeGennaio, utente.getHistoryBalance(gennaio.getMonth(), Year.of(gennaio.getYear())).getAllCharges().get(0));
assertEquals(0.75, bg.getAmount());
assertEquals(bf, utente.getHistoryBalance(febbraio.getMonth(), Year.of(febbraio.getYear())));
assertEquals(chargeFebbraio, utente.getHistoryBalance(febbraio.getMonth(), Year.of(febbraio.getYear())).getAllCharges().get(0));
assertEquals(0.75, bf.getAmount());
}
@Test
public void testMoreSeasons(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
//Season 1
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//Season 2
Season lost2 = new Season("Lost2", 2);
Chapter lost2_1 = new Chapter(1, "lost2_1", description);
Chapter lost2_2 = new Chapter(2, "lost2_2", description);
Chapter lost2_3 = new Chapter(3, "lost2_3", description);
ArrayList<Chapter> chapters2 = new ArrayList<Chapter>();
chapters2.add(lost2_1);
chapters2.add(lost2_2);
chapters2.add(lost2_3);
setSerie(lost, lost2, chapters2);
//User add a serie in his lists of series
utente.addSerie(lost);
SerieUser lost_user = new SerieUser(lost);
assertEquals("Lost1", lost_user.getSerie().getSeason(1).getTitle());
assertEquals("Lost2", lost_user.getSerie().getSeason(2).getTitle());
assertEquals(3, lost_user.getSerie().getSeason(1).getChapters().size());
assertEquals(3, lost_user.getSerie().getSeason(2).getChapters().size());
//serieUtente.addChapterSeen(lost1, lost1_1);
assertEquals(1, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(lost_user, utente.getInlist().get(0));
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 1, 3);
assertEquals(0, utente.getInlist().size());
assertEquals(1, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(2, utente.getStarted().get(0).getCurrentSeason());
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 2, 3);
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(1, utente.getEnded().size());
assertEquals(1, utente.getEnded().get(0).getCurrentSeason());
utente.selectChapter(lost_user, 2, 1);
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(1, utente.getEnded().size());
assertEquals(2, utente.getEnded().get(0).getCurrentSeason());
}
}
| Gioo14/_polafix_ | polafixBackEnd/polafix/polafix/src/test/java/com/polafix/polafix/test.java | 3,950 | //serieUtente.addChapterSeen(lost1, lost1_1); | line_comment | nl | package com.polafix.polafix;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import com.polafix.polafix.pojos.Balance;
import com.polafix.polafix.pojos.Chapter;
import com.polafix.polafix.pojos.Charge;
import com.polafix.polafix.pojos.Season;
import com.polafix.polafix.pojos.Serie;
import com.polafix.polafix.pojos.SerieUser;
import com.polafix.polafix.pojos.Subscription;
import com.polafix.polafix.pojos.Type;
import com.polafix.polafix.pojos.User;
public class test {
private ArrayList<User> users = new ArrayList<User>();
private ArrayList<Serie> series = new ArrayList<Serie>();
private String email = "[email protected]";
private Subscription type = Subscription.NOTSUBSCRIBED;
private String name ="ANNA";
private String surname = "BIANCHI";
private String IBAN = "xxxxxxxxxxxxx";
private String date_string = "20/09/1990";
//private String idSerie = "@seriexx";
private String serieName = "Lost";
private Type typeSerie = Type.SILVER;
private String description = ".........";
public void setSerie(Serie lost, Season lost1, ArrayList<Chapter> chapters){
for(int i=0; i<chapters.size(); i++){
lost1.addChapter(chapters.get(i));
}
lost.addSeason(lost1);
}
public boolean addUser(User utente){
if(users.isEmpty()){
users.add(utente);
return true;
}
else{
if(users.contains(utente)){
System.out.println("Utente già nel sistema");
return false;
}
else{
users.add(utente);
return true;
}
}
}
public boolean addSerie(Serie serie){
if(series.isEmpty()){
series.add(serie);
return true;
}
else{
if(series.contains(serie)){
System.out.println("Serie già nel catalogo");
return false;
}
else{
series.add(serie);
return true;
}
}
}
//Test on the singole method of the User class to see if it's implemented well
@Test
public void testUser(){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
assertEquals(true, addUser(utente));
assertEquals("[email protected]" ,utente.getEmail());
assertEquals(Subscription.NOTSUBSCRIBED, utente.getType());
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getEnded().size());
assertEquals(0, utente.getStarted().size());
}
//Test on the singole method of the Serie class to see if it's implemented well
@Test
public void testSerie(){
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
assertEquals(true, addSerie(lost));
assertEquals("Lost", lost.getName());
assertEquals(Type.SILVER, lost.getType());
assertEquals(1, lost.getSeasons().size());
assertEquals(3, lost.getSeason(1).getChapters().size());
assertEquals("lost1_1", lost.getSeason(1).getChapter(1).getTitle());
assertEquals("lost1_2", lost.getSeason(1).getChapter(2).getTitle());
assertEquals("lost1_3", lost.getSeason(1).getChapter(3).getTitle());
}
@Test
public void addSerie(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//User add a serie in his lists of series
utente.addSerie(lost);
SerieUser lost_user = new SerieUser(lost);
//serieUtente.addChapterSeen(lost1, lost1_1);
assertEquals(1, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(lost_user, utente.getInlist().get(0));
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 1, 1);
System.out.println(utente.getInlist().size());
assertEquals(1, utente.getStarted().size());
assertEquals(0, utente.getInlist().size());
Charge expected = new Charge(LocalDate.now(), lost.getName(), 1, 1, lost.getType().getprice());
assertEquals(1, utente.getLastBalance(utente.getBalances()).getAllCharges().size());
assertEquals(expected, utente.getLastBalance(utente.getBalances()).getAllCharges().get(0));
assertEquals(lost_user.getSerie(), utente.getStarted().get(0).getSerie());
//assertEquals(lost_user, utente.viewSerieUser(utente.getStarted(), "Lost"));
//Verify state chapters
lost_user.addChapterSeen(1, 1);
assertEquals(lost_user.getUserChapters(), utente.getStarted().get(0).getUserChapters());
//View last chapter -> verify ended
utente.selectChapter(lost_user, 1, 3);
expected = new Charge(LocalDate.now(), lost.getName(), 1, 3, lost.getType().getprice());
assertEquals(1, utente.getEnded().size());
assertEquals(lost_user.getSerie(), utente.getEnded().get(0).getSerie());
//Verify started and inlist are empty
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getInlist().size());
assertEquals(1.50, utente.getLastBalance(utente.getBalances()).getAmount());
}
@Test
public void testBalances(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//Verify different balances
LocalDate gennaio = LocalDate.of(2023, 01, 05);
LocalDate febbraio = LocalDate.of(2023, 02, 21);
Charge chargeGennaio = new Charge(gennaio, lost.getName(), 1, 1, lost.getType().getprice());
Charge chargeFebbraio = new Charge(gennaio, lost.getName(), 1, 2, lost.getType().getprice());
Balance bg = new Balance(0, gennaio.getMonth(), Year.of(gennaio.getYear()));
Balance bf = new Balance(0, febbraio.getMonth(), Year.of(febbraio.getYear()));
bg.addCharge(chargeGennaio);
bf.addCharge(chargeFebbraio);
utente.getBalances().add(bg);
utente.getBalances().add(bf);
assertEquals(bg, utente.getHistoryBalance(gennaio.getMonth(), Year.of(gennaio.getYear())));
assertEquals(chargeGennaio, utente.getHistoryBalance(gennaio.getMonth(), Year.of(gennaio.getYear())).getAllCharges().get(0));
assertEquals(0.75, bg.getAmount());
assertEquals(bf, utente.getHistoryBalance(febbraio.getMonth(), Year.of(febbraio.getYear())));
assertEquals(chargeFebbraio, utente.getHistoryBalance(febbraio.getMonth(), Year.of(febbraio.getYear())).getAllCharges().get(0));
assertEquals(0.75, bf.getAmount());
}
@Test
public void testMoreSeasons(){
//Create a new user
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(date_string);
try {
date = formatter.parse(date_string);
} catch (ParseException e) {
e.printStackTrace();
}
User utente = new User(email, type, IBAN, name, surname, date);
//Create a new serie
Serie lost = new Serie(serieName, typeSerie, description);
//Season 1
Season lost1 = new Season("Lost1", 1);
Chapter lost1_1 = new Chapter(1, "lost1_1", description);
Chapter lost1_2 = new Chapter(2, "lost1_2", description);
Chapter lost1_3 = new Chapter(3, "lost1_3", description);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
chapters.add(lost1_1);
chapters.add(lost1_2);
chapters.add(lost1_3);
setSerie(lost, lost1, chapters);
//Season 2
Season lost2 = new Season("Lost2", 2);
Chapter lost2_1 = new Chapter(1, "lost2_1", description);
Chapter lost2_2 = new Chapter(2, "lost2_2", description);
Chapter lost2_3 = new Chapter(3, "lost2_3", description);
ArrayList<Chapter> chapters2 = new ArrayList<Chapter>();
chapters2.add(lost2_1);
chapters2.add(lost2_2);
chapters2.add(lost2_3);
setSerie(lost, lost2, chapters2);
//User add a serie in his lists of series
utente.addSerie(lost);
SerieUser lost_user = new SerieUser(lost);
assertEquals("Lost1", lost_user.getSerie().getSeason(1).getTitle());
assertEquals("Lost2", lost_user.getSerie().getSeason(2).getTitle());
assertEquals(3, lost_user.getSerie().getSeason(1).getChapters().size());
assertEquals(3, lost_user.getSerie().getSeason(2).getChapters().size());
//serieUtente.addChapterSeen(lost1, lost1_1);<SUF>
assertEquals(1, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(lost_user, utente.getInlist().get(0));
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 1, 3);
assertEquals(0, utente.getInlist().size());
assertEquals(1, utente.getStarted().size());
assertEquals(0, utente.getEnded().size());
assertEquals(2, utente.getStarted().get(0).getCurrentSeason());
//User select a chapter: the chapter state change and the chapter is added at the balance
utente.selectChapter(lost_user, 2, 3);
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(1, utente.getEnded().size());
assertEquals(1, utente.getEnded().get(0).getCurrentSeason());
utente.selectChapter(lost_user, 2, 1);
assertEquals(0, utente.getInlist().size());
assertEquals(0, utente.getStarted().size());
assertEquals(1, utente.getEnded().size());
assertEquals(2, utente.getEnded().get(0).getCurrentSeason());
}
}
|
60512_4 | package practicumopdracht.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import practicumopdracht.MainApplication;
import practicumopdracht.comparators.PrijsComparator;
import practicumopdracht.comparators.ProductComparator;
import practicumopdracht.models.Product;
import practicumopdracht.models.Winkel;
import practicumopdracht.views.View;
import practicumopdracht.views.ProductView;
import practicumopdracht.views.WinkelView;
import java.time.LocalDate;
import java.util.Collections;
import static practicumopdracht.MainApplication.*;
/**
* Controller class voor de producten.
*
* Deze controller klasse handelt alle acties af die betrekking hebben tot de producten. De klasse bevat de volgende acties:
*
* - Sorteren van de producten op naam en prijs
* - Filteren van de producten op winkel
* - Zoeken naar producten op naam
* - Toevoegen van nieuwe producten
* - Verwijderen van bestaande producten
* - Valideren van de invoer van de gebruiker
* - Terugkeren naar het Winkel overzicht scherm
* - Laden, opslaan en afsluiten van een bestand
*
* De controller erft van de abstracte Controller klasse en implementeert de getView() methode.
*
* @author Marco
*/
public class ProductController extends Controller{
private final ProductView view;
private ObservableList<Winkel> winkelObservableList = FXCollections.observableList(MainApplication.getWinkelDAO().getAll());
private ObservableList<Product> productObservableList = FXCollections.observableArrayList(MainApplication.getProductDAO().getAll());
private FilteredList<Product> productFilteredList = new FilteredList<>(productObservableList);
private String selectedRadioButton;
/**
* Constructor voor de ProductController. Hierin worden de action handlers en overige functionaliteiten geinitialiseerd.
*/
public ProductController(){
view = new ProductView();
setWinkelComboBox();
//zet de default sortering op naam van A naar Z
selectedRadioButton = "NaamAZ";
view.getTerugButton().setOnAction(actionEvent -> handleTerugButton());
view.getProductOpslaanButton().setOnAction(actionEvent -> handleProductToevoegenButton());
view.getVerwijderProductButton().setOnAction(actionEvent -> handleVerwijderButton());
view.getProductNieuwButton().setOnAction(actionEvent -> handleNieuwButton());
view.getListView().getSelectionModel().selectedItemProperty().addListener((
observableValue, productOud, productNieuw) -> handleSelectie(productNieuw));
view.getListView().setItems(productFilteredList);
view.getZoekButtonView().setOnAction(actionEvent -> handleZoeken());
view.getWinkelComboBox().setOnAction(actionEvent -> handleFilterWinkel());
view.getBestandLaden().setOnAction(actionEvent -> handleBestand("Laden"));
view.getBestandOpslaan().setOnAction(actionEvent -> handleBestand("Opslaan"));
view.getBestandAfsluiten().setOnAction(actionEvent -> handleBestand("Afsluiten"));
view.getDetailPrijsZAButton().setOnAction(actionEvent -> setSelectedRadioButton("PrijsZA"));
view.getDetailPrijsAZButton().setOnAction(actionEvent -> setSelectedRadioButton("PrijsAZ"));
view.getDetailNaamZAButton().setOnAction(actionEvent -> setSelectedRadioButton("NaamZA"));
view.getDetailNaamAZButton().setOnAction(actionEvent -> setSelectedRadioButton("NaamAZ"));
handleToggle();
}
/**
Filter de producten in de productFilteredList op basis van de zoekwaarde in het zoekveld.
Als er geen zoekwaarde is ingevuld, wordt er geen filter toegepast en worden alle producten getoond.
De zoekwaarde wordt omgezet in kleine letters en vergeleken met de namen van de producten in de lijst.
*/
private void handleZoeken(){
productFilteredList.setPredicate(product ->{
/*controleer eerst of er wel een text is ingevuld om naar te zoeken anders wordt true teruggegeven hiermee
wordt er geen filter toegepast en alles laten zien*/
if(view.getZoekTextField().getText() == null || view.getZoekTextField().getText().isEmpty()){
return product.getHoortBijWinkel().equals(view.getWinkelComboBox().getValue());
}
/*Als er iets is ingevuld wordt de zoekwaarde omgezet in kleineletter en worden alle producten teruggeven naar
* de productFilteredList waard de naam de zoekwaarde bevat*/
String kleineLetterZoekwaarde = view.getZoekTextField().getText().toLowerCase();
return product.getNaam().toLowerCase().contains(kleineLetterZoekwaarde);
});
view.getListView().refresh();
}
/**
Deze methode handelt de actie af van het selecteren van een menu-item in de bestandsmenu.
Afhankelijk van de meegegeven actie-string worden verschillende acties uitgevoerd:
"Laden": Het inladen van de data uit het bestand naar de applicatie.
"Opslaan": Het opslaan van de huidige applicatie-data naar een bestand.
"Afsluiten": Het afsluiten van de applicatie.
Bij het uitvoeren van een actie wordt de winkelObservableList en productObservableList geüpdatet
met de gegevens uit de database. Daarnaast wordt de toggle-status opnieuw ingesteld en wordt
de lijst van producten vernieuwd en ververst op het scherm.
@param actie de te ondernemen actie ("Laden", "Opslaan", "Afsluiten")
*/
private void handleBestand(String actie){
menuHelper.handleBestand(actie);
if (actie == "Laden"){
winkelObservableList = FXCollections.observableArrayList(MainApplication.getWinkelDAO().getAll());
view.getWinkelComboBox().setItems(winkelObservableList);
productObservableList = FXCollections.observableArrayList(MainApplication.getProductDAO().getAll());
handleToggle();
view.getListView().setItems(productObservableList);
view.getListView().setItems(productFilteredList);
handleFilterWinkel();
view.getListView().refresh();
}
}
/**
Set de geselecteerde radiobutton en voert de handleToggle functie uit om te sorteren.
@param selectedRadioButton de naam van de geselecteerde radiobutton.
*/
private void setSelectedRadioButton(String selectedRadioButton){
this.selectedRadioButton = selectedRadioButton;
handleToggle();
}
/**
Deze methode selecteert de juiste sorteermethode op basis van de geselecteerde radiobutton.
De sorteermethode wordt toegepast op de observableList van Producten en de ListView wordt ververst.
*/
private void handleToggle(){
switch (selectedRadioButton) {
case "NaamAZ" -> Collections.sort(productObservableList, new ProductComparator(true));
case "NaamZA" -> Collections.sort(productObservableList, new ProductComparator(false));
case "PrijsAZ" -> Collections.sort(productObservableList, new PrijsComparator(true));
case "PrijsZA" -> Collections.sort(productObservableList, new PrijsComparator(false));
default -> System.err.println("Er is iets mis gegaan met het sorteren van de producten!");
}
}
/**
Filtert de lijst van producten op de geselecteerde winkel in de winkelComboBox. Als er geen winkel is geselecteerd,
worden alle producten getoond.
*/
private void handleFilterWinkel(){
productFilteredList.setPredicate(product -> {
if (view.getWinkelComboBox().getValue() == null){
return true;
}
return product.getHoortBijWinkel().equals(view.getWinkelComboBox().getValue());
});
view.getListView().refresh();
}
/**
Stelt de combobox van winkels in met de gegeven winkelObservableList.
Probeert de waarde van de geselecteerde winkel te krijgen uit de WinkelListView en past de filter voor de producten aan op basis van de geselecteerde winkel.
*/
private void setWinkelComboBox(){
view.getWinkelComboBox().setItems(winkelObservableList);
try {
view.getWinkelComboBox().setValue(WinkelView.getWinkelListView().getSelectionModel().getSelectedItem());
handleFilterWinkel();
}catch (Exception e){
System.err.println("Tijdens het presetten van de winkelcombobox ging iets mis!");
}
}
/**
Zet alle velden van het ProductView object op leeg of de default waarde.
*/
private void handleNieuwButton(){
view.getProductNaamTextField().clear();
view.getVariantTextField().clear();
view.getMerkTextField().clear();
view.getAanbiedingCheckBox().setSelected(false);
view.getInhoudTextField().clear();
view.getPrijsTextField().clear();
view.getListView().getSelectionModel().clearSelection();
}
/**
Vult de velden van het ProductView object met de gegevens van de geselecteerde Product en past de filter voor de producten aan op basis van de geselecteerde winkel.
@param productNieuw Het geselecteerde Product dat weergegeven moet worden.
*/
private void handleSelectie(Product productNieuw){
if (productNieuw == null){
return;
}
Product product = productNieuw;
view.getProductNaamTextField().setText(product.getNaam());
view.getVariantTextField().setText(product.getVariant());
view.getMerkTextField().setText(product.getMerk());
view.getDatumDatePicker().setValue(product.getLaatstePrijsWijziging());
view.getAanbiedingCheckBox().setSelected(product.isInAanbieding());
view.getInhoudTextField().setText(Integer.toString(product.getInhoud()));
view.getPrijsTextField().setText(Double.toString(product.getPrijs()));
view.getWinkelComboBox().setValue(product.getHoortBijWinkel());
}
/**
Handelt de actie af wanneer er op de "Product toevoegen" knop wordt geklikt.
Eerst worden de ingevulde gegevens gevalideerd. Vervolgens worden de gegevens opgehaald uit de tekstvelden,
comboboxen, checkboxen en datepicker en worden ze gebruikt om een nieuw Product object te maken. Dit object wordt
toegevoegd aan de lijst van producten en aan de database toegevoegd. Als er al een product geselecteerd was in de lijst,
wordt deze geüpdatet in plaats van dat er een nieuw product wordt aangemaakt. Daarna wordt de lijst van producten
gesorteerd en wordt de toggle handle methode aangeroepen.
*/
private void handleProductToevoegenButton(){
if(valideerInvulling()){
String naam = view.getProductNaamTextField().getText();
String variant = view.getVariantTextField().getText();
String merk = view.getMerkTextField().getText();
int inhoud = 0;
if (view.getInhoudEenheidComboBox().getValue() == "gram"){
inhoud = Integer.parseInt(view.getInhoudTextField().getText());
}else {
inhoud = Integer.parseInt(view.getInhoudTextField().getText() ) * 1000;
}
double prijs = Double.parseDouble(view.getPrijsTextField().getText());
boolean isAanbieding = view.getAanbiedingCheckBox().isSelected();
LocalDate laatstePrijsWijziging = view.getDatumDatePicker().getValue();
Winkel winkel = view.getWinkelComboBox().getValue();
Product productUitListView = view.getListView().getSelectionModel().getSelectedItem();
if(productUitListView == null){
Product product = new Product(naam, variant,merk,inhoud,prijs,isAanbieding,laatstePrijsWijziging,winkel);
productObservableList.add(product);
getProductDAO().addOrUpdate(product);
view.getListView().refresh();
view.getListView().getSelectionModel().selectLast();
}else{
productUitListView.setProductNieuweWaard(naam, variant,merk,inhoud,prijs,isAanbieding,laatstePrijsWijziging);
view.getListView().refresh();
}
handleToggle();
}else {
MainApplication.geefInformatieAlert("Niet alles ingevuld!","wel alles invullen heh!");
}
}
/**
Handelt de actie af wanneer er op de "Verwijderen" knop wordt geklikt. Als er een product is geselecteerd in de lijst,
wordt deze verwijderd uit de lijst van producten en uit de database. Als er geen product is geselecteerd, gebeurt er niets.
Als het verwijderen niet lukt om welke reden dan ook, wordt een informatiebericht getoond met de foutmelding.
*/
private void handleVerwijderButton(){
if (geefBevestigAlert("Verwijderen!", "Weet u zeker dat u dit wilt verwijderen")){
try{
Product product = view.getListView().getSelectionModel().getSelectedItem();
getProductDAO().remove(product);
productObservableList.remove(product);
view.getListView().refresh();
}catch (Exception e){
geefInformatieAlert("Verwijder fout", "Er ging iets fout tijdens het verwijder, " +
"zorg dat je een product selecteerd en dan verwijderd!");
}
}
}
/**
* Als op terug geklikt wordt, wordt door de switchcontroller van de mainapplicatie de controller gewisseld naar de WinkelController.
*/
private void handleTerugButton(){
switchController(new WinkelController());
}
/**
* Als deze methode wordt aangeroepen wordt de view teruggegeven
* @return de view
*/
@Override
public View getView() {
return view;
}
/**
Valideert of alle tekstvelden correct zijn ingevuld bij het toevoegen of wijzigen van een product.
zo niet komt er een rode rand eromheen.
@return Boolean waarde die aangeeft of de invoer correct is of niet.
*/
private boolean valideerInvulling(){
boolean invullenCorrect = true;
String naam = view.getProductNaamTextField().getText();
if (naam == ""){
view.getProductNaamTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getProductNaamTextField().setStyle("-fx-border-color: none");
}
String merk = view.getMerkTextField().getText();
if (merk == ""){
view.getMerkTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getMerkTextField().setStyle("-fx-border-color: none");
}
try{
int inhoud = Integer.parseInt(view.getInhoudTextField().getText());
if (inhoud == 0){
view.getInhoudTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getInhoudTextField().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getInhoudTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
try {
double prijs = Double.parseDouble(view.getPrijsTextField().getText());
if (prijs == 0) {
view.getPrijsTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getPrijsTextField().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getPrijsTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
String inhoudEenheid = view.getInhoudEenheidComboBox().getValue();
if (inhoudEenheid != "gram" && inhoudEenheid != "kg"){
geefInformatieAlert("Waarde fout","Er was een fout tijdens het toevoegen van het" +
" product, controlleer of alle waardes kloppen!");
invullenCorrect = false;
}
try {
LocalDate laatstePrijsWijziging = view.getDatumDatePicker().getValue();
if (laatstePrijsWijziging == null || laatstePrijsWijziging.isAfter(LocalDate.now())) {
view.getDatumDatePicker().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getDatumDatePicker().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getDatumDatePicker().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
try {
Winkel winkel = view.getWinkelComboBox().getValue();
if (winkel == null) {
view.getWinkelComboBox().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getWinkelComboBox().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getWinkelComboBox().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
return invullenCorrect;
}
}
| GitMarcoo/OOP-Practical-Assignment | src/practicumopdracht/Controllers/ProductController.java | 5,015 | /*controleer eerst of er wel een text is ingevuld om naar te zoeken anders wordt true teruggegeven hiermee
wordt er geen filter toegepast en alles laten zien*/ | block_comment | nl | package practicumopdracht.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import practicumopdracht.MainApplication;
import practicumopdracht.comparators.PrijsComparator;
import practicumopdracht.comparators.ProductComparator;
import practicumopdracht.models.Product;
import practicumopdracht.models.Winkel;
import practicumopdracht.views.View;
import practicumopdracht.views.ProductView;
import practicumopdracht.views.WinkelView;
import java.time.LocalDate;
import java.util.Collections;
import static practicumopdracht.MainApplication.*;
/**
* Controller class voor de producten.
*
* Deze controller klasse handelt alle acties af die betrekking hebben tot de producten. De klasse bevat de volgende acties:
*
* - Sorteren van de producten op naam en prijs
* - Filteren van de producten op winkel
* - Zoeken naar producten op naam
* - Toevoegen van nieuwe producten
* - Verwijderen van bestaande producten
* - Valideren van de invoer van de gebruiker
* - Terugkeren naar het Winkel overzicht scherm
* - Laden, opslaan en afsluiten van een bestand
*
* De controller erft van de abstracte Controller klasse en implementeert de getView() methode.
*
* @author Marco
*/
public class ProductController extends Controller{
private final ProductView view;
private ObservableList<Winkel> winkelObservableList = FXCollections.observableList(MainApplication.getWinkelDAO().getAll());
private ObservableList<Product> productObservableList = FXCollections.observableArrayList(MainApplication.getProductDAO().getAll());
private FilteredList<Product> productFilteredList = new FilteredList<>(productObservableList);
private String selectedRadioButton;
/**
* Constructor voor de ProductController. Hierin worden de action handlers en overige functionaliteiten geinitialiseerd.
*/
public ProductController(){
view = new ProductView();
setWinkelComboBox();
//zet de default sortering op naam van A naar Z
selectedRadioButton = "NaamAZ";
view.getTerugButton().setOnAction(actionEvent -> handleTerugButton());
view.getProductOpslaanButton().setOnAction(actionEvent -> handleProductToevoegenButton());
view.getVerwijderProductButton().setOnAction(actionEvent -> handleVerwijderButton());
view.getProductNieuwButton().setOnAction(actionEvent -> handleNieuwButton());
view.getListView().getSelectionModel().selectedItemProperty().addListener((
observableValue, productOud, productNieuw) -> handleSelectie(productNieuw));
view.getListView().setItems(productFilteredList);
view.getZoekButtonView().setOnAction(actionEvent -> handleZoeken());
view.getWinkelComboBox().setOnAction(actionEvent -> handleFilterWinkel());
view.getBestandLaden().setOnAction(actionEvent -> handleBestand("Laden"));
view.getBestandOpslaan().setOnAction(actionEvent -> handleBestand("Opslaan"));
view.getBestandAfsluiten().setOnAction(actionEvent -> handleBestand("Afsluiten"));
view.getDetailPrijsZAButton().setOnAction(actionEvent -> setSelectedRadioButton("PrijsZA"));
view.getDetailPrijsAZButton().setOnAction(actionEvent -> setSelectedRadioButton("PrijsAZ"));
view.getDetailNaamZAButton().setOnAction(actionEvent -> setSelectedRadioButton("NaamZA"));
view.getDetailNaamAZButton().setOnAction(actionEvent -> setSelectedRadioButton("NaamAZ"));
handleToggle();
}
/**
Filter de producten in de productFilteredList op basis van de zoekwaarde in het zoekveld.
Als er geen zoekwaarde is ingevuld, wordt er geen filter toegepast en worden alle producten getoond.
De zoekwaarde wordt omgezet in kleine letters en vergeleken met de namen van de producten in de lijst.
*/
private void handleZoeken(){
productFilteredList.setPredicate(product ->{
/*controleer eerst of<SUF>*/
if(view.getZoekTextField().getText() == null || view.getZoekTextField().getText().isEmpty()){
return product.getHoortBijWinkel().equals(view.getWinkelComboBox().getValue());
}
/*Als er iets is ingevuld wordt de zoekwaarde omgezet in kleineletter en worden alle producten teruggeven naar
* de productFilteredList waard de naam de zoekwaarde bevat*/
String kleineLetterZoekwaarde = view.getZoekTextField().getText().toLowerCase();
return product.getNaam().toLowerCase().contains(kleineLetterZoekwaarde);
});
view.getListView().refresh();
}
/**
Deze methode handelt de actie af van het selecteren van een menu-item in de bestandsmenu.
Afhankelijk van de meegegeven actie-string worden verschillende acties uitgevoerd:
"Laden": Het inladen van de data uit het bestand naar de applicatie.
"Opslaan": Het opslaan van de huidige applicatie-data naar een bestand.
"Afsluiten": Het afsluiten van de applicatie.
Bij het uitvoeren van een actie wordt de winkelObservableList en productObservableList geüpdatet
met de gegevens uit de database. Daarnaast wordt de toggle-status opnieuw ingesteld en wordt
de lijst van producten vernieuwd en ververst op het scherm.
@param actie de te ondernemen actie ("Laden", "Opslaan", "Afsluiten")
*/
private void handleBestand(String actie){
menuHelper.handleBestand(actie);
if (actie == "Laden"){
winkelObservableList = FXCollections.observableArrayList(MainApplication.getWinkelDAO().getAll());
view.getWinkelComboBox().setItems(winkelObservableList);
productObservableList = FXCollections.observableArrayList(MainApplication.getProductDAO().getAll());
handleToggle();
view.getListView().setItems(productObservableList);
view.getListView().setItems(productFilteredList);
handleFilterWinkel();
view.getListView().refresh();
}
}
/**
Set de geselecteerde radiobutton en voert de handleToggle functie uit om te sorteren.
@param selectedRadioButton de naam van de geselecteerde radiobutton.
*/
private void setSelectedRadioButton(String selectedRadioButton){
this.selectedRadioButton = selectedRadioButton;
handleToggle();
}
/**
Deze methode selecteert de juiste sorteermethode op basis van de geselecteerde radiobutton.
De sorteermethode wordt toegepast op de observableList van Producten en de ListView wordt ververst.
*/
private void handleToggle(){
switch (selectedRadioButton) {
case "NaamAZ" -> Collections.sort(productObservableList, new ProductComparator(true));
case "NaamZA" -> Collections.sort(productObservableList, new ProductComparator(false));
case "PrijsAZ" -> Collections.sort(productObservableList, new PrijsComparator(true));
case "PrijsZA" -> Collections.sort(productObservableList, new PrijsComparator(false));
default -> System.err.println("Er is iets mis gegaan met het sorteren van de producten!");
}
}
/**
Filtert de lijst van producten op de geselecteerde winkel in de winkelComboBox. Als er geen winkel is geselecteerd,
worden alle producten getoond.
*/
private void handleFilterWinkel(){
productFilteredList.setPredicate(product -> {
if (view.getWinkelComboBox().getValue() == null){
return true;
}
return product.getHoortBijWinkel().equals(view.getWinkelComboBox().getValue());
});
view.getListView().refresh();
}
/**
Stelt de combobox van winkels in met de gegeven winkelObservableList.
Probeert de waarde van de geselecteerde winkel te krijgen uit de WinkelListView en past de filter voor de producten aan op basis van de geselecteerde winkel.
*/
private void setWinkelComboBox(){
view.getWinkelComboBox().setItems(winkelObservableList);
try {
view.getWinkelComboBox().setValue(WinkelView.getWinkelListView().getSelectionModel().getSelectedItem());
handleFilterWinkel();
}catch (Exception e){
System.err.println("Tijdens het presetten van de winkelcombobox ging iets mis!");
}
}
/**
Zet alle velden van het ProductView object op leeg of de default waarde.
*/
private void handleNieuwButton(){
view.getProductNaamTextField().clear();
view.getVariantTextField().clear();
view.getMerkTextField().clear();
view.getAanbiedingCheckBox().setSelected(false);
view.getInhoudTextField().clear();
view.getPrijsTextField().clear();
view.getListView().getSelectionModel().clearSelection();
}
/**
Vult de velden van het ProductView object met de gegevens van de geselecteerde Product en past de filter voor de producten aan op basis van de geselecteerde winkel.
@param productNieuw Het geselecteerde Product dat weergegeven moet worden.
*/
private void handleSelectie(Product productNieuw){
if (productNieuw == null){
return;
}
Product product = productNieuw;
view.getProductNaamTextField().setText(product.getNaam());
view.getVariantTextField().setText(product.getVariant());
view.getMerkTextField().setText(product.getMerk());
view.getDatumDatePicker().setValue(product.getLaatstePrijsWijziging());
view.getAanbiedingCheckBox().setSelected(product.isInAanbieding());
view.getInhoudTextField().setText(Integer.toString(product.getInhoud()));
view.getPrijsTextField().setText(Double.toString(product.getPrijs()));
view.getWinkelComboBox().setValue(product.getHoortBijWinkel());
}
/**
Handelt de actie af wanneer er op de "Product toevoegen" knop wordt geklikt.
Eerst worden de ingevulde gegevens gevalideerd. Vervolgens worden de gegevens opgehaald uit de tekstvelden,
comboboxen, checkboxen en datepicker en worden ze gebruikt om een nieuw Product object te maken. Dit object wordt
toegevoegd aan de lijst van producten en aan de database toegevoegd. Als er al een product geselecteerd was in de lijst,
wordt deze geüpdatet in plaats van dat er een nieuw product wordt aangemaakt. Daarna wordt de lijst van producten
gesorteerd en wordt de toggle handle methode aangeroepen.
*/
private void handleProductToevoegenButton(){
if(valideerInvulling()){
String naam = view.getProductNaamTextField().getText();
String variant = view.getVariantTextField().getText();
String merk = view.getMerkTextField().getText();
int inhoud = 0;
if (view.getInhoudEenheidComboBox().getValue() == "gram"){
inhoud = Integer.parseInt(view.getInhoudTextField().getText());
}else {
inhoud = Integer.parseInt(view.getInhoudTextField().getText() ) * 1000;
}
double prijs = Double.parseDouble(view.getPrijsTextField().getText());
boolean isAanbieding = view.getAanbiedingCheckBox().isSelected();
LocalDate laatstePrijsWijziging = view.getDatumDatePicker().getValue();
Winkel winkel = view.getWinkelComboBox().getValue();
Product productUitListView = view.getListView().getSelectionModel().getSelectedItem();
if(productUitListView == null){
Product product = new Product(naam, variant,merk,inhoud,prijs,isAanbieding,laatstePrijsWijziging,winkel);
productObservableList.add(product);
getProductDAO().addOrUpdate(product);
view.getListView().refresh();
view.getListView().getSelectionModel().selectLast();
}else{
productUitListView.setProductNieuweWaard(naam, variant,merk,inhoud,prijs,isAanbieding,laatstePrijsWijziging);
view.getListView().refresh();
}
handleToggle();
}else {
MainApplication.geefInformatieAlert("Niet alles ingevuld!","wel alles invullen heh!");
}
}
/**
Handelt de actie af wanneer er op de "Verwijderen" knop wordt geklikt. Als er een product is geselecteerd in de lijst,
wordt deze verwijderd uit de lijst van producten en uit de database. Als er geen product is geselecteerd, gebeurt er niets.
Als het verwijderen niet lukt om welke reden dan ook, wordt een informatiebericht getoond met de foutmelding.
*/
private void handleVerwijderButton(){
if (geefBevestigAlert("Verwijderen!", "Weet u zeker dat u dit wilt verwijderen")){
try{
Product product = view.getListView().getSelectionModel().getSelectedItem();
getProductDAO().remove(product);
productObservableList.remove(product);
view.getListView().refresh();
}catch (Exception e){
geefInformatieAlert("Verwijder fout", "Er ging iets fout tijdens het verwijder, " +
"zorg dat je een product selecteerd en dan verwijderd!");
}
}
}
/**
* Als op terug geklikt wordt, wordt door de switchcontroller van de mainapplicatie de controller gewisseld naar de WinkelController.
*/
private void handleTerugButton(){
switchController(new WinkelController());
}
/**
* Als deze methode wordt aangeroepen wordt de view teruggegeven
* @return de view
*/
@Override
public View getView() {
return view;
}
/**
Valideert of alle tekstvelden correct zijn ingevuld bij het toevoegen of wijzigen van een product.
zo niet komt er een rode rand eromheen.
@return Boolean waarde die aangeeft of de invoer correct is of niet.
*/
private boolean valideerInvulling(){
boolean invullenCorrect = true;
String naam = view.getProductNaamTextField().getText();
if (naam == ""){
view.getProductNaamTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getProductNaamTextField().setStyle("-fx-border-color: none");
}
String merk = view.getMerkTextField().getText();
if (merk == ""){
view.getMerkTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getMerkTextField().setStyle("-fx-border-color: none");
}
try{
int inhoud = Integer.parseInt(view.getInhoudTextField().getText());
if (inhoud == 0){
view.getInhoudTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}else{
view.getInhoudTextField().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getInhoudTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
try {
double prijs = Double.parseDouble(view.getPrijsTextField().getText());
if (prijs == 0) {
view.getPrijsTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getPrijsTextField().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getPrijsTextField().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
String inhoudEenheid = view.getInhoudEenheidComboBox().getValue();
if (inhoudEenheid != "gram" && inhoudEenheid != "kg"){
geefInformatieAlert("Waarde fout","Er was een fout tijdens het toevoegen van het" +
" product, controlleer of alle waardes kloppen!");
invullenCorrect = false;
}
try {
LocalDate laatstePrijsWijziging = view.getDatumDatePicker().getValue();
if (laatstePrijsWijziging == null || laatstePrijsWijziging.isAfter(LocalDate.now())) {
view.getDatumDatePicker().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getDatumDatePicker().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getDatumDatePicker().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
try {
Winkel winkel = view.getWinkelComboBox().getValue();
if (winkel == null) {
view.getWinkelComboBox().setStyle("-fx-border-color: red");
invullenCorrect = false;
} else {
view.getWinkelComboBox().setStyle("-fx-border-color: none");
}
}catch (Exception error){
view.getWinkelComboBox().setStyle("-fx-border-color: red");
invullenCorrect = false;
}
return invullenCorrect;
}
}
|
151940_43 | package team181_alpha;
import java.util.ArrayList;
import java.util.Arrays;
import battlecode.common.Clock;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.Signal;
import battlecode.common.Team;
import team181_alpha.*;
public class ScoutClass extends RobotPlayer {
// Get the maximum number of tiles in one direction away in sensor radius
static int myDv = (int) Math.floor(Math.sqrt(myRobotType.sensorRadiusSquared));
static Direction[] cardinals = { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST };
static boolean[] haveOffsets = { false, false, false, false };
static Direction currentExploreDirection = Direction.NORTH;
static int numExploredDirections = 0;
static boolean haveBroadCastedMapBounds = false;
static ArrayList<MapLocation> knownDens = new ArrayList<MapLocation>();;
static int numKnownDens = 0;
// Enclosure for all of the exploration functions
static class Exploration {
// Dumb help function, please kill me and replace with a map
public static int returnCardinalIndex(Direction dir) throws GameActionException {
// Switch because no associative arrays, could map this instead, but
// that might cost more
switch (dir) {
case NORTH:
return 0;
case EAST:
return 1;
case SOUTH:
return 2;
case WEST:
return 3;
default:
GameActionException e = new GameActionException(null, "Not a valid cardinal direction.");
throw e;
}
}
// Given a direction, try to move that way, but avoid taking damage or
// going far into enemy LOF.
// General Scout exploration driver.
// Don't let scout get stuck in concave areas, or near swarms of allies.
public static void explore(Direction dirToMove) throws GameActionException {
if (rc.isCoreReady()) {
if (nearbyEnemies.length == 0) {
// There are no known enemy threats
if (rc.canMove(dirToMove)) {
rc.move(dirToMove);
} else if (rc.canMove(dirToMove.rotateLeft())) {
rc.move(dirToMove.rotateLeft());
} else if (rc.canMove(dirToMove.rotateRight())) {
rc.move(dirToMove.rotateRight());
}
} else {
// There are enemies within sight!
// Calculate least risking direction to move
MapLocation currLoc = rc.getLocation();
double leastRisk = Double.MAX_VALUE; // risks[0];
Direction leastRiskyDirection = Direction.NONE;
Direction[] allDirs = Direction.values();
MapLocation goalLoc = currLoc.add(dirToMove);
MapLocation leastRiskyLoc = goalLoc;
double[] risks = new double[allDirs.length];
for (int i = 0; i < allDirs.length; i++) {
// Check if can move in this direction
Direction currDir = allDirs[i];
if (rc.canMove(currDir)) {
// Can move in this direction
// Check attack risk value
MapLocation nextLoc = currLoc.add(currDir);
double risk = attackRisk(nextLoc);
risks[i] = risk;
// System.out.println("At location" +
// currLoc.toString() + " risk in direction " +
// currDir.toString() + " is: " +
// Double.toString(risk));
// Is this better?
// Bias towards moving the same direction, dirToMove
if (currDir.equals(dirToMove) && risk <= leastRisk) {
// At least as good
leastRisk = risk;
leastRiskyDirection = dirToMove;
leastRiskyLoc = nextLoc;
} else if (risk < leastRisk) {
// Better
leastRisk = risk;
leastRiskyDirection = allDirs[i];
leastRiskyLoc = nextLoc;
} else if (risk == leastRisk && (goalLoc.distanceSquaredTo(nextLoc) < goalLoc
.distanceSquaredTo(leastRiskyLoc))) {
// Equally as good but closer to the original
// dirToMove direction
leastRisk = risk;
leastRiskyDirection = allDirs[i];
leastRiskyLoc = nextLoc;
}
}
}
if (!leastRiskyDirection.equals(Direction.NONE)) {
// rc.setIndicatorString(2, "Retreating towards: " +
// leastRiskyDirection.toString());
rc.setIndicatorString(2, "Risk this turn is: " + Arrays.toString(risks));
rc.move(leastRiskyDirection);
}
}
}
}
/*
* Calculation the Attack risk value of moving to this location given
* the direction.
*
* Attack risk is currently the count of the number of enemies which
* will be within attack range of this location Ideal attack risk is 0
* (no risk of attack).
*
*/
public static double attackRisk(MapLocation loc) {
if (nearbyEnemies.length > 0) {
double totalRisk = 0.0;
for (RobotInfo r : nearbyEnemies) {
MapLocation enemyLoc = r.location;
RobotType enemyType = r.type;
int distAway = loc.distanceSquaredTo(enemyLoc);
int offsetBlocks = 2;
int offsetSquared = offsetBlocks * offsetBlocks;
int safeDist = (enemyType.attackRadiusSquared+offsetSquared);
if (enemyType.equals(RobotType.TURRET)) {
safeDist = RobotType.TURRET.sensorRadiusSquared + offsetSquared;
}
if (distAway <= safeDist) {
// If enemy has 0 attack power then risk = 0
// If Core delay is 0 then risk = numerator, and will be
// divided by each turn/core delay
double risk = ((safeDist - distAway) * r.attackPower)
/ (r.weaponDelay + 1.0);
totalRisk += risk;
}
}
// rc.setIndicatorString(2, "Risk this turn is: " +
// Double.toString(totalRisk));
// System.out.println("The total risk for possible location " + loc.toString() + " was: "
// + Double.toString(totalRisk));
return totalRisk;
} else {
return 0.0;
}
}
// Tells us if a point in a given cardinal direction at our maximum
// sight
// range is on the map
// This should only take in north,south,east,west
public static boolean checkCardinalOnMap(Direction dir) throws GameActionException {
MapLocation offsetLocation = rc.getLocation().add(dir, myDv);
rc.setIndicatorDot(offsetLocation, 255, 80, 80);
boolean onMap = rc.onTheMap(offsetLocation);
rc.setIndicatorString(0, dir.toString() + " point on map?: " + Boolean.toString(onMap));
return onMap;
}
// This function sets the value of a given direction bound, if it can at
// all
// this round.
// Call this after checkCardinalOnMap returns false.
public static void findExactOffset(Direction dir) throws GameActionException {
for (int i = myDv; i > 0; i--) {
MapLocation temp = rc.getLocation().add(dir, i);
if (rc.onTheMap(temp)) {
int bound = (dir == Direction.NORTH || dir == Direction.SOUTH) ? temp.y : temp.x;
setMapBound(dir, bound);
haveOffsets[returnCardinalIndex(dir)] = true;
// rc.setIndicatorString(0, dir.toString() + " bound value
// is :
// " + Integer.toString(offsets[returnCardinalIndex(dir)]));
numExploredDirections++;
break;
}
}
}
public static void broadcastMapBounds() throws GameActionException {
int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation());
rc.broadcastMessageSignal(messageConstants.SMBN, Messaging.adjustBound(northBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBE, Messaging.adjustBound(eastBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBS, Messaging.adjustBound(southBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBW, Messaging.adjustBound(westBound), distToNearestArchon);
haveBroadCastedMapBounds = true;
}
public static void tryExplore() throws GameActionException {
// If we have not found every bound
if (numExploredDirections != 4 && allBoundsSet != true) {
// If we don't already have a bound for this direction
if (!haveOffsets[returnCardinalIndex(currentExploreDirection)]) {
// If we go off the map in sight range for the given
// direction,
// we can get the offset
if (!checkCardinalOnMap(currentExploreDirection)) {
findExactOffset(currentExploreDirection);
currentExploreDirection = cardinals[numExploredDirections % 4];
// Otherwise go explore in that direction.
} else {
explore(currentExploreDirection);
}
}
} else if (!haveBroadCastedMapBounds) {
broadcastMapBounds();
} else {
explore(Movement.randomDirection());
}
}
}
static class ScoutMessaging {
public static void handleMessageQueue() throws GameActionException {
// SUPER
Messaging.handleMessageQueue();
// currentSignals[] is now set for this round. Overflow may cause
// problems.
if (currentSignals.length > 0) {
for (Signal signal : currentSignals) {
MapLocation loc = signal.getLocation();
int msg1 = signal.getMessage()[0];
int msg2 = signal.getMessage()[1];
switch (msg1) {
// Handle Scout messages that about map bounds
case messageConstants.SMBN:
case messageConstants.AMBN:
// Set map bounds
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.NORTH, msg2);
break;
case messageConstants.SMBE:
case messageConstants.AMBE:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.EAST, msg2);
break;
case messageConstants.SMBS:
case messageConstants.AMBS:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.SOUTH, msg2);
break;
case messageConstants.SMBW:
case messageConstants.AMBW:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.WEST, msg2);
break;
}
}
}
}
}
public static void reportDens() throws GameActionException {
int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation());
for (RobotInfo robot : nearbyEnemies) {
// TODO:
// Also check if the den exists in out list of knownDens
if (robot.type == RobotType.ZOMBIEDEN) {
// Check known dens so we don't add duplicates
boolean wasDuplicate = false;
for (MapLocation den : knownDens) {
if ((den.x == robot.location.x && den.y == robot.location.y)) {
wasDuplicate = true;
continue;
}
}
// If it was a duplicate, go to next robot and don't broadcast
if (wasDuplicate) {
continue;
} else {
// Otherwise we are dealing with a new den.
knownDens.add(new MapLocation(robot.location.x, robot.location.y));
}
rc.broadcastMessageSignal(messageConstants.DENX, Messaging.adjustBound(robot.location.x),
distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.DENY, Messaging.adjustBound(robot.location.y),
distToNearestArchon);
rc.setIndicatorString(2, "I transmitted denLocation this turn");
}
}
}
// Given a direction, try to move that way, but avoid taking damage or going
// far into enemy LOF.
// General Scout exploration driver.
// Don't let scout get stuck in concave areas, or near swarms of allies.
public static void pathDirectionAvoidEnemies(Direction dir) {
}
public static void run() {
while (true) {
try {
Debug.emptyIndicatorStrings();
Sensing.updateNearbyEnemies();
ScoutMessaging.handleMessageQueue();
// If we have found every bound
if (numExploredDirections == 4 || allBoundsSet == true) {
reportDens();
}
// Wander out into the wilderness
// find anything of interest
// report back to archons when we have enough data
// Give report, follow squad that gets deployed
// Constantly broadcast to squad attack info
// Signal troops to retreat when attack is done, or failed, or
// when reinforcements are needed,
// or when zombie spawn is upcoming
Exploration.tryExplore();
Clock.yield();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
| Glavin001/battlecode | src/team181_alpha/ScoutClass.java | 3,877 | // Set map bounds | line_comment | nl | package team181_alpha;
import java.util.ArrayList;
import java.util.Arrays;
import battlecode.common.Clock;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.Signal;
import battlecode.common.Team;
import team181_alpha.*;
public class ScoutClass extends RobotPlayer {
// Get the maximum number of tiles in one direction away in sensor radius
static int myDv = (int) Math.floor(Math.sqrt(myRobotType.sensorRadiusSquared));
static Direction[] cardinals = { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST };
static boolean[] haveOffsets = { false, false, false, false };
static Direction currentExploreDirection = Direction.NORTH;
static int numExploredDirections = 0;
static boolean haveBroadCastedMapBounds = false;
static ArrayList<MapLocation> knownDens = new ArrayList<MapLocation>();;
static int numKnownDens = 0;
// Enclosure for all of the exploration functions
static class Exploration {
// Dumb help function, please kill me and replace with a map
public static int returnCardinalIndex(Direction dir) throws GameActionException {
// Switch because no associative arrays, could map this instead, but
// that might cost more
switch (dir) {
case NORTH:
return 0;
case EAST:
return 1;
case SOUTH:
return 2;
case WEST:
return 3;
default:
GameActionException e = new GameActionException(null, "Not a valid cardinal direction.");
throw e;
}
}
// Given a direction, try to move that way, but avoid taking damage or
// going far into enemy LOF.
// General Scout exploration driver.
// Don't let scout get stuck in concave areas, or near swarms of allies.
public static void explore(Direction dirToMove) throws GameActionException {
if (rc.isCoreReady()) {
if (nearbyEnemies.length == 0) {
// There are no known enemy threats
if (rc.canMove(dirToMove)) {
rc.move(dirToMove);
} else if (rc.canMove(dirToMove.rotateLeft())) {
rc.move(dirToMove.rotateLeft());
} else if (rc.canMove(dirToMove.rotateRight())) {
rc.move(dirToMove.rotateRight());
}
} else {
// There are enemies within sight!
// Calculate least risking direction to move
MapLocation currLoc = rc.getLocation();
double leastRisk = Double.MAX_VALUE; // risks[0];
Direction leastRiskyDirection = Direction.NONE;
Direction[] allDirs = Direction.values();
MapLocation goalLoc = currLoc.add(dirToMove);
MapLocation leastRiskyLoc = goalLoc;
double[] risks = new double[allDirs.length];
for (int i = 0; i < allDirs.length; i++) {
// Check if can move in this direction
Direction currDir = allDirs[i];
if (rc.canMove(currDir)) {
// Can move in this direction
// Check attack risk value
MapLocation nextLoc = currLoc.add(currDir);
double risk = attackRisk(nextLoc);
risks[i] = risk;
// System.out.println("At location" +
// currLoc.toString() + " risk in direction " +
// currDir.toString() + " is: " +
// Double.toString(risk));
// Is this better?
// Bias towards moving the same direction, dirToMove
if (currDir.equals(dirToMove) && risk <= leastRisk) {
// At least as good
leastRisk = risk;
leastRiskyDirection = dirToMove;
leastRiskyLoc = nextLoc;
} else if (risk < leastRisk) {
// Better
leastRisk = risk;
leastRiskyDirection = allDirs[i];
leastRiskyLoc = nextLoc;
} else if (risk == leastRisk && (goalLoc.distanceSquaredTo(nextLoc) < goalLoc
.distanceSquaredTo(leastRiskyLoc))) {
// Equally as good but closer to the original
// dirToMove direction
leastRisk = risk;
leastRiskyDirection = allDirs[i];
leastRiskyLoc = nextLoc;
}
}
}
if (!leastRiskyDirection.equals(Direction.NONE)) {
// rc.setIndicatorString(2, "Retreating towards: " +
// leastRiskyDirection.toString());
rc.setIndicatorString(2, "Risk this turn is: " + Arrays.toString(risks));
rc.move(leastRiskyDirection);
}
}
}
}
/*
* Calculation the Attack risk value of moving to this location given
* the direction.
*
* Attack risk is currently the count of the number of enemies which
* will be within attack range of this location Ideal attack risk is 0
* (no risk of attack).
*
*/
public static double attackRisk(MapLocation loc) {
if (nearbyEnemies.length > 0) {
double totalRisk = 0.0;
for (RobotInfo r : nearbyEnemies) {
MapLocation enemyLoc = r.location;
RobotType enemyType = r.type;
int distAway = loc.distanceSquaredTo(enemyLoc);
int offsetBlocks = 2;
int offsetSquared = offsetBlocks * offsetBlocks;
int safeDist = (enemyType.attackRadiusSquared+offsetSquared);
if (enemyType.equals(RobotType.TURRET)) {
safeDist = RobotType.TURRET.sensorRadiusSquared + offsetSquared;
}
if (distAway <= safeDist) {
// If enemy has 0 attack power then risk = 0
// If Core delay is 0 then risk = numerator, and will be
// divided by each turn/core delay
double risk = ((safeDist - distAway) * r.attackPower)
/ (r.weaponDelay + 1.0);
totalRisk += risk;
}
}
// rc.setIndicatorString(2, "Risk this turn is: " +
// Double.toString(totalRisk));
// System.out.println("The total risk for possible location " + loc.toString() + " was: "
// + Double.toString(totalRisk));
return totalRisk;
} else {
return 0.0;
}
}
// Tells us if a point in a given cardinal direction at our maximum
// sight
// range is on the map
// This should only take in north,south,east,west
public static boolean checkCardinalOnMap(Direction dir) throws GameActionException {
MapLocation offsetLocation = rc.getLocation().add(dir, myDv);
rc.setIndicatorDot(offsetLocation, 255, 80, 80);
boolean onMap = rc.onTheMap(offsetLocation);
rc.setIndicatorString(0, dir.toString() + " point on map?: " + Boolean.toString(onMap));
return onMap;
}
// This function sets the value of a given direction bound, if it can at
// all
// this round.
// Call this after checkCardinalOnMap returns false.
public static void findExactOffset(Direction dir) throws GameActionException {
for (int i = myDv; i > 0; i--) {
MapLocation temp = rc.getLocation().add(dir, i);
if (rc.onTheMap(temp)) {
int bound = (dir == Direction.NORTH || dir == Direction.SOUTH) ? temp.y : temp.x;
setMapBound(dir, bound);
haveOffsets[returnCardinalIndex(dir)] = true;
// rc.setIndicatorString(0, dir.toString() + " bound value
// is :
// " + Integer.toString(offsets[returnCardinalIndex(dir)]));
numExploredDirections++;
break;
}
}
}
public static void broadcastMapBounds() throws GameActionException {
int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation());
rc.broadcastMessageSignal(messageConstants.SMBN, Messaging.adjustBound(northBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBE, Messaging.adjustBound(eastBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBS, Messaging.adjustBound(southBound), distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.SMBW, Messaging.adjustBound(westBound), distToNearestArchon);
haveBroadCastedMapBounds = true;
}
public static void tryExplore() throws GameActionException {
// If we have not found every bound
if (numExploredDirections != 4 && allBoundsSet != true) {
// If we don't already have a bound for this direction
if (!haveOffsets[returnCardinalIndex(currentExploreDirection)]) {
// If we go off the map in sight range for the given
// direction,
// we can get the offset
if (!checkCardinalOnMap(currentExploreDirection)) {
findExactOffset(currentExploreDirection);
currentExploreDirection = cardinals[numExploredDirections % 4];
// Otherwise go explore in that direction.
} else {
explore(currentExploreDirection);
}
}
} else if (!haveBroadCastedMapBounds) {
broadcastMapBounds();
} else {
explore(Movement.randomDirection());
}
}
}
static class ScoutMessaging {
public static void handleMessageQueue() throws GameActionException {
// SUPER
Messaging.handleMessageQueue();
// currentSignals[] is now set for this round. Overflow may cause
// problems.
if (currentSignals.length > 0) {
for (Signal signal : currentSignals) {
MapLocation loc = signal.getLocation();
int msg1 = signal.getMessage()[0];
int msg2 = signal.getMessage()[1];
switch (msg1) {
// Handle Scout messages that about map bounds
case messageConstants.SMBN:
case messageConstants.AMBN:
// Set map<SUF>
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.NORTH, msg2);
break;
case messageConstants.SMBE:
case messageConstants.AMBE:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.EAST, msg2);
break;
case messageConstants.SMBS:
case messageConstants.AMBS:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.SOUTH, msg2);
break;
case messageConstants.SMBW:
case messageConstants.AMBW:
msg2 = Messaging.adjustBound(msg2);
setMapBound(Direction.WEST, msg2);
break;
}
}
}
}
}
public static void reportDens() throws GameActionException {
int distToNearestArchon = nearestArchon.distanceSquaredTo(rc.getLocation());
for (RobotInfo robot : nearbyEnemies) {
// TODO:
// Also check if the den exists in out list of knownDens
if (robot.type == RobotType.ZOMBIEDEN) {
// Check known dens so we don't add duplicates
boolean wasDuplicate = false;
for (MapLocation den : knownDens) {
if ((den.x == robot.location.x && den.y == robot.location.y)) {
wasDuplicate = true;
continue;
}
}
// If it was a duplicate, go to next robot and don't broadcast
if (wasDuplicate) {
continue;
} else {
// Otherwise we are dealing with a new den.
knownDens.add(new MapLocation(robot.location.x, robot.location.y));
}
rc.broadcastMessageSignal(messageConstants.DENX, Messaging.adjustBound(robot.location.x),
distToNearestArchon);
rc.broadcastMessageSignal(messageConstants.DENY, Messaging.adjustBound(robot.location.y),
distToNearestArchon);
rc.setIndicatorString(2, "I transmitted denLocation this turn");
}
}
}
// Given a direction, try to move that way, but avoid taking damage or going
// far into enemy LOF.
// General Scout exploration driver.
// Don't let scout get stuck in concave areas, or near swarms of allies.
public static void pathDirectionAvoidEnemies(Direction dir) {
}
public static void run() {
while (true) {
try {
Debug.emptyIndicatorStrings();
Sensing.updateNearbyEnemies();
ScoutMessaging.handleMessageQueue();
// If we have found every bound
if (numExploredDirections == 4 || allBoundsSet == true) {
reportDens();
}
// Wander out into the wilderness
// find anything of interest
// report back to archons when we have enough data
// Give report, follow squad that gets deployed
// Constantly broadcast to squad attack info
// Signal troops to retreat when attack is done, or failed, or
// when reinforcements are needed,
// or when zombie spawn is upcoming
Exploration.tryExplore();
Clock.yield();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
|
106816_12 | import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ImageIcon image = new ImageIcon("/Users/estinesmith/eclipse-workspace/JLabel/technology-monitor-alpha-coders-binary-wallpaper-preview.jpg");
JLabel label =new JLabel();
label.setText("Coder?");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setForeground(Color.blue);//Changing label text color
label.setFont(new Font ("MV Boli",Font.PLAIN,20));//set font of text
label.setIconTextGap(200);//Gap between image and text
label.setBackground(Color.black);
label.setVerticalAlignment(JLabel.CENTER);//set vertical position of icon + text within label as groter of kleiner maak
label.setHorizontalAlignment(JLabel.CENTER);//set horizontical position of icon + text within label as groter of keliner maak
//label.setBounds(100,100,250,250);//set x,y positioon within fram as well as dimension (samet frame.setLayout()
JFrame frame = new JFrame();
frame.setTitle("Main");//setting titles
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit of application
frame.setResizable(false);//cant make bigger or smaller
frame.setSize(500,500);//setting size of box
frame.setVisible(true);//make frame visible
//frame.setLayout(null);
//Adding label to frame
frame.add(label); // Moet bo pack wees
frame.pack();//laat alles fit in frane
}
}
| GlenBowler/Java-refresher | JLabel/src/Main.java | 530 | // Moet bo pack wees | line_comment | nl | import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ImageIcon image = new ImageIcon("/Users/estinesmith/eclipse-workspace/JLabel/technology-monitor-alpha-coders-binary-wallpaper-preview.jpg");
JLabel label =new JLabel();
label.setText("Coder?");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setForeground(Color.blue);//Changing label text color
label.setFont(new Font ("MV Boli",Font.PLAIN,20));//set font of text
label.setIconTextGap(200);//Gap between image and text
label.setBackground(Color.black);
label.setVerticalAlignment(JLabel.CENTER);//set vertical position of icon + text within label as groter of kleiner maak
label.setHorizontalAlignment(JLabel.CENTER);//set horizontical position of icon + text within label as groter of keliner maak
//label.setBounds(100,100,250,250);//set x,y positioon within fram as well as dimension (samet frame.setLayout()
JFrame frame = new JFrame();
frame.setTitle("Main");//setting titles
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit of application
frame.setResizable(false);//cant make bigger or smaller
frame.setSize(500,500);//setting size of box
frame.setVisible(true);//make frame visible
//frame.setLayout(null);
//Adding label to frame
frame.add(label); // Moet bo<SUF>
frame.pack();//laat alles fit in frane
}
}
|
92277_5 | package be.vdab.services;
import java.util.List;
import be.vdab.entities.Employee;
/**
* Service voor het ophalen van Werknemers uit de database
* @author cursist
*
*/
public interface EmployeeService {
/**
* Het wegschrijven van een werknemer naar de database
* @param employee
*/
public void create(Employee employee);
/**
* Haalt alle werknemers op uit de database
* @return een lijst met werknemers
*/
public List<Employee> findAll();
/**
* Zoekt een werknemer op basis van een id
* @param id van de werknemer
* @return een werknemer
*/
public Employee find(Long id);
/**
* Een werknemer verwijderen uit de database
* @param employee
*/
public void remove(Employee employee);
/**
* een werknemer aanpassen in de database
* @param employee
*/
public void edit(Employee employee);
/**
* Het ophalen van alle werknemers met een bepaald deel van de naam
* @param waarde die in de naam moet voorkomen
* @return een lijst van werknemers
*/
public List<Employee> findByNaamContaining(String waarde);
}
| GlennLefevere/JSFBeanValidation | src/main/java/be/vdab/services/EmployeeService.java | 347 | /**
* een werknemer aanpassen in de database
* @param employee
*/ | block_comment | nl | package be.vdab.services;
import java.util.List;
import be.vdab.entities.Employee;
/**
* Service voor het ophalen van Werknemers uit de database
* @author cursist
*
*/
public interface EmployeeService {
/**
* Het wegschrijven van een werknemer naar de database
* @param employee
*/
public void create(Employee employee);
/**
* Haalt alle werknemers op uit de database
* @return een lijst met werknemers
*/
public List<Employee> findAll();
/**
* Zoekt een werknemer op basis van een id
* @param id van de werknemer
* @return een werknemer
*/
public Employee find(Long id);
/**
* Een werknemer verwijderen uit de database
* @param employee
*/
public void remove(Employee employee);
/**
* een werknemer aanpassen<SUF>*/
public void edit(Employee employee);
/**
* Het ophalen van alle werknemers met een bepaald deel van de naam
* @param waarde die in de naam moet voorkomen
* @return een lijst van werknemers
*/
public List<Employee> findByNaamContaining(String waarde);
}
|
141674_10 | /***************************************************************************
* (C) Copyright 2003-2011 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
List<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan city gardens
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start")
)
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
})));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| Gnefil/Stendhal-Game | src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java | 1,817 | // Annie, Kalavan city gardens | line_comment | nl | /***************************************************************************
* (C) Copyright 2003-2011 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
List<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan<SUF>
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start")
)
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
})));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
|
12234_0 | package be.kdg.healthtips.notifications;
import android.content.Context;
import be.kdg.healthtips.activity.TipDetailActivity;
public class SpecificNotificationThrower {
public static void throwYouHaveEatenBeforeSleeping(Context context) {
//wanneer je ziet dat de gebruiker heeft gegeten voor het slapen gaan
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_SLEEP, "Eten voor het slapengaan", "", TipDetailActivity.class, "Eten voor het slapengaan", "Eten vlak voor je gaat slapen is niet goed en zorgt ervoor dat je minder snel in slaap valt. Sommige snacks zijn wel ok; melk, kersen, brood of een banaan. Als je echt honger hebt voor het slapen gaan kan je best een van deze snacks eten");
}
public static void throwYouHaveEatenBeforeSporting(Context context) {
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_RUNNING, "Eten voor het sporten", "", TipDetailActivity.class, "Eten voor het sporten", "Voeding gegeten voor een inspanning is alleen van nut wanneer de gegeten voedingsmiddelen ook effectief verteerd worden en opgenomen worden via het maagdarmstelsel. Dit wil zeggen dat er tijd nodig is om het gegeten voedsel daadwerkelijk als brandstof voor de inspanning te gebruiken. De tijd die hiervoor nodig is, is afhankelijk van de soort voeding. Voedingsmiddelen met veel vet, veel eiwit en veel voedingsvezel verteren langzamer en kunnen, wanneer ze nog niet volledig verteerd zijn, maaglast bezorgen tijdens het sporten. Grote hoeveelheden hebben ook langer nodig om te verteren dan kleine porties. En over het algemeen wordt voeding beter verdragen tijdens inspanningen aan lage intensiteit of tijdens sporten waarbij het lichaam wordt “gedragen” ( wielrennen versus lopen). Een algemene richtlijn is om de laatste maaltijd 3 tot 4 uur voor het sporten te plannen terwijl een lichte snack nog kan tot nog 1-2 uur voor de inspanning. Maar het is aan de sporter om hiermee te experimenteren wat het beste scenario is.\n" +
"\n" +
"Een goede maaltijd voor de inspanning en een goede bevoorrading tijdens het sporten (meer dan 1 uur) gaan hand in hand.");
}
public static void throwYouSportBeforeSleeping(Context context) {
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_SLEEP, "Sporten voor het slapengaan", "", TipDetailActivity.class, "Sporten voor het slapengaan", "Wees ook voorzichtig met sporten vlak voor het slapen gaan. Sommige niet-slapers proberen zich af te sloven vlak voordat ze naar bed gaan, in de hoop dat de slaap op die manier wel gaat komen. Dat is echter een misrekening, want te zware lichaamsinspanningen zullen eerder een negatief dan een positief effect hebben.\n" +
"\n" +
"Een wandeling vlak voor slaaptijd is te verkiezen boven enkele kilometers joggen aan een strak tempo. Het komt er eigenlijk op aan om niet alleen het verstand op nul te zetten, maar ook om het lichaam aan het verstand te brengen dat er op een lager pitje moet worden gedraaid. Wie met deze en nog een aantal andere factoren rekening houdt, zal al veel minder moeite hebben om de slaap te vatten. ");
}
public static void throwBadFoodHabit(Context context) {
//bv. gebruiker eet elke week 1x fastfood
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_FOOD, "Eetgewoonte", "Probeer deze af te leren", TipDetailActivity.class, "Slechte eetgewoontes", "Je hebt de gewoonte om elke zondag fastfood te eten. Probeer dit af te leren, dit is een aanslag op je gezondheid.");
}
}
| GoGoris/TipFit | app/src/main/java/be/kdg/healthtips/notifications/SpecificNotificationThrower.java | 1,033 | //wanneer je ziet dat de gebruiker heeft gegeten voor het slapen gaan | line_comment | nl | package be.kdg.healthtips.notifications;
import android.content.Context;
import be.kdg.healthtips.activity.TipDetailActivity;
public class SpecificNotificationThrower {
public static void throwYouHaveEatenBeforeSleeping(Context context) {
//wanneer je<SUF>
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_SLEEP, "Eten voor het slapengaan", "", TipDetailActivity.class, "Eten voor het slapengaan", "Eten vlak voor je gaat slapen is niet goed en zorgt ervoor dat je minder snel in slaap valt. Sommige snacks zijn wel ok; melk, kersen, brood of een banaan. Als je echt honger hebt voor het slapen gaan kan je best een van deze snacks eten");
}
public static void throwYouHaveEatenBeforeSporting(Context context) {
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_RUNNING, "Eten voor het sporten", "", TipDetailActivity.class, "Eten voor het sporten", "Voeding gegeten voor een inspanning is alleen van nut wanneer de gegeten voedingsmiddelen ook effectief verteerd worden en opgenomen worden via het maagdarmstelsel. Dit wil zeggen dat er tijd nodig is om het gegeten voedsel daadwerkelijk als brandstof voor de inspanning te gebruiken. De tijd die hiervoor nodig is, is afhankelijk van de soort voeding. Voedingsmiddelen met veel vet, veel eiwit en veel voedingsvezel verteren langzamer en kunnen, wanneer ze nog niet volledig verteerd zijn, maaglast bezorgen tijdens het sporten. Grote hoeveelheden hebben ook langer nodig om te verteren dan kleine porties. En over het algemeen wordt voeding beter verdragen tijdens inspanningen aan lage intensiteit of tijdens sporten waarbij het lichaam wordt “gedragen” ( wielrennen versus lopen). Een algemene richtlijn is om de laatste maaltijd 3 tot 4 uur voor het sporten te plannen terwijl een lichte snack nog kan tot nog 1-2 uur voor de inspanning. Maar het is aan de sporter om hiermee te experimenteren wat het beste scenario is.\n" +
"\n" +
"Een goede maaltijd voor de inspanning en een goede bevoorrading tijdens het sporten (meer dan 1 uur) gaan hand in hand.");
}
public static void throwYouSportBeforeSleeping(Context context) {
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_SLEEP, "Sporten voor het slapengaan", "", TipDetailActivity.class, "Sporten voor het slapengaan", "Wees ook voorzichtig met sporten vlak voor het slapen gaan. Sommige niet-slapers proberen zich af te sloven vlak voordat ze naar bed gaan, in de hoop dat de slaap op die manier wel gaat komen. Dat is echter een misrekening, want te zware lichaamsinspanningen zullen eerder een negatief dan een positief effect hebben.\n" +
"\n" +
"Een wandeling vlak voor slaaptijd is te verkiezen boven enkele kilometers joggen aan een strak tempo. Het komt er eigenlijk op aan om niet alleen het verstand op nul te zetten, maar ook om het lichaam aan het verstand te brengen dat er op een lager pitje moet worden gedraaid. Wie met deze en nog een aantal andere factoren rekening houdt, zal al veel minder moeite hebben om de slaap te vatten. ");
}
public static void throwBadFoodHabit(Context context) {
//bv. gebruiker eet elke week 1x fastfood
NotificationThrower.throwSpecificTip(context, NotificationThrower.IconType.T_FOOD, "Eetgewoonte", "Probeer deze af te leren", TipDetailActivity.class, "Slechte eetgewoontes", "Je hebt de gewoonte om elke zondag fastfood te eten. Probeer dit af te leren, dit is een aanslag op je gezondheid.");
}
}
|
136404_2 | /*
* The MIT License
*
* Copyright 2014 Goblom.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package block;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Regeneration v1.0
*
* A simple block regeneration class that allows a person to request a location
* to be regenerated after a certain amount of time.
*
* @author Goblom
*/
public class Regeneration {
private final Plugin plugin;
private static final Map<Location, BlockState> toRegen = Maps.newHashMap();
private static final List<BlockRegen> tasks = Lists.newArrayList();
/**
* @see Regeneration
* @param plugin
*/
public Regeneration(Plugin plugin) {
this.plugin = plugin;
}
/**
* Checks to see if the task list is not empty and need to run tasks
*
* @return true if there are tasks that need to run
*/
public boolean hasTasks() {
return !tasks.isEmpty();
}
/**
* Forces all tasks to run
*/
public void forceTasks() {
for (BlockRegen task : tasks) {
//i overwrote the cancel task
task.cancel();
}
}
/**
* Checks if the location you want to regen already has a regen task running
* on it
*
* @param location
* @return true if that location already has a {@link BlockRegen} task
*/
public boolean alreadyScheduled(Location location) {
return toRegen.containsKey(location);
}
/**
* Request the location for a {@link BlockRegen} task
*
* @param block the block to regen back to
* @param ticksLater ticks later for regen task to run
* @return true if task was started, false if a task is {@link Regeneration#alreadyScheduled(org.bukkit.Location)
* }
*/
public boolean request(Block block, long ticksLater) {
return request(block.getState(), ticksLater);
}
/**
* Request the location for a {@link BlockRegen} task
*
* @param state the state to regen back to
* @param ticksLater ticks later for regen task to run
* @return true if task was started, false if a task is {@link Regeneration#alreadyScheduled(org.bukkit.Location)
* }
*/
public boolean request(BlockState state, long ticksLater) {
if (alreadyScheduled(state.getLocation())) {
return false;
}
this.toRegen.put(state.getLocation(), state);
BlockRegen regenTask = new BlockRegen(state.getLocation(), state);
regenTask.runTaskLater(plugin, ticksLater);
return tasks.add(regenTask);
}
/**
* Does the event task for you, just pass the {@link BlockBreakEvent} to
* this
*
* @param event
* @param ticksLater
*/
public void onBlockBreak(BlockBreakEvent event, long ticksLater) {
request(event.getBlock(), ticksLater);
}
/**
* Does the event task for you, just pass the {@link BlockPlaceEvent} to
* this
*
* @param event
* @param ticksLater
*/
public void onBlockPlace(BlockPlaceEvent event, long ticksLater) {
request(event.getBlockReplacedState(), ticksLater);
}
/**
* BlockRegen
*
* The Regeneration task that is scheduled whenever a regen is requested
*/
public class BlockRegen extends BukkitRunnable {
private final BlockState state;
private final Location location;
private boolean hasRun = false;
protected BlockRegen(Location location, BlockState state) {
this.state = state;
this.location = location;
}
public Location getLocation() {
return location;
}
public BlockState getState() {
return state;
}
@Override
public void cancel() {
if (!hasRun) {
run();
}
super.cancel();
}
@Override
public void run() {
getLocation().getBlock().setType(getState().getType());
getLocation().getBlock().setData(getState().getBlock().getData());
finish();
}
public void finish() {
this.hasRun = true;
if (toRegen.containsKey(getLocation())) {
toRegen.remove(getLocation());
}
if (tasks.contains(this)) {
tasks.remove(this);
}
}
}
}
| Goblom/Bukkit-Libraries | src/main/java/block/Regeneration.java | 1,630 | /**
* @see Regeneration
* @param plugin
*/ | block_comment | nl | /*
* The MIT License
*
* Copyright 2014 Goblom.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package block;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Regeneration v1.0
*
* A simple block regeneration class that allows a person to request a location
* to be regenerated after a certain amount of time.
*
* @author Goblom
*/
public class Regeneration {
private final Plugin plugin;
private static final Map<Location, BlockState> toRegen = Maps.newHashMap();
private static final List<BlockRegen> tasks = Lists.newArrayList();
/**
* @see Regeneration
<SUF>*/
public Regeneration(Plugin plugin) {
this.plugin = plugin;
}
/**
* Checks to see if the task list is not empty and need to run tasks
*
* @return true if there are tasks that need to run
*/
public boolean hasTasks() {
return !tasks.isEmpty();
}
/**
* Forces all tasks to run
*/
public void forceTasks() {
for (BlockRegen task : tasks) {
//i overwrote the cancel task
task.cancel();
}
}
/**
* Checks if the location you want to regen already has a regen task running
* on it
*
* @param location
* @return true if that location already has a {@link BlockRegen} task
*/
public boolean alreadyScheduled(Location location) {
return toRegen.containsKey(location);
}
/**
* Request the location for a {@link BlockRegen} task
*
* @param block the block to regen back to
* @param ticksLater ticks later for regen task to run
* @return true if task was started, false if a task is {@link Regeneration#alreadyScheduled(org.bukkit.Location)
* }
*/
public boolean request(Block block, long ticksLater) {
return request(block.getState(), ticksLater);
}
/**
* Request the location for a {@link BlockRegen} task
*
* @param state the state to regen back to
* @param ticksLater ticks later for regen task to run
* @return true if task was started, false if a task is {@link Regeneration#alreadyScheduled(org.bukkit.Location)
* }
*/
public boolean request(BlockState state, long ticksLater) {
if (alreadyScheduled(state.getLocation())) {
return false;
}
this.toRegen.put(state.getLocation(), state);
BlockRegen regenTask = new BlockRegen(state.getLocation(), state);
regenTask.runTaskLater(plugin, ticksLater);
return tasks.add(regenTask);
}
/**
* Does the event task for you, just pass the {@link BlockBreakEvent} to
* this
*
* @param event
* @param ticksLater
*/
public void onBlockBreak(BlockBreakEvent event, long ticksLater) {
request(event.getBlock(), ticksLater);
}
/**
* Does the event task for you, just pass the {@link BlockPlaceEvent} to
* this
*
* @param event
* @param ticksLater
*/
public void onBlockPlace(BlockPlaceEvent event, long ticksLater) {
request(event.getBlockReplacedState(), ticksLater);
}
/**
* BlockRegen
*
* The Regeneration task that is scheduled whenever a regen is requested
*/
public class BlockRegen extends BukkitRunnable {
private final BlockState state;
private final Location location;
private boolean hasRun = false;
protected BlockRegen(Location location, BlockState state) {
this.state = state;
this.location = location;
}
public Location getLocation() {
return location;
}
public BlockState getState() {
return state;
}
@Override
public void cancel() {
if (!hasRun) {
run();
}
super.cancel();
}
@Override
public void run() {
getLocation().getBlock().setType(getState().getType());
getLocation().getBlock().setData(getState().getBlock().getData());
finish();
}
public void finish() {
this.hasRun = true;
if (toRegen.containsKey(getLocation())) {
toRegen.remove(getLocation());
}
if (tasks.contains(this)) {
tasks.remove(this);
}
}
}
}
|
49330_4 | package fact.it.plantservice;
import com.fasterxml.jackson.databind.ObjectMapper;
import fact.it.plantservice.model.Plant;
import fact.it.plantservice.repository.PlantRepository;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@SpringBootTest
@AutoConfigureMockMvc
public class PlantControllerIntegrationTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private PlantRepository plantRepository;
// Test data (best no postconstruct in controller)
// Plant information from: https://www.buitenlevengevoel.nl/meest-populaire-tuinplanten-van-nederland/
private Plant plantCenter1Plant1 = new Plant(1, "P0100", "Kerstroos", "De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.");
private Plant plantCenter1Plant2 = new Plant(1, "P0101", "Hortensia", "Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.");
private Plant plantCenter2Plant1 = new Plant(2, "P0102", "Buxus", "De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.");
private Plant plantCenter3Plant2 = new Plant(3, "P0103", "Klimop", "Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.");
private Plant plantCenter3Plant3 = new Plant(3, "P0104", "Hartlelie", "Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.");
// private Plant plantCenter1Plant3 = new Plant(1, "Lavendel", "De lavendel is vooral populair door de mooie diep paarse kleur én de heerlijke geur die deze plant verspreidt. Lavendel is een kleine vaste tuinplant voor in de tuin. De plant wordt namelijk niet hoger dan één meter en doet klein aan door de dunne stengels waar de plant uit bestaat.");
// private Plant plantCenter2Plant2 = new Plant(2, "Viooltje", "Niet iedere populaire plant is een grote plant. Het kleine viooltje blijft een favoriet voor in de Nederlandse tuin. Dit omdat wij toch wel fan zijn van dit kleine, fleurige plantje. Door de vele kleuruitvoeringen past er in iedere tuin wel een viooltje en daarom kon hij niet ontbreken in deze lijst van de meest populaire tuinplanten van Nederland.");
// private Plant plantCenter2Plant3 = new Plant(2, "Geranium", "Pelargonium (pelargos) betekent ooievaarsbek en het is dan ook om die reden dat de geranium ook wel ooievaarsbek genoemd wordt. Geraniums hebben lange tijd een wat stoffig imago gehad door het bekende gezegde ‘achter de geraniums zitten'. De plant wordt veelal geassocieerd met oude mensen die de hele dag maar binnen zitten.");
// private Plant plantCenter2Plant4 = new Plant(2, "Spaanse margriet", "De Spaanse margriet is niet, zoals je zou verwachten, afkomstig uit Spanje. Deze populaire plant komt uit het verre Zuid-Afrika en is een éénjarige tuinplant.");
// private Plant plantCenter3Plant1 = new Plant(3, "Vlinderstruik", "Dat de vlinderstruik bij de meest populaire tuinplanten van Nederland zit verbaasd ons wederom niets. Deze plant is niet alleen mooi om te zien, maar trekt ook nog eens de mooiste vlinders aan. Zo zullen onder andere het koolwitje, de citroenvlinder en de atalanta de verleiding van deze plant niet kunnen weerstaan.");
@BeforeEach
public void beforeAllTests() {
// Make sure EVERYTHING is deleted from the db
plantRepository.deleteAll();
// Save all the plants
plantRepository.save(plantCenter1Plant1);
plantRepository.save(plantCenter1Plant2);
plantRepository.save(plantCenter2Plant1);
plantRepository.save(plantCenter3Plant2);
plantRepository.save(plantCenter3Plant3);
// plantRepository.save(plantCenter1Plant3);
// plantRepository.save(plantCenter2Plant2);
// plantRepository.save(plantCenter2Plant3);
// plantRepository.save(plantCenter2Plant4);
// plantRepository.save(plantCenter3Plant1);
}
@AfterEach
public void afterAllTests() {
// Watch out with deleteAll() methods when you have other data in the test database!!
plantRepository.deleteAll();
}
private ObjectMapper mapper = new ObjectMapper();
@Test
public void givenPlant_whenGetPlantByName_ThenReturnJsonPlant() throws Exception {
mockMvc.perform(get("/plants/name/{name}", "Kerstroos"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(1)))
.andExpect(jsonPath("$.plantNumber", is("P0100")))
.andExpect(jsonPath("$.name", is("Kerstroos")))
.andExpect(jsonPath("$.description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")));
}
@Test
public void givenPlant_whenGetPlantByPlantNumber_ThenReturnJsonPlant() throws Exception {
mockMvc.perform(get("/plants/{plantNumber}", "P0100"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(1)))
.andExpect(jsonPath("$.plantNumber", is("P0100")))
.andExpect(jsonPath("$.name", is("Kerstroos")))
.andExpect(jsonPath("$.description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")));
}
@Test
public void givenPlant_whenGetPlantByContainingDescription_ThenReturnJsonPlants() throws Exception {
// Only one plant found
mockMvc.perform(get("/plants/description/{description}", "Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen."))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].gardenCenterId", is(1)))
.andExpect(jsonPath("$[0].plantNumber", is("P0101")))
.andExpect(jsonPath("$[0].name", is("Hortensia")))
.andExpect(jsonPath("$[0].description", is("Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.")));
// Two plants founf
mockMvc.perform(get("/plants/description/{description}", "groen"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].gardenCenterId", is(3)))
.andExpect(jsonPath("$[0].plantNumber", is("P0103")))
.andExpect(jsonPath("$[0].name", is("Klimop")))
.andExpect(jsonPath("$[0].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(3)))
.andExpect(jsonPath("$[1].plantNumber", is("P0104")))
.andExpect(jsonPath("$[1].name", is("Hartlelie")))
.andExpect(jsonPath("$[1].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void givenPlant_whenGetPlantByGardenCenterId_ThenReturnJsonPlants() throws Exception {
mockMvc.perform(get("/plants/gardencenterid/{gardenCenterId}", 3))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].gardenCenterId", is(3)))
.andExpect(jsonPath("$[0].plantNumber", is("P0103")))
.andExpect(jsonPath("$[0].name", is("Klimop")))
.andExpect(jsonPath("$[0].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(3)))
.andExpect(jsonPath("$[1].plantNumber", is("P0104")))
.andExpect(jsonPath("$[1].name", is("Hartlelie")))
.andExpect(jsonPath("$[1].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void givenPlant_whenPlants_ThenReturnAllJsonPlants() throws Exception {
mockMvc.perform(get("/plants"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(5)))
.andExpect(jsonPath("$[0].gardenCenterId", is(1)))
.andExpect(jsonPath("$[0].plantNumber", is("P0100")))
.andExpect(jsonPath("$[0].name", is("Kerstroos")))
.andExpect(jsonPath("$[0].description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(1)))
.andExpect(jsonPath("$[1].plantNumber", is("P0101")))
.andExpect(jsonPath("$[1].name", is("Hortensia")))
.andExpect(jsonPath("$[1].description", is("Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.")))
.andExpect(jsonPath("$[2].gardenCenterId", is(2)))
.andExpect(jsonPath("$[2].plantNumber", is("P0102")))
.andExpect(jsonPath("$[2].name", is("Buxus")))
.andExpect(jsonPath("$[2].description", is("De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.")))
.andExpect(jsonPath("$[3].gardenCenterId", is(3)))
.andExpect(jsonPath("$[3].plantNumber", is("P0103")))
.andExpect(jsonPath("$[3].name", is("Klimop")))
.andExpect(jsonPath("$[3].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[4].gardenCenterId", is(3)))
.andExpect(jsonPath("$[4].plantNumber", is("P0104")))
.andExpect(jsonPath("$[4].name", is("Hartlelie")))
.andExpect(jsonPath("$[4].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void whenPostPlant_thenReturnJsonPlant() throws Exception {
Plant plantCenter2Plant5 = new Plant(2, "P0105", "Ice Dance", "De Carex morrowii 'Ice Dance' is een laagblijvend siergras dat in de breedte groeit met schuin opgaande bladeren. De 'Ice Dance' wordt max. 40cm hoog worden.");
mockMvc.perform(post("/plants")
.content(mapper.writeValueAsString(plantCenter2Plant5))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(2)))
.andExpect(jsonPath("$.plantNumber", is("P0105")))
.andExpect(jsonPath("$.name", is("Ice Dance")))
.andExpect(jsonPath("$.description", is("De Carex morrowii 'Ice Dance' is een laagblijvend siergras dat in de breedte groeit met schuin opgaande bladeren. De 'Ice Dance' wordt max. 40cm hoog worden.")));
}
@Test
public void givenPlant_whenPutPlant_thenReturnJsonPlant() throws Exception {
Plant updatedPlant = new Plant(2, "P0102", "BuxusUPDATE", "De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.");
mockMvc.perform(put("/plants")
.content(mapper.writeValueAsString(updatedPlant))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(2)))
.andExpect(jsonPath("$.plantNumber", is("P0102")))
.andExpect(jsonPath("$.name", is("BuxusUPDATE")))
.andExpect(jsonPath("$.description", is("De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.")));
}
@Test
public void givenPlant_whenDeletePlant_thenStatusOk() throws Exception {
// Plant is IN db
mockMvc.perform(delete("/plants/{plantNumber}", "P0100")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void givenNoRPlant_whenDeletePlant_thenStatusNotFound() throws Exception {
// Plant is NOT in db
mockMvc.perform(delete("/plants/{plantNumber}", "K9999")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
| Goetsie/plant-service-APT | src/test/java/fact/it/plantservice/PlantControllerIntegrationTests.java | 5,303 | // private Plant plantCenter2Plant3 = new Plant(2, "Geranium", "Pelargonium (pelargos) betekent ooievaarsbek en het is dan ook om die reden dat de geranium ook wel ooievaarsbek genoemd wordt. Geraniums hebben lange tijd een wat stoffig imago gehad door het bekende gezegde ‘achter de geraniums zitten'. De plant wordt veelal geassocieerd met oude mensen die de hele dag maar binnen zitten."); | line_comment | nl | package fact.it.plantservice;
import com.fasterxml.jackson.databind.ObjectMapper;
import fact.it.plantservice.model.Plant;
import fact.it.plantservice.repository.PlantRepository;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@SpringBootTest
@AutoConfigureMockMvc
public class PlantControllerIntegrationTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private PlantRepository plantRepository;
// Test data (best no postconstruct in controller)
// Plant information from: https://www.buitenlevengevoel.nl/meest-populaire-tuinplanten-van-nederland/
private Plant plantCenter1Plant1 = new Plant(1, "P0100", "Kerstroos", "De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.");
private Plant plantCenter1Plant2 = new Plant(1, "P0101", "Hortensia", "Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.");
private Plant plantCenter2Plant1 = new Plant(2, "P0102", "Buxus", "De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.");
private Plant plantCenter3Plant2 = new Plant(3, "P0103", "Klimop", "Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.");
private Plant plantCenter3Plant3 = new Plant(3, "P0104", "Hartlelie", "Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.");
// private Plant plantCenter1Plant3 = new Plant(1, "Lavendel", "De lavendel is vooral populair door de mooie diep paarse kleur én de heerlijke geur die deze plant verspreidt. Lavendel is een kleine vaste tuinplant voor in de tuin. De plant wordt namelijk niet hoger dan één meter en doet klein aan door de dunne stengels waar de plant uit bestaat.");
// private Plant plantCenter2Plant2 = new Plant(2, "Viooltje", "Niet iedere populaire plant is een grote plant. Het kleine viooltje blijft een favoriet voor in de Nederlandse tuin. Dit omdat wij toch wel fan zijn van dit kleine, fleurige plantje. Door de vele kleuruitvoeringen past er in iedere tuin wel een viooltje en daarom kon hij niet ontbreken in deze lijst van de meest populaire tuinplanten van Nederland.");
// private Plant<SUF>
// private Plant plantCenter2Plant4 = new Plant(2, "Spaanse margriet", "De Spaanse margriet is niet, zoals je zou verwachten, afkomstig uit Spanje. Deze populaire plant komt uit het verre Zuid-Afrika en is een éénjarige tuinplant.");
// private Plant plantCenter3Plant1 = new Plant(3, "Vlinderstruik", "Dat de vlinderstruik bij de meest populaire tuinplanten van Nederland zit verbaasd ons wederom niets. Deze plant is niet alleen mooi om te zien, maar trekt ook nog eens de mooiste vlinders aan. Zo zullen onder andere het koolwitje, de citroenvlinder en de atalanta de verleiding van deze plant niet kunnen weerstaan.");
@BeforeEach
public void beforeAllTests() {
// Make sure EVERYTHING is deleted from the db
plantRepository.deleteAll();
// Save all the plants
plantRepository.save(plantCenter1Plant1);
plantRepository.save(plantCenter1Plant2);
plantRepository.save(plantCenter2Plant1);
plantRepository.save(plantCenter3Plant2);
plantRepository.save(plantCenter3Plant3);
// plantRepository.save(plantCenter1Plant3);
// plantRepository.save(plantCenter2Plant2);
// plantRepository.save(plantCenter2Plant3);
// plantRepository.save(plantCenter2Plant4);
// plantRepository.save(plantCenter3Plant1);
}
@AfterEach
public void afterAllTests() {
// Watch out with deleteAll() methods when you have other data in the test database!!
plantRepository.deleteAll();
}
private ObjectMapper mapper = new ObjectMapper();
@Test
public void givenPlant_whenGetPlantByName_ThenReturnJsonPlant() throws Exception {
mockMvc.perform(get("/plants/name/{name}", "Kerstroos"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(1)))
.andExpect(jsonPath("$.plantNumber", is("P0100")))
.andExpect(jsonPath("$.name", is("Kerstroos")))
.andExpect(jsonPath("$.description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")));
}
@Test
public void givenPlant_whenGetPlantByPlantNumber_ThenReturnJsonPlant() throws Exception {
mockMvc.perform(get("/plants/{plantNumber}", "P0100"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(1)))
.andExpect(jsonPath("$.plantNumber", is("P0100")))
.andExpect(jsonPath("$.name", is("Kerstroos")))
.andExpect(jsonPath("$.description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")));
}
@Test
public void givenPlant_whenGetPlantByContainingDescription_ThenReturnJsonPlants() throws Exception {
// Only one plant found
mockMvc.perform(get("/plants/description/{description}", "Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen."))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].gardenCenterId", is(1)))
.andExpect(jsonPath("$[0].plantNumber", is("P0101")))
.andExpect(jsonPath("$[0].name", is("Hortensia")))
.andExpect(jsonPath("$[0].description", is("Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.")));
// Two plants founf
mockMvc.perform(get("/plants/description/{description}", "groen"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].gardenCenterId", is(3)))
.andExpect(jsonPath("$[0].plantNumber", is("P0103")))
.andExpect(jsonPath("$[0].name", is("Klimop")))
.andExpect(jsonPath("$[0].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(3)))
.andExpect(jsonPath("$[1].plantNumber", is("P0104")))
.andExpect(jsonPath("$[1].name", is("Hartlelie")))
.andExpect(jsonPath("$[1].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void givenPlant_whenGetPlantByGardenCenterId_ThenReturnJsonPlants() throws Exception {
mockMvc.perform(get("/plants/gardencenterid/{gardenCenterId}", 3))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].gardenCenterId", is(3)))
.andExpect(jsonPath("$[0].plantNumber", is("P0103")))
.andExpect(jsonPath("$[0].name", is("Klimop")))
.andExpect(jsonPath("$[0].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(3)))
.andExpect(jsonPath("$[1].plantNumber", is("P0104")))
.andExpect(jsonPath("$[1].name", is("Hartlelie")))
.andExpect(jsonPath("$[1].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void givenPlant_whenPlants_ThenReturnAllJsonPlants() throws Exception {
mockMvc.perform(get("/plants"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(5)))
.andExpect(jsonPath("$[0].gardenCenterId", is(1)))
.andExpect(jsonPath("$[0].plantNumber", is("P0100")))
.andExpect(jsonPath("$[0].name", is("Kerstroos")))
.andExpect(jsonPath("$[0].description", is("De Helleborus niger staat beter bekend als de kerstroos. Deze tuinplant dankt die bijnaam onder andere aan zijn bijzondere bloeiperiode. Wanneer de rest van de tuin in diepe winterrust is, bloeit de kerstroos namelijk helemaal op. Volgens een oude legende zou de eerste kerstroos in Bethlehem zijn ontsproten uit de tranen van een arme herder die geen geschenk had voor het kindje Jezus. Op die manier kon hij de bloemen geven.")))
.andExpect(jsonPath("$[1].gardenCenterId", is(1)))
.andExpect(jsonPath("$[1].plantNumber", is("P0101")))
.andExpect(jsonPath("$[1].name", is("Hortensia")))
.andExpect(jsonPath("$[1].description", is("Het zal je waarschijnlijk niet verbazen de hortensia in de lijst tegen te komen. Deze plant kom je in veel Nederlandse voor- en achtertuinen tegen. De hortensia kent veel verschillende soorten, maar de populairste is toch wel de Hydrangea macrophylla.")))
.andExpect(jsonPath("$[2].gardenCenterId", is(2)))
.andExpect(jsonPath("$[2].plantNumber", is("P0102")))
.andExpect(jsonPath("$[2].name", is("Buxus")))
.andExpect(jsonPath("$[2].description", is("De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.")))
.andExpect(jsonPath("$[3].gardenCenterId", is(3)))
.andExpect(jsonPath("$[3].plantNumber", is("P0103")))
.andExpect(jsonPath("$[3].name", is("Klimop")))
.andExpect(jsonPath("$[3].description", is("Ondanks dat sommigen hem liever kwijt zijn dan rijk, is de klimop in Nederland een erg populaire plant. Waarschijnlijk heeft de plant deze status te danken aan het feit dat het een makkelijke plant is die het overal goed doet. Ook blijft de Hedera het hele jaar door groen en is het een geschikte plant om het gevoel van een verticale tuin mee te creëren.")))
.andExpect(jsonPath("$[4].gardenCenterId", is(3)))
.andExpect(jsonPath("$[4].plantNumber", is("P0104")))
.andExpect(jsonPath("$[4].name", is("Hartlelie")))
.andExpect(jsonPath("$[4].description", is("Door zijn vele soorten is er wat de hartlelie betreft voor iedereen wel een passende variant te vinden. De Hosta is bijvoorbeeld te krijgen met goudgele, witte, roomwit omrande, groene of blauwe (zweem) bladeren.")));
}
@Test
public void whenPostPlant_thenReturnJsonPlant() throws Exception {
Plant plantCenter2Plant5 = new Plant(2, "P0105", "Ice Dance", "De Carex morrowii 'Ice Dance' is een laagblijvend siergras dat in de breedte groeit met schuin opgaande bladeren. De 'Ice Dance' wordt max. 40cm hoog worden.");
mockMvc.perform(post("/plants")
.content(mapper.writeValueAsString(plantCenter2Plant5))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(2)))
.andExpect(jsonPath("$.plantNumber", is("P0105")))
.andExpect(jsonPath("$.name", is("Ice Dance")))
.andExpect(jsonPath("$.description", is("De Carex morrowii 'Ice Dance' is een laagblijvend siergras dat in de breedte groeit met schuin opgaande bladeren. De 'Ice Dance' wordt max. 40cm hoog worden.")));
}
@Test
public void givenPlant_whenPutPlant_thenReturnJsonPlant() throws Exception {
Plant updatedPlant = new Plant(2, "P0102", "BuxusUPDATE", "De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.");
mockMvc.perform(put("/plants")
.content(mapper.writeValueAsString(updatedPlant))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.gardenCenterId", is(2)))
.andExpect(jsonPath("$.plantNumber", is("P0102")))
.andExpect(jsonPath("$.name", is("BuxusUPDATE")))
.andExpect(jsonPath("$.description", is("De buxus is zo'n fijne plant, omdat je deze in werkelijk alle vormen kunt snoeien waarin je maar wilt. Hierdoor zijn ze in iedere tuin precies naar de wensen van de eigenaar te gebruiken.")));
}
@Test
public void givenPlant_whenDeletePlant_thenStatusOk() throws Exception {
// Plant is IN db
mockMvc.perform(delete("/plants/{plantNumber}", "P0100")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void givenNoRPlant_whenDeletePlant_thenStatusNotFound() throws Exception {
// Plant is NOT in db
mockMvc.perform(delete("/plants/{plantNumber}", "K9999")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
|
187431_2 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sql;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.extensions.sql.SqlTransform;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
public class BasicSQL {
private static final Logger LOG = LoggerFactory.getLogger(BasicSQL.class);
public static final Schema rowSchema = Schema.builder()
.addStringField("name")
.addInt32Field("year")
.addStringField("country")
.build();
public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(PipelineOptions.class);
Pipeline p = Pipeline.create(options);
final List<String> elements = Arrays.asList(
"John, 1990, USA",
"Charles, 1995, USA",
"Alice, 1997, Spain",
"Bob, 1995, USA",
"Amanda, 1991, France",
"Alex, 1999, Mexico",
"Eliza, 2000, Japan"
);
p
.apply(Create.of(elements))
//Convert to Row
.apply("to Row", ParDo.of(new DoFn<String, Row>() {
@ProcessElement
public void processElement(ProcessContext c) {
String[] columns = c.element().split(", ");
Row row = Row
.withSchema(rowSchema)
.addValues(columns[0], Integer.parseInt(columns[1]), columns[2])
.build();
c.output(row);
}
})).setRowSchema(rowSchema) // Output needs an schema
// SQL
.apply(SqlTransform.query(
"SELECT COUNT(*) AS `count`, `year`, country FROM PCOLLECTION GROUP BY `year`, country")) // year and count with `` since are part of Calcite SQL
.apply("Log", ParDo.of(new DoFn<Row, String>() {
@ProcessElement
public void processElement(ProcessContext c) {
Row row = c.element();
Long count = row.getInt64("count"); // COUNT is type Long
Integer year = row.getInt32(1); // You can use the index
String country = row.getString("country");
String finalString = String.format("Country %s has total %d for year %d", country, count, year);
LOG.info(finalString);
c.output(finalString);
}
})
);
p.run();
}
}
| GoogleCloudPlatform/dataflow-cookbook | Java/src/main/java/sql/BasicSQL.java | 982 | // Output needs an schema | line_comment | nl | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sql;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.extensions.sql.SqlTransform;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
public class BasicSQL {
private static final Logger LOG = LoggerFactory.getLogger(BasicSQL.class);
public static final Schema rowSchema = Schema.builder()
.addStringField("name")
.addInt32Field("year")
.addStringField("country")
.build();
public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(PipelineOptions.class);
Pipeline p = Pipeline.create(options);
final List<String> elements = Arrays.asList(
"John, 1990, USA",
"Charles, 1995, USA",
"Alice, 1997, Spain",
"Bob, 1995, USA",
"Amanda, 1991, France",
"Alex, 1999, Mexico",
"Eliza, 2000, Japan"
);
p
.apply(Create.of(elements))
//Convert to Row
.apply("to Row", ParDo.of(new DoFn<String, Row>() {
@ProcessElement
public void processElement(ProcessContext c) {
String[] columns = c.element().split(", ");
Row row = Row
.withSchema(rowSchema)
.addValues(columns[0], Integer.parseInt(columns[1]), columns[2])
.build();
c.output(row);
}
})).setRowSchema(rowSchema) // Output needs<SUF>
// SQL
.apply(SqlTransform.query(
"SELECT COUNT(*) AS `count`, `year`, country FROM PCOLLECTION GROUP BY `year`, country")) // year and count with `` since are part of Calcite SQL
.apply("Log", ParDo.of(new DoFn<Row, String>() {
@ProcessElement
public void processElement(ProcessContext c) {
Row row = c.element();
Long count = row.getInt64("count"); // COUNT is type Long
Integer year = row.getInt32(1); // You can use the index
String country = row.getString("country");
String finalString = String.format("Country %s has total %d for year %d", country, count, year);
LOG.info(finalString);
c.output(finalString);
}
})
);
p.run();
}
}
|
15814_4 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.AccessConfig;
import com.google.api.services.compute.model.AttachedDisk;
import com.google.api.services.compute.model.AttachedDiskInitializeParams;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
import com.google.api.services.compute.model.Metadata;
import com.google.api.services.compute.model.NetworkInterface;
import com.google.api.services.compute.model.Operation;
import com.google.api.services.compute.model.ServiceAccount;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Command-line sample to demo listing Google Compute Engine instances using Java and the Google
* Compute Engine API.
*
* @author Jonathan Simon
*/
public class ComputeEngineSample {
/**
* Be sure to specify the name of your application. If the application name is {@code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "";
/** Set PROJECT_ID to your Project ID from the Overview pane in the Developers console. */
private static final String PROJECT_ID = "YOUR_PROJECT_ID";
/** Set Compute Engine zone. */
private static final String ZONE_NAME = "us-central1-f";
/** Set the name of the sample VM instance to be created. */
private static final String SAMPLE_INSTANCE_NAME = "my-sample-instance";
/** Set the path of the OS image for the sample VM instance to be created. */
private static final String SOURCE_IMAGE_PREFIX =
"https://www.googleapis.com/compute/v1/projects/";
private static final String SOURCE_IMAGE_PATH =
"ubuntu-os-cloud/global/images/ubuntu-2004-focal-v20200529";
/** Set the Network configuration values of the sample VM instance to be created. */
private static final String NETWORK_INTERFACE_CONFIG = "ONE_TO_ONE_NAT";
private static final String NETWORK_ACCESS_CONFIG = "External NAT";
/** Set the time out limit for operation calls to the Compute Engine API. */
private static final long OPERATION_TIMEOUT_MILLIS = 60 * 1000;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
public static void main(String[] args) {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// Authenticate using Google Application Default Credentials.
GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
// Set Google Cloud Storage scope to Full Control.
scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
// Set Google Compute Engine scope to Read-write.
scopes.add(ComputeScopes.COMPUTE);
credential = credential.createScoped(scopes);
}
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
// Create Compute Engine object for listing instances.
Compute compute =
new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
// List out instances, looking for the one created by this sample app.
boolean foundOurInstance = printInstances(compute);
Operation op;
if (foundOurInstance) {
op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
} else {
op = startInstance(compute, SAMPLE_INSTANCE_NAME);
}
// Call Compute Engine API operation and poll for operation completion status
System.out.println("Waiting for operation completion...");
Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
if (error == null) {
System.out.println("Success!");
} else {
System.out.println(error.toPrettyString());
}
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
// [START list_instances]
/**
* Print available machine instances.
*
* @param compute The main API access point
* @return {@code true} if the instance created by this sample app is in the list
*/
public static boolean printInstances(Compute compute) throws IOException {
System.out.println("================== Listing Compute Engine Instances ==================");
Compute.Instances.List instances = compute.instances().list(PROJECT_ID, ZONE_NAME);
InstanceList list = instances.execute();
boolean found = false;
if (list.getItems() == null) {
System.out.println(
"No instances found. Sign in to the Google Developers Console and create "
+ "an instance at: https://console.developers.google.com/");
} else {
for (Instance instance : list.getItems()) {
System.out.println(instance.toPrettyString());
if (instance.getName().equals(SAMPLE_INSTANCE_NAME)) {
found = true;
}
}
}
return found;
}
// [END list_instances]
// [START create_instances]
public static Operation startInstance(Compute compute, String instanceName) throws IOException {
System.out.println("================== Starting New Instance ==================");
// Create VM Instance object with the required properties.
Instance instance = new Instance();
instance.setName(instanceName);
instance.setMachineType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/e2-standard-1",
PROJECT_ID, ZONE_NAME));
// Add Network Interface to be used by VM Instance.
NetworkInterface ifc = new NetworkInterface();
ifc.setNetwork(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/global/networks/default",
PROJECT_ID));
List<AccessConfig> configs = new ArrayList<>();
AccessConfig config = new AccessConfig();
config.setType(NETWORK_INTERFACE_CONFIG);
config.setName(NETWORK_ACCESS_CONFIG);
configs.add(config);
ifc.setAccessConfigs(configs);
instance.setNetworkInterfaces(Collections.singletonList(ifc));
// Add attached Persistent Disk to be used by VM Instance.
AttachedDisk disk = new AttachedDisk();
disk.setBoot(true);
disk.setAutoDelete(true);
disk.setType("PERSISTENT");
AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
// Assign the Persistent Disk the same name as the VM Instance.
params.setDiskName(instanceName);
// Specify the source operating system machine image to be used by the VM Instance.
params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH);
// Specify the disk type as Standard Persistent Disk
params.setDiskType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/diskTypes/pd-standard",
PROJECT_ID, ZONE_NAME));
disk.setInitializeParams(params);
instance.setDisks(Collections.singletonList(disk));
// Initialize the service account to be used by the VM Instance and set the API access scopes.
ServiceAccount account = new ServiceAccount();
account.setEmail("default");
List<String> scopes = new ArrayList<>();
scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
scopes.add("https://www.googleapis.com/auth/compute");
account.setScopes(scopes);
instance.setServiceAccounts(Collections.singletonList(account));
// Optional - Add a startup script to be used by the VM Instance.
Metadata meta = new Metadata();
Metadata.Items item = new Metadata.Items();
item.setKey("startup-script-url");
// If you put a script called "vm-startup.sh" in this Google Cloud Storage
// bucket, it will execute on VM startup. This assumes you've created a
// bucket named the same as your PROJECT_ID.
// For info on creating buckets see:
// https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
item.setValue(String.format("gs://%s/vm-startup.sh", PROJECT_ID));
meta.setItems(Collections.singletonList(item));
instance.setMetadata(meta);
System.out.println(instance.toPrettyString());
Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance);
return insert.execute();
}
// [END create_instances]
private static Operation deleteInstance(Compute compute, String instanceName) throws Exception {
System.out.println(
"================== Deleting Instance " + instanceName + " ==================");
Compute.Instances.Delete delete =
compute.instances().delete(PROJECT_ID, ZONE_NAME, instanceName);
return delete.execute();
}
public static String getLastWordFromUrl(String url) {
if (url != null) {
String[] bits = url.split("/");
url = bits[bits.length - 1];
}
return url;
}
// [START wait_until_complete]
/**
* Wait until {@code operation} is completed.
*
* @param compute the {@code Compute} object
* @param operation the operation returned by the original request
* @param timeout the timeout, in millis
* @return the error, if any, else {@code null} if there was no error
* @throws InterruptedException if we timed out waiting for the operation to complete
* @throws IOException if we had trouble connecting
*/
public static Operation.Error blockUntilComplete(
Compute compute, Operation operation, long timeout) throws Exception {
long start = System.currentTimeMillis();
final long pollInterval = 5 * 1000;
String zone = getLastWordFromUrl(operation.getZone()); // null for global/regional operations
String region = getLastWordFromUrl(operation.getRegion());
String status = operation.getStatus();
String opId = operation.getName();
while (operation != null && !status.equals("DONE")) {
Thread.sleep(pollInterval);
long elapsed = System.currentTimeMillis() - start;
if (elapsed >= timeout) {
throw new InterruptedException("Timed out waiting for operation to complete");
}
System.out.println("waiting...");
if (zone != null) {
Compute.ZoneOperations.Get get = compute.zoneOperations().get(PROJECT_ID, zone, opId);
operation = get.execute();
} else if (region != null) {
Compute.RegionOperations.Get get = compute.regionOperations().get(PROJECT_ID, region, opId);
operation = get.execute();
} else {
Compute.GlobalOperations.Get get = compute.globalOperations().get(PROJECT_ID, opId);
operation = get.execute();
}
if (operation != null) {
status = operation.getStatus();
}
}
return operation == null ? null : operation.getError();
}
// [END wait_until_complete]
}
| GoogleCloudPlatform/java-docs-samples | compute/cmdline/src/main/java/ComputeEngineSample.java | 3,451 | /** Set Compute Engine zone. */ | block_comment | nl | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.AccessConfig;
import com.google.api.services.compute.model.AttachedDisk;
import com.google.api.services.compute.model.AttachedDiskInitializeParams;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
import com.google.api.services.compute.model.Metadata;
import com.google.api.services.compute.model.NetworkInterface;
import com.google.api.services.compute.model.Operation;
import com.google.api.services.compute.model.ServiceAccount;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Command-line sample to demo listing Google Compute Engine instances using Java and the Google
* Compute Engine API.
*
* @author Jonathan Simon
*/
public class ComputeEngineSample {
/**
* Be sure to specify the name of your application. If the application name is {@code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "";
/** Set PROJECT_ID to your Project ID from the Overview pane in the Developers console. */
private static final String PROJECT_ID = "YOUR_PROJECT_ID";
/** Set Compute Engine<SUF>*/
private static final String ZONE_NAME = "us-central1-f";
/** Set the name of the sample VM instance to be created. */
private static final String SAMPLE_INSTANCE_NAME = "my-sample-instance";
/** Set the path of the OS image for the sample VM instance to be created. */
private static final String SOURCE_IMAGE_PREFIX =
"https://www.googleapis.com/compute/v1/projects/";
private static final String SOURCE_IMAGE_PATH =
"ubuntu-os-cloud/global/images/ubuntu-2004-focal-v20200529";
/** Set the Network configuration values of the sample VM instance to be created. */
private static final String NETWORK_INTERFACE_CONFIG = "ONE_TO_ONE_NAT";
private static final String NETWORK_ACCESS_CONFIG = "External NAT";
/** Set the time out limit for operation calls to the Compute Engine API. */
private static final long OPERATION_TIMEOUT_MILLIS = 60 * 1000;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
public static void main(String[] args) {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// Authenticate using Google Application Default Credentials.
GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
// Set Google Cloud Storage scope to Full Control.
scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
// Set Google Compute Engine scope to Read-write.
scopes.add(ComputeScopes.COMPUTE);
credential = credential.createScoped(scopes);
}
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
// Create Compute Engine object for listing instances.
Compute compute =
new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
// List out instances, looking for the one created by this sample app.
boolean foundOurInstance = printInstances(compute);
Operation op;
if (foundOurInstance) {
op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
} else {
op = startInstance(compute, SAMPLE_INSTANCE_NAME);
}
// Call Compute Engine API operation and poll for operation completion status
System.out.println("Waiting for operation completion...");
Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
if (error == null) {
System.out.println("Success!");
} else {
System.out.println(error.toPrettyString());
}
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
// [START list_instances]
/**
* Print available machine instances.
*
* @param compute The main API access point
* @return {@code true} if the instance created by this sample app is in the list
*/
public static boolean printInstances(Compute compute) throws IOException {
System.out.println("================== Listing Compute Engine Instances ==================");
Compute.Instances.List instances = compute.instances().list(PROJECT_ID, ZONE_NAME);
InstanceList list = instances.execute();
boolean found = false;
if (list.getItems() == null) {
System.out.println(
"No instances found. Sign in to the Google Developers Console and create "
+ "an instance at: https://console.developers.google.com/");
} else {
for (Instance instance : list.getItems()) {
System.out.println(instance.toPrettyString());
if (instance.getName().equals(SAMPLE_INSTANCE_NAME)) {
found = true;
}
}
}
return found;
}
// [END list_instances]
// [START create_instances]
public static Operation startInstance(Compute compute, String instanceName) throws IOException {
System.out.println("================== Starting New Instance ==================");
// Create VM Instance object with the required properties.
Instance instance = new Instance();
instance.setName(instanceName);
instance.setMachineType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/e2-standard-1",
PROJECT_ID, ZONE_NAME));
// Add Network Interface to be used by VM Instance.
NetworkInterface ifc = new NetworkInterface();
ifc.setNetwork(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/global/networks/default",
PROJECT_ID));
List<AccessConfig> configs = new ArrayList<>();
AccessConfig config = new AccessConfig();
config.setType(NETWORK_INTERFACE_CONFIG);
config.setName(NETWORK_ACCESS_CONFIG);
configs.add(config);
ifc.setAccessConfigs(configs);
instance.setNetworkInterfaces(Collections.singletonList(ifc));
// Add attached Persistent Disk to be used by VM Instance.
AttachedDisk disk = new AttachedDisk();
disk.setBoot(true);
disk.setAutoDelete(true);
disk.setType("PERSISTENT");
AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
// Assign the Persistent Disk the same name as the VM Instance.
params.setDiskName(instanceName);
// Specify the source operating system machine image to be used by the VM Instance.
params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH);
// Specify the disk type as Standard Persistent Disk
params.setDiskType(
String.format(
"https://www.googleapis.com/compute/v1/projects/%s/zones/%s/diskTypes/pd-standard",
PROJECT_ID, ZONE_NAME));
disk.setInitializeParams(params);
instance.setDisks(Collections.singletonList(disk));
// Initialize the service account to be used by the VM Instance and set the API access scopes.
ServiceAccount account = new ServiceAccount();
account.setEmail("default");
List<String> scopes = new ArrayList<>();
scopes.add("https://www.googleapis.com/auth/devstorage.full_control");
scopes.add("https://www.googleapis.com/auth/compute");
account.setScopes(scopes);
instance.setServiceAccounts(Collections.singletonList(account));
// Optional - Add a startup script to be used by the VM Instance.
Metadata meta = new Metadata();
Metadata.Items item = new Metadata.Items();
item.setKey("startup-script-url");
// If you put a script called "vm-startup.sh" in this Google Cloud Storage
// bucket, it will execute on VM startup. This assumes you've created a
// bucket named the same as your PROJECT_ID.
// For info on creating buckets see:
// https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
item.setValue(String.format("gs://%s/vm-startup.sh", PROJECT_ID));
meta.setItems(Collections.singletonList(item));
instance.setMetadata(meta);
System.out.println(instance.toPrettyString());
Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance);
return insert.execute();
}
// [END create_instances]
private static Operation deleteInstance(Compute compute, String instanceName) throws Exception {
System.out.println(
"================== Deleting Instance " + instanceName + " ==================");
Compute.Instances.Delete delete =
compute.instances().delete(PROJECT_ID, ZONE_NAME, instanceName);
return delete.execute();
}
public static String getLastWordFromUrl(String url) {
if (url != null) {
String[] bits = url.split("/");
url = bits[bits.length - 1];
}
return url;
}
// [START wait_until_complete]
/**
* Wait until {@code operation} is completed.
*
* @param compute the {@code Compute} object
* @param operation the operation returned by the original request
* @param timeout the timeout, in millis
* @return the error, if any, else {@code null} if there was no error
* @throws InterruptedException if we timed out waiting for the operation to complete
* @throws IOException if we had trouble connecting
*/
public static Operation.Error blockUntilComplete(
Compute compute, Operation operation, long timeout) throws Exception {
long start = System.currentTimeMillis();
final long pollInterval = 5 * 1000;
String zone = getLastWordFromUrl(operation.getZone()); // null for global/regional operations
String region = getLastWordFromUrl(operation.getRegion());
String status = operation.getStatus();
String opId = operation.getName();
while (operation != null && !status.equals("DONE")) {
Thread.sleep(pollInterval);
long elapsed = System.currentTimeMillis() - start;
if (elapsed >= timeout) {
throw new InterruptedException("Timed out waiting for operation to complete");
}
System.out.println("waiting...");
if (zone != null) {
Compute.ZoneOperations.Get get = compute.zoneOperations().get(PROJECT_ID, zone, opId);
operation = get.execute();
} else if (region != null) {
Compute.RegionOperations.Get get = compute.regionOperations().get(PROJECT_ID, region, opId);
operation = get.execute();
} else {
Compute.GlobalOperations.Get get = compute.globalOperations().get(PROJECT_ID, opId);
operation = get.execute();
}
if (operation != null) {
status = operation.getStatus();
}
}
return operation == null ? null : operation.getError();
}
// [END wait_until_complete]
}
|
152525_12 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 tech.mlsql.ets.hdfs;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.shell.*;
import org.apache.hadoop.tools.TableListing;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
/**
* 2019-05-07 WilliamZhu([email protected])
*/
public class WowFsShell extends Configured implements Tool {
static final Log LOG = LogFactory.getLog(WowFsShell.class);
private static final int MAX_LINE_WIDTH = 80;
private FileSystem fs;
protected String basePath;
protected CommandFactory commandFactory;
private final ByteArrayOutputStream outS = new ByteArrayOutputStream();
private final ByteArrayOutputStream errorS = new ByteArrayOutputStream();
public final PrintStream out = new PrintStream(outS);
public final PrintStream error = new PrintStream(errorS);
public String getOut() {
return _out(outS);
}
public String _out(ByteArrayOutputStream wow) {
try {
String temp = wow.toString("UTF8");
wow.reset();
return temp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getError() {
return _out(errorS);
}
private final String usagePrefix =
"Usage: hadoop fs [generic options]";
/**
* Default ctor with no configuration. Be sure to invoke
* {@link #setConf(Configuration)} with a valid configuration prior
* to running commands.
*/
public WowFsShell() {
this(null, null);
}
/**
* Construct a FsShell with the given configuration. Commands can be
* executed via {@link #run(String[])}
*
* @param conf the hadoop configuration
*/
public WowFsShell(Configuration conf, String basePath) {
super(conf);
if(!StringUtils.isBlank(basePath)) {
this.basePath = basePath;
} else {
this.basePath = "/";
}
}
protected FileSystem getFS() throws IOException {
if (fs == null) {
fs = FileSystem.get(getConf());
}
return fs;
}
protected void init() throws IOException {
getConf().setQuietMode(true);
if (commandFactory == null) {
commandFactory = new WowCommandFactory(getConf());
commandFactory.addObject(new WowFsShell.Help(getConf(), basePath, out, error), "-help");
commandFactory.addObject(new WowFsShell.Usage(getConf(), basePath, out, error), "-usage");
commandFactory.addObject(new WowLs(getConf(), basePath, out, error), "-ls");
commandFactory.addObject(new WowLs.Lsr(getConf(), basePath, out, error), "-lsr");
commandFactory.addObject(new WowDelete.Rm(getConf(), basePath, out, error), "-rm");
commandFactory.addObject(new WowDelete.Rmdir(getConf(), basePath, out, error), "-rmdir");
commandFactory.addObject(new WowDelete.Rmr(getConf(), basePath, out, error), "-rmr");
commandFactory.addObject(new WowMoveCommands.Rename(getConf(), basePath, out, error), "-mv");
commandFactory.addObject(new WowMkdir(getConf(), basePath, out, error), "-mkdir");
commandFactory.addObject(new WowCopyCommands.Merge(getConf(), basePath, out, error), "-getmerge");
commandFactory.addObject(new WowCopyCommands.Cp(getConf(), basePath, out, error), "-cp");
commandFactory.addObject(new WowCount(getConf(), basePath, out, error), "-count");
}
}
// NOTE: Usage/Help are inner classes to allow access to outer methods
// that access commandFactory
/**
* Display help for commands with their short usage and long description
*/
protected class Usage extends WowFsCommand {
public static final String NAME = "usage";
public static final String USAGE = "[cmd ...]";
public static final String DESCRIPTION =
"Displays the usage for given command or all commands if none " +
"is specified.";
public Usage(Configuration conf, String basePath, PrintStream out, PrintStream error) {
super(conf, basePath, out, error);
}
@Override
protected void processRawArguments(LinkedList<String> args) {
if (args.isEmpty()) {
printUsage(out);
} else {
for (String arg : args) printUsage(out, arg);
}
}
}
/**
* Displays short usage of commands sans the long description
*/
protected class Help extends WowFsCommand {
public static final String NAME = "help";
public static final String USAGE = "[cmd ...]";
public static final String DESCRIPTION =
"Displays help for given command or all commands if none " +
"is specified.";
public Help(Configuration conf, String basePath, PrintStream out, PrintStream error) {
super(conf, basePath, out, error);
}
@Override
protected void processRawArguments(LinkedList<String> args) {
if (args.isEmpty()) {
printHelp(out);
} else {
for (String arg : args) printHelp(out, arg);
}
}
}
/*
* The following are helper methods for getInfo(). They are defined
* outside of the scope of the Help/Usage class because the run() method
* needs to invoke them too.
*/
// print all usages
private void printUsage(PrintStream out) {
printInfo(out, null, false);
}
// print one usage
private void printUsage(PrintStream out, String cmd) {
printInfo(out, cmd, false);
}
// print all helps
private void printHelp(PrintStream out) {
printInfo(out, null, true);
}
// print one help
private void printHelp(PrintStream out, String cmd) {
printInfo(out, cmd, true);
}
private void printInfo(PrintStream out, String cmd, boolean showHelp) {
if (cmd != null) {
// display help or usage for one command
Command instance = commandFactory.getInstance("-" + cmd);
if (instance == null) {
throw new WowFsShell.UnknownCommandException(cmd);
}
if (showHelp) {
printInstanceHelp(out, instance);
} else {
printInstanceUsage(out, instance);
}
} else {
// display help or usage for all commands
out.println(usagePrefix);
// display list of short usages
ArrayList<Command> instances = new ArrayList<Command>();
for (String name : commandFactory.getNames()) {
Command instance = commandFactory.getInstance(name);
if (!instance.isDeprecated()) {
out.println("\t[" + instance.getUsage() + "]");
instances.add(instance);
}
}
// display long descriptions for each command
if (showHelp) {
for (Command instance : instances) {
out.println();
printInstanceHelp(out, instance);
}
}
out.println();
ToolRunner.printGenericCommandUsage(out);
}
}
private void printInstanceUsage(PrintStream out, Command instance) {
out.println(usagePrefix + " " + instance.getUsage());
}
private void printInstanceHelp(PrintStream out, Command instance) {
out.println(instance.getUsage() + " :");
TableListing listing = null;
final String prefix = " ";
for (String line : instance.getDescription().split("\n")) {
if (line.matches("^[ \t]*[-<].*$")) {
String[] segments = line.split(":");
if (segments.length == 2) {
if (listing == null) {
listing = createOptionTableListing();
}
listing.addRow(segments[0].trim(), segments[1].trim());
continue;
}
}
// Normal literal description.
if (listing != null) {
for (String listingLine : listing.toString().split("\n")) {
out.println(prefix + listingLine);
}
listing = null;
}
for (String descLine : WordUtils.wrap(
line, MAX_LINE_WIDTH, "\n", true).split("\n")) {
out.println(prefix + descLine);
}
}
if (listing != null) {
for (String listingLine : listing.toString().split("\n")) {
out.println(prefix + listingLine);
}
}
}
// Creates a two-row table, the first row is for the command line option,
// the second row is for the option description.
private TableListing createOptionTableListing() {
return new TableListing.Builder().addField("").addField("", true)
.wrapWidth(MAX_LINE_WIDTH).build();
}
/**
* run
*/
@Override
public int run(String argv[]) throws Exception {
// initialize FsShell
init();
int exitCode = -1;
if (argv.length < 1) {
printUsage(error);
} else {
String cmd = argv[0];
Command instance = null;
try {
instance = commandFactory.getInstance(cmd);
if (instance == null) {
throw new WowFsShell.UnknownCommandException();
}
exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length));
} catch (IllegalArgumentException e) {
displayError(cmd, e.getLocalizedMessage());
if (instance != null) {
printInstanceUsage(error, instance);
}
} catch (Exception e) {
// instance.run catches IOE, so something is REALLY wrong if here
LOG.debug("Error", e);
displayError(cmd, "Fatal internal error");
e.printStackTrace(error);
}
}
return exitCode;
}
private void displayError(String cmd, String message) {
for (String line : message.split("\n")) {
error.println(cmd + ": " + line);
if (cmd.charAt(0) != '-') {
Command instance = null;
instance = commandFactory.getInstance("-" + cmd);
if (instance != null) {
error.println("Did you mean -" + cmd + "? This command " +
"begins with a dash.");
}
}
}
}
/**
* Performs any necessary cleanup
*
* @throws IOException upon error
*/
public void close() throws IOException {
outS.close();
out.close();
errorS.close();
error.close();
}
/**
* The default ctor signals that the command being executed does not exist,
* while other ctor signals that a specific command does not exist. The
* latter is used by commands that process other commands, ex. -usage/-help
*/
@SuppressWarnings("serial")
static class UnknownCommandException extends IllegalArgumentException {
private final String cmd;
UnknownCommandException() {
this(null);
}
UnknownCommandException(String cmd) {
this.cmd = cmd;
}
@Override
public String getMessage() {
return ((cmd != null) ? "`" + cmd + "': " : "") + "Unknown command";
}
}
}
| Goryudyuma/streamingpro | streamingpro-mlsql/src/main/java/tech/mlsql/ets/hdfs/WowFsShell.java | 3,375 | // print one help | line_comment | nl | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 tech.mlsql.ets.hdfs;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.shell.*;
import org.apache.hadoop.tools.TableListing;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
/**
* 2019-05-07 WilliamZhu([email protected])
*/
public class WowFsShell extends Configured implements Tool {
static final Log LOG = LogFactory.getLog(WowFsShell.class);
private static final int MAX_LINE_WIDTH = 80;
private FileSystem fs;
protected String basePath;
protected CommandFactory commandFactory;
private final ByteArrayOutputStream outS = new ByteArrayOutputStream();
private final ByteArrayOutputStream errorS = new ByteArrayOutputStream();
public final PrintStream out = new PrintStream(outS);
public final PrintStream error = new PrintStream(errorS);
public String getOut() {
return _out(outS);
}
public String _out(ByteArrayOutputStream wow) {
try {
String temp = wow.toString("UTF8");
wow.reset();
return temp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getError() {
return _out(errorS);
}
private final String usagePrefix =
"Usage: hadoop fs [generic options]";
/**
* Default ctor with no configuration. Be sure to invoke
* {@link #setConf(Configuration)} with a valid configuration prior
* to running commands.
*/
public WowFsShell() {
this(null, null);
}
/**
* Construct a FsShell with the given configuration. Commands can be
* executed via {@link #run(String[])}
*
* @param conf the hadoop configuration
*/
public WowFsShell(Configuration conf, String basePath) {
super(conf);
if(!StringUtils.isBlank(basePath)) {
this.basePath = basePath;
} else {
this.basePath = "/";
}
}
protected FileSystem getFS() throws IOException {
if (fs == null) {
fs = FileSystem.get(getConf());
}
return fs;
}
protected void init() throws IOException {
getConf().setQuietMode(true);
if (commandFactory == null) {
commandFactory = new WowCommandFactory(getConf());
commandFactory.addObject(new WowFsShell.Help(getConf(), basePath, out, error), "-help");
commandFactory.addObject(new WowFsShell.Usage(getConf(), basePath, out, error), "-usage");
commandFactory.addObject(new WowLs(getConf(), basePath, out, error), "-ls");
commandFactory.addObject(new WowLs.Lsr(getConf(), basePath, out, error), "-lsr");
commandFactory.addObject(new WowDelete.Rm(getConf(), basePath, out, error), "-rm");
commandFactory.addObject(new WowDelete.Rmdir(getConf(), basePath, out, error), "-rmdir");
commandFactory.addObject(new WowDelete.Rmr(getConf(), basePath, out, error), "-rmr");
commandFactory.addObject(new WowMoveCommands.Rename(getConf(), basePath, out, error), "-mv");
commandFactory.addObject(new WowMkdir(getConf(), basePath, out, error), "-mkdir");
commandFactory.addObject(new WowCopyCommands.Merge(getConf(), basePath, out, error), "-getmerge");
commandFactory.addObject(new WowCopyCommands.Cp(getConf(), basePath, out, error), "-cp");
commandFactory.addObject(new WowCount(getConf(), basePath, out, error), "-count");
}
}
// NOTE: Usage/Help are inner classes to allow access to outer methods
// that access commandFactory
/**
* Display help for commands with their short usage and long description
*/
protected class Usage extends WowFsCommand {
public static final String NAME = "usage";
public static final String USAGE = "[cmd ...]";
public static final String DESCRIPTION =
"Displays the usage for given command or all commands if none " +
"is specified.";
public Usage(Configuration conf, String basePath, PrintStream out, PrintStream error) {
super(conf, basePath, out, error);
}
@Override
protected void processRawArguments(LinkedList<String> args) {
if (args.isEmpty()) {
printUsage(out);
} else {
for (String arg : args) printUsage(out, arg);
}
}
}
/**
* Displays short usage of commands sans the long description
*/
protected class Help extends WowFsCommand {
public static final String NAME = "help";
public static final String USAGE = "[cmd ...]";
public static final String DESCRIPTION =
"Displays help for given command or all commands if none " +
"is specified.";
public Help(Configuration conf, String basePath, PrintStream out, PrintStream error) {
super(conf, basePath, out, error);
}
@Override
protected void processRawArguments(LinkedList<String> args) {
if (args.isEmpty()) {
printHelp(out);
} else {
for (String arg : args) printHelp(out, arg);
}
}
}
/*
* The following are helper methods for getInfo(). They are defined
* outside of the scope of the Help/Usage class because the run() method
* needs to invoke them too.
*/
// print all usages
private void printUsage(PrintStream out) {
printInfo(out, null, false);
}
// print one usage
private void printUsage(PrintStream out, String cmd) {
printInfo(out, cmd, false);
}
// print all helps
private void printHelp(PrintStream out) {
printInfo(out, null, true);
}
// print one<SUF>
private void printHelp(PrintStream out, String cmd) {
printInfo(out, cmd, true);
}
private void printInfo(PrintStream out, String cmd, boolean showHelp) {
if (cmd != null) {
// display help or usage for one command
Command instance = commandFactory.getInstance("-" + cmd);
if (instance == null) {
throw new WowFsShell.UnknownCommandException(cmd);
}
if (showHelp) {
printInstanceHelp(out, instance);
} else {
printInstanceUsage(out, instance);
}
} else {
// display help or usage for all commands
out.println(usagePrefix);
// display list of short usages
ArrayList<Command> instances = new ArrayList<Command>();
for (String name : commandFactory.getNames()) {
Command instance = commandFactory.getInstance(name);
if (!instance.isDeprecated()) {
out.println("\t[" + instance.getUsage() + "]");
instances.add(instance);
}
}
// display long descriptions for each command
if (showHelp) {
for (Command instance : instances) {
out.println();
printInstanceHelp(out, instance);
}
}
out.println();
ToolRunner.printGenericCommandUsage(out);
}
}
private void printInstanceUsage(PrintStream out, Command instance) {
out.println(usagePrefix + " " + instance.getUsage());
}
private void printInstanceHelp(PrintStream out, Command instance) {
out.println(instance.getUsage() + " :");
TableListing listing = null;
final String prefix = " ";
for (String line : instance.getDescription().split("\n")) {
if (line.matches("^[ \t]*[-<].*$")) {
String[] segments = line.split(":");
if (segments.length == 2) {
if (listing == null) {
listing = createOptionTableListing();
}
listing.addRow(segments[0].trim(), segments[1].trim());
continue;
}
}
// Normal literal description.
if (listing != null) {
for (String listingLine : listing.toString().split("\n")) {
out.println(prefix + listingLine);
}
listing = null;
}
for (String descLine : WordUtils.wrap(
line, MAX_LINE_WIDTH, "\n", true).split("\n")) {
out.println(prefix + descLine);
}
}
if (listing != null) {
for (String listingLine : listing.toString().split("\n")) {
out.println(prefix + listingLine);
}
}
}
// Creates a two-row table, the first row is for the command line option,
// the second row is for the option description.
private TableListing createOptionTableListing() {
return new TableListing.Builder().addField("").addField("", true)
.wrapWidth(MAX_LINE_WIDTH).build();
}
/**
* run
*/
@Override
public int run(String argv[]) throws Exception {
// initialize FsShell
init();
int exitCode = -1;
if (argv.length < 1) {
printUsage(error);
} else {
String cmd = argv[0];
Command instance = null;
try {
instance = commandFactory.getInstance(cmd);
if (instance == null) {
throw new WowFsShell.UnknownCommandException();
}
exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length));
} catch (IllegalArgumentException e) {
displayError(cmd, e.getLocalizedMessage());
if (instance != null) {
printInstanceUsage(error, instance);
}
} catch (Exception e) {
// instance.run catches IOE, so something is REALLY wrong if here
LOG.debug("Error", e);
displayError(cmd, "Fatal internal error");
e.printStackTrace(error);
}
}
return exitCode;
}
private void displayError(String cmd, String message) {
for (String line : message.split("\n")) {
error.println(cmd + ": " + line);
if (cmd.charAt(0) != '-') {
Command instance = null;
instance = commandFactory.getInstance("-" + cmd);
if (instance != null) {
error.println("Did you mean -" + cmd + "? This command " +
"begins with a dash.");
}
}
}
}
/**
* Performs any necessary cleanup
*
* @throws IOException upon error
*/
public void close() throws IOException {
outS.close();
out.close();
errorS.close();
error.close();
}
/**
* The default ctor signals that the command being executed does not exist,
* while other ctor signals that a specific command does not exist. The
* latter is used by commands that process other commands, ex. -usage/-help
*/
@SuppressWarnings("serial")
static class UnknownCommandException extends IllegalArgumentException {
private final String cmd;
UnknownCommandException() {
this(null);
}
UnknownCommandException(String cmd) {
this.cmd = cmd;
}
@Override
public String getMessage() {
return ((cmd != null) ? "`" + cmd + "': " : "") + "Unknown command";
}
}
}
|
74859_5 | package com.games.Android.Laser_Cube.Objects;
import java.util.ArrayList;
import com.games.Android.Laser_Cube.Load.Vector;
public class Laser
{
private float level = 0;
private float breedte = 85;
private float hoogte = 45;
public float laser_time_opening = 0.4f;
public float laser_time_level1 = 1f;
public float Speed = 2.5f;
public Vector position = new Vector( );
public boolean Weg = false;
public boolean laser_weg = false;
//up/down or left/right
public boolean vertical = true;
//when up/down up or down, when left/right left or right, true is up for up/down and left for left/right
public boolean up_left = true;
private float laser_y = 100;
private float laser_x = 100;
private float laser_y_end = 100;
private float laser_x_end = 100;
private float length_laser = 0;
public float laser_size = 0f;
private float[] distance_cube = new float[30];
private float[] distance_mirror = new float[30];
private float[] distance_block = new float[30];
private float[] distance_radiation_tile = new float[30];
private float[] distance_colour_changer = new float[30];
private float distance_opening_tile = 100;
public boolean touched_opening_tile = false;
public boolean[] touched_radiation_tile = new boolean[30];
public boolean[] touched_block = new boolean[30];
//de 4 zijden van de mirrors
public boolean[] touched_mirror_top = new boolean[30];
public boolean[] touched_mirror_bottom = new boolean[30];
public boolean[] touched_mirror_left = new boolean[30];
public boolean[] touched_mirror_right = new boolean[30];
public boolean[] touched_colour_changer_top = new boolean[30];
public boolean[] touched_colour_changer_bottom = new boolean[30];
public boolean[] touched_colour_changer_left = new boolean[30];
public boolean[] touched_colour_changer_right = new boolean[30];
private float stroom = 0;
private int number_of_cubes = 0;
private int number_of_mirrors = 0;
private int number_of_radiation_tiles = 0;
private int number_of_blocks = 0;
private int number_of_colour_changers = 0;
public void Level( ArrayList<Cube> cubes, ArrayList<Mirror> mirrors, ArrayList<Radiation_Tile> radiation_tiles, ArrayList<Block> blocks, ArrayList<Colour_Changer> colour_changers )
{
reset_variabels();
if( mirrors == null )
{
number_of_mirrors = 0;
}
else
{
number_of_mirrors = ( mirrors.size() - 1 );
}
if( cubes == null )
{
number_of_cubes = 0;
}
else
{
number_of_cubes = ( cubes.size() - 1 );
}
if( radiation_tiles == null )
{
number_of_radiation_tiles = 0;
}
else
{
number_of_radiation_tiles = ( radiation_tiles.size() - 1 );
}
if( blocks == null )
{
number_of_blocks = 0;
}
else
{
number_of_blocks = ( blocks.size() - 1 );
}
if( colour_changers == null )
{
number_of_colour_changers = 0;
}
else
{
number_of_colour_changers = ( colour_changers.size() - 1 );
}
for( int i = 1; i <= number_of_cubes; i++ )
{
distance_cube[i] = cubes.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_mirrors; i++ )
{
distance_mirror[i] = mirrors.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_radiation_tiles; i++ )
{
distance_radiation_tile[i] = radiation_tiles.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_blocks; i++ )
{
distance_block[i] = blocks.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_colour_changers; i++ )
{
distance_colour_changer[i] = colour_changers.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
level = 1;
}
public void Opening_Screen( ArrayList<Mirror> mirrors )
{
reset_variabels();
distance_mirror[1] = mirrors.get(1).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[2] = mirrors.get(2).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[3] = mirrors.get(3).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[4] = mirrors.get(4).position.distance( new Vector( laser_x, laser_y, 0));
level = 8008;
}
private void reset_variabels()
{
for( int k = 0; k < 30; k++)
{
distance_mirror[k] = 100;
distance_radiation_tile[k] = 100;
distance_cube[k] = 100;
distance_block[k] = 100;
distance_colour_changer[k] = 100;
}
}
public void direction (boolean vertical, boolean up_left)
{
this.vertical = vertical;
this.up_left = up_left;
}
public void update()
{
//de laser gaat verticaal
if( vertical )
{
laser_y = (position.y + (laser_size + laser_size));
laser_y_end = ( position.y + laser_size );
laser_x = position.x;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x, laser_y_end, 0));
//de laser gaat verticaal omhoog
if ( up_left )
{
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_bottom[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_bottom[i] = false;
}
}
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if ( laser_y >= hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( laser_y_end > laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//de laser gaat verticaal omlaag
else
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_top[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_top[i] = false;
}
}
if ( laser_y <= -hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( laser_y_end < laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//Log.d( " mirror ", " distance " + laser_y );
}
else
{
laser_x = (position.x + (laser_size + laser_size));
laser_x_end = ( position.x + laser_size );
laser_y = position.y;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x_end, laser_y, 0));
//de laser gaat left (links)
if( up_left )
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if (distance_opening_tile < 30 )
{
touched_opening_tile = true;
}
else
{
touched_opening_tile = false;
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_right[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_right[i] = false;
}
}
if ( laser_x >= breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end > laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
else
{
//de laser gaat naar rechts
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_left[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_left[i] = false;
}
}
if ( laser_x <= -breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end < laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
}
//Log.d( " mirror ", " distance " + laser_y);
}
} | Grabot/Laser-Cube | Laser_Cube/src/com/games/Android/Laser_Cube/Objects/Laser.java | 5,839 | //de laser gaat verticaal omlaag | line_comment | nl | package com.games.Android.Laser_Cube.Objects;
import java.util.ArrayList;
import com.games.Android.Laser_Cube.Load.Vector;
public class Laser
{
private float level = 0;
private float breedte = 85;
private float hoogte = 45;
public float laser_time_opening = 0.4f;
public float laser_time_level1 = 1f;
public float Speed = 2.5f;
public Vector position = new Vector( );
public boolean Weg = false;
public boolean laser_weg = false;
//up/down or left/right
public boolean vertical = true;
//when up/down up or down, when left/right left or right, true is up for up/down and left for left/right
public boolean up_left = true;
private float laser_y = 100;
private float laser_x = 100;
private float laser_y_end = 100;
private float laser_x_end = 100;
private float length_laser = 0;
public float laser_size = 0f;
private float[] distance_cube = new float[30];
private float[] distance_mirror = new float[30];
private float[] distance_block = new float[30];
private float[] distance_radiation_tile = new float[30];
private float[] distance_colour_changer = new float[30];
private float distance_opening_tile = 100;
public boolean touched_opening_tile = false;
public boolean[] touched_radiation_tile = new boolean[30];
public boolean[] touched_block = new boolean[30];
//de 4 zijden van de mirrors
public boolean[] touched_mirror_top = new boolean[30];
public boolean[] touched_mirror_bottom = new boolean[30];
public boolean[] touched_mirror_left = new boolean[30];
public boolean[] touched_mirror_right = new boolean[30];
public boolean[] touched_colour_changer_top = new boolean[30];
public boolean[] touched_colour_changer_bottom = new boolean[30];
public boolean[] touched_colour_changer_left = new boolean[30];
public boolean[] touched_colour_changer_right = new boolean[30];
private float stroom = 0;
private int number_of_cubes = 0;
private int number_of_mirrors = 0;
private int number_of_radiation_tiles = 0;
private int number_of_blocks = 0;
private int number_of_colour_changers = 0;
public void Level( ArrayList<Cube> cubes, ArrayList<Mirror> mirrors, ArrayList<Radiation_Tile> radiation_tiles, ArrayList<Block> blocks, ArrayList<Colour_Changer> colour_changers )
{
reset_variabels();
if( mirrors == null )
{
number_of_mirrors = 0;
}
else
{
number_of_mirrors = ( mirrors.size() - 1 );
}
if( cubes == null )
{
number_of_cubes = 0;
}
else
{
number_of_cubes = ( cubes.size() - 1 );
}
if( radiation_tiles == null )
{
number_of_radiation_tiles = 0;
}
else
{
number_of_radiation_tiles = ( radiation_tiles.size() - 1 );
}
if( blocks == null )
{
number_of_blocks = 0;
}
else
{
number_of_blocks = ( blocks.size() - 1 );
}
if( colour_changers == null )
{
number_of_colour_changers = 0;
}
else
{
number_of_colour_changers = ( colour_changers.size() - 1 );
}
for( int i = 1; i <= number_of_cubes; i++ )
{
distance_cube[i] = cubes.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_mirrors; i++ )
{
distance_mirror[i] = mirrors.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_radiation_tiles; i++ )
{
distance_radiation_tile[i] = radiation_tiles.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_blocks; i++ )
{
distance_block[i] = blocks.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
for( int i = 1; i <= number_of_colour_changers; i++ )
{
distance_colour_changer[i] = colour_changers.get(i).position.distance( new Vector( laser_x, laser_y, 0 ));
}
level = 1;
}
public void Opening_Screen( ArrayList<Mirror> mirrors )
{
reset_variabels();
distance_mirror[1] = mirrors.get(1).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[2] = mirrors.get(2).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[3] = mirrors.get(3).position.distance( new Vector( laser_x, laser_y, 0));
distance_mirror[4] = mirrors.get(4).position.distance( new Vector( laser_x, laser_y, 0));
level = 8008;
}
private void reset_variabels()
{
for( int k = 0; k < 30; k++)
{
distance_mirror[k] = 100;
distance_radiation_tile[k] = 100;
distance_cube[k] = 100;
distance_block[k] = 100;
distance_colour_changer[k] = 100;
}
}
public void direction (boolean vertical, boolean up_left)
{
this.vertical = vertical;
this.up_left = up_left;
}
public void update()
{
//de laser gaat verticaal
if( vertical )
{
laser_y = (position.y + (laser_size + laser_size));
laser_y_end = ( position.y + laser_size );
laser_x = position.x;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x, laser_y_end, 0));
//de laser gaat verticaal omhoog
if ( up_left )
{
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_bottom[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_bottom[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_bottom[i] = false;
}
}
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if ( laser_y >= hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( laser_y_end > laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//de laser<SUF>
else
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_top[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_top[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_top[i] = false;
}
}
if ( laser_y <= -hoogte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( laser_y_end < laser_y )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.y -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
}
//Log.d( " mirror ", " distance " + laser_y );
}
else
{
laser_x = (position.x + (laser_size + laser_size));
laser_x_end = ( position.x + laser_size );
laser_y = position.y;
length_laser = new Vector( laser_x, laser_y, 0).distance(new Vector(laser_x_end, laser_y, 0));
//de laser gaat left (links)
if( up_left )
{
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
if (distance_opening_tile < 30 )
{
touched_opening_tile = true;
}
else
{
touched_opening_tile = false;
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_right[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_right[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_right[i] = false;
}
}
if ( laser_x >= breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size += (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x += (2f * Speed);
laser_size -= (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end > laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
else
{
//de laser gaat naar rechts
for( int i = 0; i < distance_block.length; i++ )
{
if( distance_block[i] < 3 )
{
touched_block[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_cube.length; i++)
{
if( distance_cube[i] < 3 )
{
if(length_laser > 5)
{
Weg = true;
}
}
}
for( int i = 1; i < distance_mirror.length; i++)
{
if( distance_mirror[i] < 3)
{
touched_mirror_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_mirror_left[i] = false;
}
}
for( int i = 0; i < distance_radiation_tile.length; i++ )
{
if( distance_radiation_tile[i] < 3 )
{
touched_radiation_tile[i] = true;
}
}
for( int i = 1; i < distance_colour_changer.length; i++)
{
if( distance_colour_changer[i] < 3)
{
touched_colour_changer_left[i] = true;
if(length_laser > 5)
{
Weg = true;
}
}
else
{
touched_colour_changer_left[i] = false;
}
}
if ( laser_x <= -breedte)
{
Weg = true;
}
else
{
}
if ( Weg )
{
}
else
{
laser_size -= (1f * Speed);
}
if ( level == 8008 )
{
if( stroom > laser_time_opening )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
else
{
if( stroom > laser_time_level1 )
{
position.x -= (2f * Speed);
laser_size += (1f * Speed);
}
else
{
stroom += 0.01f;
}
}
if ( laser_x_end < laser_x )
{
laser_weg = true;
}
else
{
laser_weg = false;
}
}
}
//Log.d( " mirror ", " distance " + laser_y);
}
} |
179778_7 | package com.Android.games.Music_Drop.PlayScreen;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;
import com.Android.games.Music_Drop.Load.Spectrum_Analyzer;
import com.Android.games.Music_Drop.Load.Vector;
import com.Android.games.Music_Drop.Objects.ScoreBall;
import com.badlogic.gdx.Gdx;
public class Simulation
{
private float emma_bass = 0; //de huidige waarde van de bass_range
private float watson_bass = 0; //de vorige waarde van de bass_range
private float emma_watson_bass = 0; //totale waarde van het liedje tot nu toe in bass
private float emma_stone_bass = 0; //gemiddelde waarde van het liedje tot nu toe in bass
private float emma_total = 0;
private float emma_mid = 0; //de huidige waarde van de mid_range
private float watson_mid = 0; //de vorige waarde van de mid_range
private float emma_watson_mid = 0;//totale waarde van het liedje tot nu toe in mid
private float emma_stone_mid = 0; //gemiddelde waarde van het liedje tot nu toe in mid
private float watson_total = 0;
private float width = 0;
private float height = 0;
private float touchX = 0;
private float touchY = 0;
private float bass_range = 0;
private float mid_range = 0;
private float button_distance;
private boolean touched_down = false;
private boolean back_pressed = false;
private float touch_distance_x = 0;
private float touch_distance_y = 0;
private int section = 0;
public static final String LOG = Simulation.class.getSimpleName();
private PlayScreen game;
private int seconds = 0;
public ArrayList<ScoreBall> red_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> yellow_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> blue_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> green_scoreballs = new ArrayList<ScoreBall>( );
ScoreBall scoreball;
private Spectrum_Analyzer spectrum;
Random ran = new Random();
private int point;
private int game_score = 0;
private double total_score = 0.0;
private float song_length = 0;
private float elapsed_time = 0;
private double multiplier_bonus = 1;
private DecimalFormat oneDigit;
private boolean game_ended = false;
private boolean pause = false;
private boolean paused_touched = false;
private boolean continue_touched = false;
private boolean exit_touched = false;
private boolean just_pressed = false;
public Simulation( PlayScreen game, Spectrum_Analyzer spectrum )
{
this.game = game;
this.spectrum = spectrum;
populate( );
}
public void populate( )
{
oneDigit = new DecimalFormat("#,##0.0");//format to 1 decimal place
song_length = spectrum.get_song_length();
Gdx.app.log( Simulation.LOG, "Game Started" );
}
public void variables( float touchX, float touchY, float width, float height, boolean touched_down, boolean back_pressed )
{
this.width = width;
this.height = height;
this.touchX = touchX;
this.touchY = touchY;
this.touched_down = touched_down;
this.back_pressed = back_pressed;
}
public void update( float delta )
{
spectrum.set_pause( pause );
if( pause )
{
check_pause();
}
else
{
bass_range = spectrum.get_Bass_Spectrum();
mid_range = spectrum.get_Mid_Spectrum();
check_spectrum();
UpdateScoreBalls_Green();
UpdateScoreBalls_Red();
UpdateScoreBalls_Yellow();
UpdateScoreBalls_Blue();
UpdateSongLength( delta );
check_next_level();
}
check_touch();
}
private void check_pause()
{
if((( touch_distance_x > -75 ) && ( touch_distance_x < 75 )) && (( touch_distance_y > 50 ) && ( touch_distance_y < 100 )))
{
continue_touched = true;
}
else
{
continue_touched = false;
}
if( !touched_down && continue_touched )
{
pause = false;
}
if((( touch_distance_x > -75 ) && ( touch_distance_x < 75 )) && (( touch_distance_y > -50 ) && ( touch_distance_y < 0 )))
{
exit_touched = true;
}
else
{
exit_touched = false;
}
if( !touched_down && exit_touched )
{
spectrum.stop_playing();
game.Game_Finished( 2, "0.0", 0.0 );
}
if( back_pressed )
{
pause = false;
}
}
private void UpdateSongLength( float delta )
{
elapsed_time += delta;
if( elapsed_time > song_length )
{
elapsed_time -= delta;
game_ended = true;
}
else
{
}
}
private void check_spectrum()
{
if( seconds == 0 )
{
Check_Bass_Peaks();
Check_Mid_Peaks();
Check_Bonus_Peaks();
seconds ++;
point++;
}
else if( seconds > 0 )
{
seconds = 0;
}
else
{
seconds++;
}
}
private void Check_Bonus_Peaks()
{
emma_total = bass_range + mid_range;
if( green_scoreballs.size() > 2 )
{
}
else
{
if(( emma_total - watson_total ) > 4000 )
{
Add_Green_ScoreBall(( emma_total - watson_total) );
Add_Red_ScoreBall(( emma_total - watson_total ));
}
else
{
}
}
}
private void Check_Bass_Peaks()
{
emma_bass = bass_range;
if( (emma_bass - watson_bass) > 200 )
{
Add_Blue_ScoreBall(( emma_bass - watson_bass ));
}
else
{
}
watson_bass = emma_bass;
emma_watson_bass += emma_bass;
emma_stone_bass = (emma_watson_bass/point);
}
private void Check_Mid_Peaks()
{
emma_mid = mid_range;
if( ( emma_mid - watson_mid) > 200 )
{
Add_Blue_ScoreBall(( emma_mid - watson_mid ));
}
watson_mid = emma_mid;
emma_watson_mid += emma_mid;
emma_stone_mid = (emma_watson_mid/point);
}
private void Add_Blue_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/800);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt( 480 ) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
blue_scoreballs.add( scoreball );
}
}
private void Add_Red_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/4000);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
red_scoreballs.add( scoreball );
}
}
private void Add_Yellow_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/500);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
yellow_scoreballs.add( scoreball );
}
}
private void Add_Green_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/4000);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
green_scoreballs.add( scoreball );
}
}
private void check_next_level()
{
if( back_pressed )
{
pause = true;
}
if(( touch_distance_x < -200 ) && ( touch_distance_y < -360 ))
{
paused_touched = true;
}
else
{
}
if( !touched_down && paused_touched )
{
paused_touched = false;
pause = true;
}
if( game_ended )
{
game.Game_Finished( 4, oneDigit.format(total_score), total_score );
}
}
ArrayList<ScoreBall> scoreball_green_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Green()
{
scoreball_green_weg.clear();
for( int i = 0; i < green_scoreballs.size(); i++ )
{
ScoreBall scoreball = green_scoreballs.get(i);
scoreball.update();
Check_BonusBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_green_weg.add(scoreball);
}
for( int k = 0; k < scoreball_green_weg.size(); k++ )
{
green_scoreballs.remove( scoreball_green_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_yellow_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Yellow()
{
scoreball_yellow_weg.clear();
for( int i = 0; i < yellow_scoreballs.size(); i++ )
{
ScoreBall scoreball = yellow_scoreballs.get(i);
scoreball.update();
Check_ScoreBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_yellow_weg.add(scoreball);
}
for( int k = 0; k < scoreball_yellow_weg.size(); k++ )
{
yellow_scoreballs.remove( scoreball_yellow_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_red_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Red()
{
scoreball_red_weg.clear();
for( int i = 0; i < red_scoreballs.size(); i++ )
{
ScoreBall scoreball = red_scoreballs.get(i);
scoreball.update();
Check_DeBonusBall_Collision( scoreball );
if( scoreball.scoreball_weg )
{
scoreball_red_weg.add(scoreball);
}
for( int k = 0; k < scoreball_red_weg.size(); k++ )
{
red_scoreballs.remove( scoreball_red_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_blue_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Blue()
{
scoreball_blue_weg.clear();
for( int i = 0; i < blue_scoreballs.size(); i++ )
{
ScoreBall scoreball = blue_scoreballs.get(i);
scoreball.update();
Check_ScoreBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_blue_weg.add(scoreball);
}
for( int k = 0; k < scoreball_blue_weg.size(); k++ )
{
blue_scoreballs.remove( scoreball_blue_weg.get(k) );
}
}
}
private void Check_DeBonusBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
multiplier_bonus -= 0.2;
check_scoreball.scoreball_gone();
}
}
private void Check_BonusBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
multiplier_bonus += 0.1;
check_scoreball.scoreball_gone();
}
}
private void Check_ScoreBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
game_score += (1 * multiplier_bonus);
total_score += (1 * multiplier_bonus);
check_scoreball.scoreball_gone();
}
}
private void check_touch()
{
touch_distance_x = new Vector ( width/2, height/2 ).distance( new Vector ( touchX, (height/2)));
touch_distance_y = new Vector ( width/2, height/2 ).distance( new Vector ( (width/2), touchY));
if (( touchX > ( width / 2) ) && ( touchY > ( height/2 )))
{
section = 4;
touch_distance_x = (touch_distance_x / (width / (float)480));
if( touch_distance_y > 0)
{
touch_distance_y = ((touch_distance_y * -1) / (height / (float)800));
}
}
else if (( touchX > ( width / 2 )) && ( touchY < ( height / 2 )))
{
section = 2;
touch_distance_x = (touch_distance_x / (width / (float)480));
touch_distance_y = (touch_distance_y / (height / (float)800));
}
else if (( touchX < ( width / 2 )) && ( touchY > ( height / 2 )))
{
section = 3;
if( touch_distance_x > 0 )
{
touch_distance_x = ((touch_distance_x * -1) / (width / (float)480));
}
if( touch_distance_y > 0)
{
touch_distance_y = ((touch_distance_y * -1) / (height / (float)800));
}
}
else if (( touchX < ( width / 2 )) && ( touchY < ( height / 2 )))
{
section = 1;
if( touch_distance_x > 0 )
{
touch_distance_x = ((touch_distance_x * -1) / (width / (float)480));
}
touch_distance_y = (touch_distance_y / (height / (float)800));
}
else
{
section = 0;
}
}
public float get_elapsed_time()
{
return elapsed_time;
}
public int getScore()
{
return game_score;
}
public double getTotalScore()
{
return total_score;
}
public String Score()
{
return oneDigit.format(total_score);
}
public String multipier()
{
return oneDigit.format(multiplier_bonus);
}
public boolean pause()
{
return pause;
}
}
| Grabot/Music-Drop | Music_Drop/src/com/Android/games/Music_Drop/PlayScreen/Simulation.java | 5,334 | //gemiddelde waarde van het liedje tot nu toe in mid | line_comment | nl | package com.Android.games.Music_Drop.PlayScreen;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;
import com.Android.games.Music_Drop.Load.Spectrum_Analyzer;
import com.Android.games.Music_Drop.Load.Vector;
import com.Android.games.Music_Drop.Objects.ScoreBall;
import com.badlogic.gdx.Gdx;
public class Simulation
{
private float emma_bass = 0; //de huidige waarde van de bass_range
private float watson_bass = 0; //de vorige waarde van de bass_range
private float emma_watson_bass = 0; //totale waarde van het liedje tot nu toe in bass
private float emma_stone_bass = 0; //gemiddelde waarde van het liedje tot nu toe in bass
private float emma_total = 0;
private float emma_mid = 0; //de huidige waarde van de mid_range
private float watson_mid = 0; //de vorige waarde van de mid_range
private float emma_watson_mid = 0;//totale waarde van het liedje tot nu toe in mid
private float emma_stone_mid = 0; //gemiddelde waarde<SUF>
private float watson_total = 0;
private float width = 0;
private float height = 0;
private float touchX = 0;
private float touchY = 0;
private float bass_range = 0;
private float mid_range = 0;
private float button_distance;
private boolean touched_down = false;
private boolean back_pressed = false;
private float touch_distance_x = 0;
private float touch_distance_y = 0;
private int section = 0;
public static final String LOG = Simulation.class.getSimpleName();
private PlayScreen game;
private int seconds = 0;
public ArrayList<ScoreBall> red_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> yellow_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> blue_scoreballs = new ArrayList<ScoreBall>( );
public ArrayList<ScoreBall> green_scoreballs = new ArrayList<ScoreBall>( );
ScoreBall scoreball;
private Spectrum_Analyzer spectrum;
Random ran = new Random();
private int point;
private int game_score = 0;
private double total_score = 0.0;
private float song_length = 0;
private float elapsed_time = 0;
private double multiplier_bonus = 1;
private DecimalFormat oneDigit;
private boolean game_ended = false;
private boolean pause = false;
private boolean paused_touched = false;
private boolean continue_touched = false;
private boolean exit_touched = false;
private boolean just_pressed = false;
public Simulation( PlayScreen game, Spectrum_Analyzer spectrum )
{
this.game = game;
this.spectrum = spectrum;
populate( );
}
public void populate( )
{
oneDigit = new DecimalFormat("#,##0.0");//format to 1 decimal place
song_length = spectrum.get_song_length();
Gdx.app.log( Simulation.LOG, "Game Started" );
}
public void variables( float touchX, float touchY, float width, float height, boolean touched_down, boolean back_pressed )
{
this.width = width;
this.height = height;
this.touchX = touchX;
this.touchY = touchY;
this.touched_down = touched_down;
this.back_pressed = back_pressed;
}
public void update( float delta )
{
spectrum.set_pause( pause );
if( pause )
{
check_pause();
}
else
{
bass_range = spectrum.get_Bass_Spectrum();
mid_range = spectrum.get_Mid_Spectrum();
check_spectrum();
UpdateScoreBalls_Green();
UpdateScoreBalls_Red();
UpdateScoreBalls_Yellow();
UpdateScoreBalls_Blue();
UpdateSongLength( delta );
check_next_level();
}
check_touch();
}
private void check_pause()
{
if((( touch_distance_x > -75 ) && ( touch_distance_x < 75 )) && (( touch_distance_y > 50 ) && ( touch_distance_y < 100 )))
{
continue_touched = true;
}
else
{
continue_touched = false;
}
if( !touched_down && continue_touched )
{
pause = false;
}
if((( touch_distance_x > -75 ) && ( touch_distance_x < 75 )) && (( touch_distance_y > -50 ) && ( touch_distance_y < 0 )))
{
exit_touched = true;
}
else
{
exit_touched = false;
}
if( !touched_down && exit_touched )
{
spectrum.stop_playing();
game.Game_Finished( 2, "0.0", 0.0 );
}
if( back_pressed )
{
pause = false;
}
}
private void UpdateSongLength( float delta )
{
elapsed_time += delta;
if( elapsed_time > song_length )
{
elapsed_time -= delta;
game_ended = true;
}
else
{
}
}
private void check_spectrum()
{
if( seconds == 0 )
{
Check_Bass_Peaks();
Check_Mid_Peaks();
Check_Bonus_Peaks();
seconds ++;
point++;
}
else if( seconds > 0 )
{
seconds = 0;
}
else
{
seconds++;
}
}
private void Check_Bonus_Peaks()
{
emma_total = bass_range + mid_range;
if( green_scoreballs.size() > 2 )
{
}
else
{
if(( emma_total - watson_total ) > 4000 )
{
Add_Green_ScoreBall(( emma_total - watson_total) );
Add_Red_ScoreBall(( emma_total - watson_total ));
}
else
{
}
}
}
private void Check_Bass_Peaks()
{
emma_bass = bass_range;
if( (emma_bass - watson_bass) > 200 )
{
Add_Blue_ScoreBall(( emma_bass - watson_bass ));
}
else
{
}
watson_bass = emma_bass;
emma_watson_bass += emma_bass;
emma_stone_bass = (emma_watson_bass/point);
}
private void Check_Mid_Peaks()
{
emma_mid = mid_range;
if( ( emma_mid - watson_mid) > 200 )
{
Add_Blue_ScoreBall(( emma_mid - watson_mid ));
}
watson_mid = emma_mid;
emma_watson_mid += emma_mid;
emma_stone_mid = (emma_watson_mid/point);
}
private void Add_Blue_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/800);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt( 480 ) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
blue_scoreballs.add( scoreball );
}
}
private void Add_Red_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/4000);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
red_scoreballs.add( scoreball );
}
}
private void Add_Yellow_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/500);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
yellow_scoreballs.add( scoreball );
}
}
private void Add_Green_ScoreBall( float spectrum_rize )
{
int number_of_balls = (int)(spectrum_rize/4000);
for( int i = 0; i < number_of_balls; i++ )
{
scoreball = new ScoreBall();
scoreball.position.set( ( ran.nextInt(480) - 240 ), 400 );
scoreball.set_rotation( ran.nextInt( 360 ), ((ran.nextFloat()*8)-4) );
scoreball.set_speed( 7 );
scoreball.set_deceleration( (float)0.03 );
green_scoreballs.add( scoreball );
}
}
private void check_next_level()
{
if( back_pressed )
{
pause = true;
}
if(( touch_distance_x < -200 ) && ( touch_distance_y < -360 ))
{
paused_touched = true;
}
else
{
}
if( !touched_down && paused_touched )
{
paused_touched = false;
pause = true;
}
if( game_ended )
{
game.Game_Finished( 4, oneDigit.format(total_score), total_score );
}
}
ArrayList<ScoreBall> scoreball_green_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Green()
{
scoreball_green_weg.clear();
for( int i = 0; i < green_scoreballs.size(); i++ )
{
ScoreBall scoreball = green_scoreballs.get(i);
scoreball.update();
Check_BonusBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_green_weg.add(scoreball);
}
for( int k = 0; k < scoreball_green_weg.size(); k++ )
{
green_scoreballs.remove( scoreball_green_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_yellow_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Yellow()
{
scoreball_yellow_weg.clear();
for( int i = 0; i < yellow_scoreballs.size(); i++ )
{
ScoreBall scoreball = yellow_scoreballs.get(i);
scoreball.update();
Check_ScoreBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_yellow_weg.add(scoreball);
}
for( int k = 0; k < scoreball_yellow_weg.size(); k++ )
{
yellow_scoreballs.remove( scoreball_yellow_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_red_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Red()
{
scoreball_red_weg.clear();
for( int i = 0; i < red_scoreballs.size(); i++ )
{
ScoreBall scoreball = red_scoreballs.get(i);
scoreball.update();
Check_DeBonusBall_Collision( scoreball );
if( scoreball.scoreball_weg )
{
scoreball_red_weg.add(scoreball);
}
for( int k = 0; k < scoreball_red_weg.size(); k++ )
{
red_scoreballs.remove( scoreball_red_weg.get(k) );
}
}
}
ArrayList<ScoreBall> scoreball_blue_weg = new ArrayList<ScoreBall>();
private void UpdateScoreBalls_Blue()
{
scoreball_blue_weg.clear();
for( int i = 0; i < blue_scoreballs.size(); i++ )
{
ScoreBall scoreball = blue_scoreballs.get(i);
scoreball.update();
Check_ScoreBall_Collision(scoreball);
if( scoreball.scoreball_weg )
{
scoreball_blue_weg.add(scoreball);
}
for( int k = 0; k < scoreball_blue_weg.size(); k++ )
{
blue_scoreballs.remove( scoreball_blue_weg.get(k) );
}
}
}
private void Check_DeBonusBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
multiplier_bonus -= 0.2;
check_scoreball.scoreball_gone();
}
}
private void Check_BonusBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
multiplier_bonus += 0.1;
check_scoreball.scoreball_gone();
}
}
private void Check_ScoreBall_Collision( ScoreBall check_scoreball )
{
float scoreball_distance = check_scoreball.position.distance( new Vector( touch_distance_x, touch_distance_y ));
if( scoreball_distance < 50 )
{
game_score += (1 * multiplier_bonus);
total_score += (1 * multiplier_bonus);
check_scoreball.scoreball_gone();
}
}
private void check_touch()
{
touch_distance_x = new Vector ( width/2, height/2 ).distance( new Vector ( touchX, (height/2)));
touch_distance_y = new Vector ( width/2, height/2 ).distance( new Vector ( (width/2), touchY));
if (( touchX > ( width / 2) ) && ( touchY > ( height/2 )))
{
section = 4;
touch_distance_x = (touch_distance_x / (width / (float)480));
if( touch_distance_y > 0)
{
touch_distance_y = ((touch_distance_y * -1) / (height / (float)800));
}
}
else if (( touchX > ( width / 2 )) && ( touchY < ( height / 2 )))
{
section = 2;
touch_distance_x = (touch_distance_x / (width / (float)480));
touch_distance_y = (touch_distance_y / (height / (float)800));
}
else if (( touchX < ( width / 2 )) && ( touchY > ( height / 2 )))
{
section = 3;
if( touch_distance_x > 0 )
{
touch_distance_x = ((touch_distance_x * -1) / (width / (float)480));
}
if( touch_distance_y > 0)
{
touch_distance_y = ((touch_distance_y * -1) / (height / (float)800));
}
}
else if (( touchX < ( width / 2 )) && ( touchY < ( height / 2 )))
{
section = 1;
if( touch_distance_x > 0 )
{
touch_distance_x = ((touch_distance_x * -1) / (width / (float)480));
}
touch_distance_y = (touch_distance_y / (height / (float)800));
}
else
{
section = 0;
}
}
public float get_elapsed_time()
{
return elapsed_time;
}
public int getScore()
{
return game_score;
}
public double getTotalScore()
{
return total_score;
}
public String Score()
{
return oneDigit.format(total_score);
}
public String multipier()
{
return oneDigit.format(multiplier_bonus);
}
public boolean pause()
{
return pause;
}
}
|
63706_17 | package emu.grasscutter.game.entity;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.*;
import emu.grasscutter.game.ability.*;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.*;
import emu.grasscutter.game.world.*;
import emu.grasscutter.net.proto.FightPropPairOuterClass.FightPropPair;
import emu.grasscutter.net.proto.GadgetInteractReqOuterClass.GadgetInteractReq;
import emu.grasscutter.net.proto.MotionInfoOuterClass.MotionInfo;
import emu.grasscutter.net.proto.MotionStateOuterClass.MotionState;
import emu.grasscutter.net.proto.SceneEntityInfoOuterClass.SceneEntityInfo;
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
import emu.grasscutter.scripts.data.controller.EntityController;
import emu.grasscutter.server.event.entity.*;
import emu.grasscutter.server.packet.send.PacketEntityFightPropUpdateNotify;
import it.unimi.dsi.fastutil.ints.*;
import java.util.*;
import lombok.*;
public abstract class GameEntity {
@Getter private final Scene scene;
@Getter protected int id;
@Getter @Setter private SpawnDataEntry spawnEntry;
@Getter @Setter private int blockId;
@Getter @Setter private int configId;
@Getter @Setter private int groupId;
@Getter @Setter private MotionState motionState;
@Getter @Setter private int lastMoveSceneTimeMs;
@Getter @Setter private int lastMoveReliableSeq;
@Getter @Setter private boolean lockHP;
private boolean limbo;
private float limboHpThreshold;
@Setter(AccessLevel.PROTECTED)
@Getter
private boolean isDead = false;
// Lua controller for specific actions
@Getter @Setter private EntityController entityController;
@Getter private ElementType lastAttackType = ElementType.None;
@Getter private List<Ability> instancedAbilities = new ArrayList<>();
@Getter
private Int2ObjectMap<AbilityModifierController> instancedModifiers =
new Int2ObjectOpenHashMap<>();
@Getter private Map<String, Float> globalAbilityValues = new HashMap<>();
public GameEntity(Scene scene) {
this.scene = scene;
this.motionState = MotionState.MOTION_STATE_NONE;
}
public abstract void initAbilities();
public EntityType getEntityType() {
return EntityIdType.toEntityType(this.getId() >> 24);
}
public abstract int getEntityTypeId();
public World getWorld() {
return this.getScene().getWorld();
}
public boolean isAlive() {
return !this.isDead;
}
public LifeState getLifeState() {
return this.isAlive() ? LifeState.LIFE_ALIVE : LifeState.LIFE_DEAD;
}
public abstract Int2FloatMap getFightProperties();
public abstract Position getPosition();
public abstract Position getRotation();
public void setFightProperty(FightProperty prop, float value) {
this.getFightProperties().put(prop.getId(), value);
}
public void setFightProperty(int id, float value) {
this.getFightProperties().put(id, value);
}
public void addFightProperty(FightProperty prop, float value) {
this.getFightProperties().put(prop.getId(), this.getFightProperty(prop) + value);
}
public float getFightProperty(FightProperty prop) {
return this.getFightProperties().getOrDefault(prop.getId(), 0f);
}
public boolean hasFightProperty(FightProperty prop) {
return this.getFightProperties().containsKey(prop.getId());
}
public void addAllFightPropsToEntityInfo(SceneEntityInfo.Builder entityInfo) {
this.getFightProperties()
.forEach(
(key, value) -> {
if (key == 0) return;
entityInfo.addFightPropList(
FightPropPair.newBuilder().setPropType(key).setPropValue(value).build());
});
}
protected void setLimbo(float hpThreshold) {
limbo = true;
limboHpThreshold = hpThreshold;
}
public void onAddAbilityModifier(AbilityModifier data) {
// Set limbo state (invulnerability at a certain HP threshold)
// if ability modifier calls for it
if (data.state == AbilityModifier.State.Limbo
&& data.properties != null
&& data.properties.Actor_HpThresholdRatio > .0f) {
this.setLimbo(data.properties.Actor_HpThresholdRatio);
}
}
protected MotionInfo getMotionInfo() {
return MotionInfo.newBuilder()
.setPos(this.getPosition().toProto())
.setRot(this.getRotation().toProto())
.setSpeed(Vector.newBuilder())
.setState(this.getMotionState())
.build();
}
public float heal(float amount) {
return heal(amount, false);
}
public float heal(float amount, boolean mute) {
if (this.getFightProperties() == null) {
return 0f;
}
float curHp = this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP);
float maxHp = this.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
if (curHp >= maxHp) {
return 0f;
}
float healed = Math.min(maxHp - curHp, amount);
this.addFightProperty(FightProperty.FIGHT_PROP_CUR_HP, healed);
this.getScene()
.broadcastPacket(
new PacketEntityFightPropUpdateNotify(this, FightProperty.FIGHT_PROP_CUR_HP));
return healed;
}
public void damage(float amount) {
this.damage(amount, 0, ElementType.None);
}
public void damage(float amount, ElementType attackType) {
this.damage(amount, 0, attackType);
}
public void damage(float amount, int killerId, ElementType attackType) {
// Check if the entity has properties.
if (this.getFightProperties() == null || !hasFightProperty(FightProperty.FIGHT_PROP_CUR_HP)) {
return;
}
// Invoke entity damage event.
EntityDamageEvent event =
new EntityDamageEvent(this, amount, attackType, this.getScene().getEntityById(killerId));
event.call();
if (event.isCanceled()) {
return; // If the event is canceled, do not damage the entity.
}
float effectiveDamage = 0;
float curHp = getFightProperty(FightProperty.FIGHT_PROP_CUR_HP);
if (limbo) {
float maxHp = getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
float curRatio = curHp / maxHp;
if (curRatio > limboHpThreshold) {
// OK if this hit takes HP below threshold.
effectiveDamage = event.getDamage();
}
if (effectiveDamage >= curHp && limboHpThreshold > .0f) {
// Don't let entity die while in limbo.
effectiveDamage = curHp - 1;
}
} else if (curHp != Float.POSITIVE_INFINITY && !lockHP
|| lockHP && curHp <= event.getDamage()) {
effectiveDamage = event.getDamage();
}
// Add negative HP to the current HP property.
this.addFightProperty(FightProperty.FIGHT_PROP_CUR_HP, -effectiveDamage);
this.lastAttackType = attackType;
this.checkIfDead();
this.runLuaCallbacks(event);
// Packets
this.getScene()
.broadcastPacket(
new PacketEntityFightPropUpdateNotify(this, FightProperty.FIGHT_PROP_CUR_HP));
// Check if dead.
if (this.isDead) {
this.getScene().killEntity(this, killerId);
}
}
public void checkIfDead() {
if (this.getFightProperties() == null || !hasFightProperty(FightProperty.FIGHT_PROP_CUR_HP)) {
return;
}
if (this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP) <= 0f) {
this.setFightProperty(FightProperty.FIGHT_PROP_CUR_HP, 0f);
this.isDead = true;
}
}
/**
* Runs the Lua callbacks for {@link EntityDamageEvent}.
*
* @param event The damage event.
*/
public void runLuaCallbacks(EntityDamageEvent event) {
if (entityController != null) {
entityController.onBeHurt(this, event.getAttackElementType(), true); // todo is host handling
}
}
/**
* Move this entity to a new position.
*
* @param position The new position.
* @param rotation The new rotation.
*/
public void move(Position position, Position rotation) {
// Set the position and rotation.
this.getPosition().set(position);
this.getRotation().set(rotation);
}
/**
* Called when a player interacts with this entity
*
* @param player Player that is interacting with this entity
* @param interactReq Interact request protobuf data
*/
public void onInteract(Player player, GadgetInteractReq interactReq) {}
/** Called when this entity is added to the world */
public void onCreate() {}
public void onRemoved() {}
private int[] parseCountRange(String range) {
var split = range.split(";");
if (split.length == 1)
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[0])};
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1])};
}
public boolean dropSubfieldItem(int dropId) {
var drop = GameData.getDropSubfieldMappingMap().get(dropId);
if (drop == null) return false;
var dropTableEntry = GameData.getDropTableExcelConfigDataMap().get(drop.getItemId());
if (dropTableEntry == null) return false;
Int2ObjectMap<Integer> itemsToDrop = new Int2ObjectOpenHashMap<>();
switch (dropTableEntry.getRandomType()) {
case 0: // select one
{
int weightCount = 0;
for (var entry : dropTableEntry.getDropVec()) weightCount += entry.getWeight();
int randomValue = new Random().nextInt(weightCount);
weightCount = 0;
for (var entry : dropTableEntry.getDropVec()) {
if (randomValue >= weightCount && randomValue < (weightCount + entry.getWeight())) {
var countRange = parseCountRange(entry.getCountRange());
itemsToDrop.put(
entry.getItemId(),
Integer.valueOf((new Random().nextBoolean() ? countRange[0] : countRange[1])));
}
}
}
break;
case 1: // Select various
{
for (var entry : dropTableEntry.getDropVec()) {
if (entry.getWeight() < new Random().nextInt(10000)) {
var countRange = parseCountRange(entry.getCountRange());
itemsToDrop.put(
entry.getItemId(),
Integer.valueOf((new Random().nextBoolean() ? countRange[0] : countRange[1])));
}
}
}
break;
}
for (var entry : itemsToDrop.int2ObjectEntrySet()) {
var item =
new EntityItem(
scene,
null,
GameData.getItemDataMap().get(entry.getIntKey()),
getPosition().nearby2d(1f).addY(0.5f),
entry.getValue(),
true);
scene.addEntity(item);
}
return true;
}
public boolean dropSubfield(String subfieldName) {
var subfieldMapping = GameData.getSubfieldMappingMap().get(getEntityTypeId());
if (subfieldMapping == null || subfieldMapping.getSubfields() == null) return false;
for (var entry : subfieldMapping.getSubfields()) {
if (entry.getSubfieldName().compareTo(subfieldName) == 0) {
return dropSubfieldItem(entry.getDrop_id());
}
}
return false;
}
public void onTick(int sceneTime) {
if (entityController != null) {
entityController.onTimer(this, sceneTime);
}
}
public int onClientExecuteRequest(int param1, int param2, int param3) {
if (entityController != null) {
return entityController.onClientExecuteRequest(this, param1, param2, param3);
}
return 0;
}
/**
* Called when this entity dies
*
* @param killerId Entity id of the entity that killed this entity
*/
public void onDeath(int killerId) {
// Invoke entity death event.
EntityDeathEvent event = new EntityDeathEvent(this, killerId);
event.call();
// Run Lua callbacks.
if (entityController != null) {
entityController.onDie(this, getLastAttackType());
}
this.isDead = true;
}
/** Invoked when a global ability value is updated. */
public void onAbilityValueUpdate() {
// Does nothing.
}
public abstract SceneEntityInfo toProto();
@Override
public String toString() {
return "Entity ID: %s; Group ID: %s; Config ID: %s"
.formatted(this.getId(), this.getGroupId(), this.getConfigId());
}
}
| Grasscutters/Grasscutter | src/main/java/emu/grasscutter/game/entity/GameEntity.java | 3,837 | // Invoke entity death event. | line_comment | nl | package emu.grasscutter.game.entity;
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.binout.*;
import emu.grasscutter.game.ability.*;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.props.*;
import emu.grasscutter.game.world.*;
import emu.grasscutter.net.proto.FightPropPairOuterClass.FightPropPair;
import emu.grasscutter.net.proto.GadgetInteractReqOuterClass.GadgetInteractReq;
import emu.grasscutter.net.proto.MotionInfoOuterClass.MotionInfo;
import emu.grasscutter.net.proto.MotionStateOuterClass.MotionState;
import emu.grasscutter.net.proto.SceneEntityInfoOuterClass.SceneEntityInfo;
import emu.grasscutter.net.proto.VectorOuterClass.Vector;
import emu.grasscutter.scripts.data.controller.EntityController;
import emu.grasscutter.server.event.entity.*;
import emu.grasscutter.server.packet.send.PacketEntityFightPropUpdateNotify;
import it.unimi.dsi.fastutil.ints.*;
import java.util.*;
import lombok.*;
public abstract class GameEntity {
@Getter private final Scene scene;
@Getter protected int id;
@Getter @Setter private SpawnDataEntry spawnEntry;
@Getter @Setter private int blockId;
@Getter @Setter private int configId;
@Getter @Setter private int groupId;
@Getter @Setter private MotionState motionState;
@Getter @Setter private int lastMoveSceneTimeMs;
@Getter @Setter private int lastMoveReliableSeq;
@Getter @Setter private boolean lockHP;
private boolean limbo;
private float limboHpThreshold;
@Setter(AccessLevel.PROTECTED)
@Getter
private boolean isDead = false;
// Lua controller for specific actions
@Getter @Setter private EntityController entityController;
@Getter private ElementType lastAttackType = ElementType.None;
@Getter private List<Ability> instancedAbilities = new ArrayList<>();
@Getter
private Int2ObjectMap<AbilityModifierController> instancedModifiers =
new Int2ObjectOpenHashMap<>();
@Getter private Map<String, Float> globalAbilityValues = new HashMap<>();
public GameEntity(Scene scene) {
this.scene = scene;
this.motionState = MotionState.MOTION_STATE_NONE;
}
public abstract void initAbilities();
public EntityType getEntityType() {
return EntityIdType.toEntityType(this.getId() >> 24);
}
public abstract int getEntityTypeId();
public World getWorld() {
return this.getScene().getWorld();
}
public boolean isAlive() {
return !this.isDead;
}
public LifeState getLifeState() {
return this.isAlive() ? LifeState.LIFE_ALIVE : LifeState.LIFE_DEAD;
}
public abstract Int2FloatMap getFightProperties();
public abstract Position getPosition();
public abstract Position getRotation();
public void setFightProperty(FightProperty prop, float value) {
this.getFightProperties().put(prop.getId(), value);
}
public void setFightProperty(int id, float value) {
this.getFightProperties().put(id, value);
}
public void addFightProperty(FightProperty prop, float value) {
this.getFightProperties().put(prop.getId(), this.getFightProperty(prop) + value);
}
public float getFightProperty(FightProperty prop) {
return this.getFightProperties().getOrDefault(prop.getId(), 0f);
}
public boolean hasFightProperty(FightProperty prop) {
return this.getFightProperties().containsKey(prop.getId());
}
public void addAllFightPropsToEntityInfo(SceneEntityInfo.Builder entityInfo) {
this.getFightProperties()
.forEach(
(key, value) -> {
if (key == 0) return;
entityInfo.addFightPropList(
FightPropPair.newBuilder().setPropType(key).setPropValue(value).build());
});
}
protected void setLimbo(float hpThreshold) {
limbo = true;
limboHpThreshold = hpThreshold;
}
public void onAddAbilityModifier(AbilityModifier data) {
// Set limbo state (invulnerability at a certain HP threshold)
// if ability modifier calls for it
if (data.state == AbilityModifier.State.Limbo
&& data.properties != null
&& data.properties.Actor_HpThresholdRatio > .0f) {
this.setLimbo(data.properties.Actor_HpThresholdRatio);
}
}
protected MotionInfo getMotionInfo() {
return MotionInfo.newBuilder()
.setPos(this.getPosition().toProto())
.setRot(this.getRotation().toProto())
.setSpeed(Vector.newBuilder())
.setState(this.getMotionState())
.build();
}
public float heal(float amount) {
return heal(amount, false);
}
public float heal(float amount, boolean mute) {
if (this.getFightProperties() == null) {
return 0f;
}
float curHp = this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP);
float maxHp = this.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
if (curHp >= maxHp) {
return 0f;
}
float healed = Math.min(maxHp - curHp, amount);
this.addFightProperty(FightProperty.FIGHT_PROP_CUR_HP, healed);
this.getScene()
.broadcastPacket(
new PacketEntityFightPropUpdateNotify(this, FightProperty.FIGHT_PROP_CUR_HP));
return healed;
}
public void damage(float amount) {
this.damage(amount, 0, ElementType.None);
}
public void damage(float amount, ElementType attackType) {
this.damage(amount, 0, attackType);
}
public void damage(float amount, int killerId, ElementType attackType) {
// Check if the entity has properties.
if (this.getFightProperties() == null || !hasFightProperty(FightProperty.FIGHT_PROP_CUR_HP)) {
return;
}
// Invoke entity damage event.
EntityDamageEvent event =
new EntityDamageEvent(this, amount, attackType, this.getScene().getEntityById(killerId));
event.call();
if (event.isCanceled()) {
return; // If the event is canceled, do not damage the entity.
}
float effectiveDamage = 0;
float curHp = getFightProperty(FightProperty.FIGHT_PROP_CUR_HP);
if (limbo) {
float maxHp = getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
float curRatio = curHp / maxHp;
if (curRatio > limboHpThreshold) {
// OK if this hit takes HP below threshold.
effectiveDamage = event.getDamage();
}
if (effectiveDamage >= curHp && limboHpThreshold > .0f) {
// Don't let entity die while in limbo.
effectiveDamage = curHp - 1;
}
} else if (curHp != Float.POSITIVE_INFINITY && !lockHP
|| lockHP && curHp <= event.getDamage()) {
effectiveDamage = event.getDamage();
}
// Add negative HP to the current HP property.
this.addFightProperty(FightProperty.FIGHT_PROP_CUR_HP, -effectiveDamage);
this.lastAttackType = attackType;
this.checkIfDead();
this.runLuaCallbacks(event);
// Packets
this.getScene()
.broadcastPacket(
new PacketEntityFightPropUpdateNotify(this, FightProperty.FIGHT_PROP_CUR_HP));
// Check if dead.
if (this.isDead) {
this.getScene().killEntity(this, killerId);
}
}
public void checkIfDead() {
if (this.getFightProperties() == null || !hasFightProperty(FightProperty.FIGHT_PROP_CUR_HP)) {
return;
}
if (this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP) <= 0f) {
this.setFightProperty(FightProperty.FIGHT_PROP_CUR_HP, 0f);
this.isDead = true;
}
}
/**
* Runs the Lua callbacks for {@link EntityDamageEvent}.
*
* @param event The damage event.
*/
public void runLuaCallbacks(EntityDamageEvent event) {
if (entityController != null) {
entityController.onBeHurt(this, event.getAttackElementType(), true); // todo is host handling
}
}
/**
* Move this entity to a new position.
*
* @param position The new position.
* @param rotation The new rotation.
*/
public void move(Position position, Position rotation) {
// Set the position and rotation.
this.getPosition().set(position);
this.getRotation().set(rotation);
}
/**
* Called when a player interacts with this entity
*
* @param player Player that is interacting with this entity
* @param interactReq Interact request protobuf data
*/
public void onInteract(Player player, GadgetInteractReq interactReq) {}
/** Called when this entity is added to the world */
public void onCreate() {}
public void onRemoved() {}
private int[] parseCountRange(String range) {
var split = range.split(";");
if (split.length == 1)
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[0])};
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1])};
}
public boolean dropSubfieldItem(int dropId) {
var drop = GameData.getDropSubfieldMappingMap().get(dropId);
if (drop == null) return false;
var dropTableEntry = GameData.getDropTableExcelConfigDataMap().get(drop.getItemId());
if (dropTableEntry == null) return false;
Int2ObjectMap<Integer> itemsToDrop = new Int2ObjectOpenHashMap<>();
switch (dropTableEntry.getRandomType()) {
case 0: // select one
{
int weightCount = 0;
for (var entry : dropTableEntry.getDropVec()) weightCount += entry.getWeight();
int randomValue = new Random().nextInt(weightCount);
weightCount = 0;
for (var entry : dropTableEntry.getDropVec()) {
if (randomValue >= weightCount && randomValue < (weightCount + entry.getWeight())) {
var countRange = parseCountRange(entry.getCountRange());
itemsToDrop.put(
entry.getItemId(),
Integer.valueOf((new Random().nextBoolean() ? countRange[0] : countRange[1])));
}
}
}
break;
case 1: // Select various
{
for (var entry : dropTableEntry.getDropVec()) {
if (entry.getWeight() < new Random().nextInt(10000)) {
var countRange = parseCountRange(entry.getCountRange());
itemsToDrop.put(
entry.getItemId(),
Integer.valueOf((new Random().nextBoolean() ? countRange[0] : countRange[1])));
}
}
}
break;
}
for (var entry : itemsToDrop.int2ObjectEntrySet()) {
var item =
new EntityItem(
scene,
null,
GameData.getItemDataMap().get(entry.getIntKey()),
getPosition().nearby2d(1f).addY(0.5f),
entry.getValue(),
true);
scene.addEntity(item);
}
return true;
}
public boolean dropSubfield(String subfieldName) {
var subfieldMapping = GameData.getSubfieldMappingMap().get(getEntityTypeId());
if (subfieldMapping == null || subfieldMapping.getSubfields() == null) return false;
for (var entry : subfieldMapping.getSubfields()) {
if (entry.getSubfieldName().compareTo(subfieldName) == 0) {
return dropSubfieldItem(entry.getDrop_id());
}
}
return false;
}
public void onTick(int sceneTime) {
if (entityController != null) {
entityController.onTimer(this, sceneTime);
}
}
public int onClientExecuteRequest(int param1, int param2, int param3) {
if (entityController != null) {
return entityController.onClientExecuteRequest(this, param1, param2, param3);
}
return 0;
}
/**
* Called when this entity dies
*
* @param killerId Entity id of the entity that killed this entity
*/
public void onDeath(int killerId) {
// Invoke entity<SUF>
EntityDeathEvent event = new EntityDeathEvent(this, killerId);
event.call();
// Run Lua callbacks.
if (entityController != null) {
entityController.onDie(this, getLastAttackType());
}
this.isDead = true;
}
/** Invoked when a global ability value is updated. */
public void onAbilityValueUpdate() {
// Does nothing.
}
public abstract SceneEntityInfo toProto();
@Override
public String toString() {
return "Entity ID: %s; Group ID: %s; Config ID: %s"
.formatted(this.getId(), this.getGroupId(), this.getConfigId());
}
}
|
55717_1 | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
package org.graylog2.security;
import org.graylog2.plugin.database.Persisted;
import org.joda.time.DateTime;
/**
* @author Dennis Oelkers <[email protected]>
*/
public interface AccessToken extends Persisted {
DateTime getLastAccess();
String getUserName();
void setUserName(String userName);
String getToken();
void setToken(String token);
String getName();
void setName(String name);
}
| Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/security/AccessToken.java | 305 | /**
* @author Dennis Oelkers <[email protected]>
*/ | block_comment | nl | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
package org.graylog2.security;
import org.graylog2.plugin.database.Persisted;
import org.joda.time.DateTime;
/**
* @author Dennis Oelkers<SUF>*/
public interface AccessToken extends Persisted {
DateTime getLastAccess();
String getUserName();
void setUserName(String userName);
String getToken();
void setToken(String token);
String getName();
void setName(String name);
}
|
17255_50 | package com.dinodevs.greatfitwatchface.resource;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**<p>Moon phase calculation routines for computing:</p>
* <ol>
* <li> current moon phase as an index from 0 to 7,</li>
* <li> current moon age as days/hours/minutes, and</li>
* <li> percentage of the moon's illuminated portion</li>
* </ol>
* <p>Converted from rc-utils.c in the GCal package
* (http://ftp.gnu.org/gnu/gcal/gcal-2.40.tar.gz)</p>
*/
public class MoonPhase {
//Prefs prefs;
private static final double MY_PI = 3.14159265358979323846;
private static final double EPOCH = 2444238.5; /* 1980 January 0.0. */
private static final double SUN_ELONG_EPOCH = 278.833540; /* Ecliptic longitude of the Sun at epoch 1980.0. */
private static final double SUN_ELONG_PERIGEE = 282.596403; /* Ecliptic longitude of the Sun at perigee. */
private static final double ECCENT_EARTH_ORBIT = 0.016718; /* Eccentricity of Earth's orbit. */
private static final double MOON_MEAN_LONGITUDE_EPOCH = 64.975464; /* Moon's mean lonigitude at the epoch. */
private static final double MOON_MEAN_LONGITUDE_PERIGREE = 349.383063; /* Mean longitude of the perigee at the epoch. */
private static final double KEPLER_EPSILON = 1E-6; /* Accurancy of the Kepler equation. */
private static final double SYNMONTH = 29.53058868; /* Synodic month (new Moon to new Moon) */
private static final boolean orthodox_calendar = false;
public static final int mvec[] =
{
0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334
};
private static final int greg[] = {1582, 10, 5, 14};
private static final int YEAR = 0;
private static final int MONTH = 1;
public static final int FIRST_DAY = 2;
private static final int LAST_DAY = 3;
//private instance fields
private Calendar _curCal;
private double _JD;
private double _phase;
private double _moonAgeAsDays;
private String moon_phase_name[] = {
"New moon", // 0
"Waxing crescent", // 1
"First quarter", // 2
"Waxing gibbous", // 3
"Full moon", // 4
"Waning gibbous", // 5
"Last quarter", // 6
"Waning crescent" // 7
};
public MoonPhase(Calendar c){
_curCal = c;
}
public MoonPhase() {
_curCal = Calendar.getInstance();
}
/*
* Some useful mathematical functions used by John Walkers `phase()' function.
*/
private double FIXANGLE(double a) {
return (a) - 360.0 * (Math.floor((a) / 360.0));
}
private double TORAD(double d) {
return (d) * (MY_PI / 180.0);
}
private double TODEG(double r) {
return (r) * (180.0 / MY_PI);
}
/*
Solves the equation of Kepler.
*/
private double kepler(double m) {
double e;
double delta;
e = m = TORAD(m);
do {
delta = e - ECCENT_EARTH_ORBIT * Math.sin(e) - m;
e -= delta / (1.0 - ECCENT_EARTH_ORBIT * Math.cos(e));
} while (Math.abs(delta) - KEPLER_EPSILON > 0.0);
return (e);
}
// /**
// * Computes the absolute number of days of the given date since
// * 00010101(==YYYYMMDD) respecting the missing period of the
// * Gregorian Reformation.
// * @param day int day as integer value
// * @param month int month as integer value
// * @param year int year as integer value
// */
// public static int date2num(int day,
// int month,
// int year) {
// int julian_days = (year - 1) * (DAY_LAST) + ((year - 1) >> 2);
//
//
// if (year > greg[YEAR]
// || ((year == greg[YEAR])
// && (month > greg[MONTH]
// || ((month == greg[MONTH])
// && (day > greg[LAST_DAY])))))
// julian_days -= greg[LAST_DAY] - greg[FIRST_DAY] + 1;
// if (year > greg[YEAR]) {
// julian_days += (((year - 1) / 400) - (greg[YEAR] / 400));
// julian_days -= (((year - 1) / 100) - (greg[YEAR] / 100));
// if (!((greg[YEAR] % 100) == 0)
// && ((greg[YEAR] % 400) == 0)) {
// julian_days--;
// }
// }
// julian_days += mvec[month - 1];
// julian_days += day;
// if ((days_of_february(year) == 29)
// && (month > 2))
// julian_days++;
//
// return (julian_days);
// }
//
/*
Computes the number of days in February --- respecting the Gregorian
Reformation period likewise the leap year rule as used by the
Eastern orthodox churches --- and returns them.
*/
private int days_of_february(int year) {
int day;
if ((year > greg[YEAR])
|| ((year == greg[YEAR])
&& (greg[MONTH] == 1
|| ((greg[MONTH] == 2)
&& (greg[LAST_DAY] >= 28))))) {
if (orthodox_calendar)
day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0)) ? (((year % 9) == 2 || (year % 9) == 6) ? 29 : 28) : 29);
else
day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0) && ((year % 400) != 0)) ? 28 : 29);
} else
day = ((year & 3) != 0) ? 28 : 29;
/*
Exception, the year 4 AD was historically NO leap year!
*/
if (year == 4)
day--;
return (day);
}
private int SGN(double gc_x) {
return gc_x < 0 ? -1 : gc_x > 0 ? 1 : 0;
}
/**
<p>Calculates the phase of the Moon and returns the illuminated fraction of
the Moon's disc as a value within the range of -99.9~...0.0...+99.9~,
which has a negative sign in case the Moon wanes, otherwise the sign
is positive. The New Moon phase is around the 0.0 value and the Full
Moon phase is around the +/-99.9~ value. The argument is the time for
which the phase is requested, expressed as a Julian date and fraction.</p>
<p>This function is taken from the program "moontool" by John Walker,
February 1988, which is in the public domain. So see it for more
information! It is adapted (crippled) and `pretty-printed' to the
requirements of Gcal, which means it is lacking all the other useful
computations of astronomical values of the original code.</p>
<p>Here is the blurb from "moontool":</p>
<p>...The algorithms used in this program to calculate the positions Sun
and Moon as seen from the Earth are given in the book "Practical Astronomy
With Your Calculator" by Peter Duffett-Smith, Second Edition,
Cambridge University Press, 1981. Ignore the word "Calculator" in the
title; this is an essential reference if you're interested in
developing software which calculates planetary positions, orbits,
eclipses, and the like. If you're interested in pursuing such
programming, you should also obtain:</p>
<p>"Astronomical Formulae for Calculators" by Jean Meeus, Third Edition,
Willmann-Bell, 1985. A must-have.</p>
</p>"Planetary Programs and Tables from -4000 to +2800" by Pierre
Bretagnon and Jean-Louis Simon, Willmann-Bell, 1986. If you want the
utmost (outside of JPL) accuracy for the planets, it's here.</p>
<p>"Celestial BASIC" by Eric Burgess, Revised Edition, Sybex, 1985. Very
cookbook oriented, and many of the algorithms are hard to dig out of
the turgid BASIC code, but you'll probably want it anyway.</p>
<p>Many of these references can be obtained from Willmann-Bell, P.O. Box
35025, Richmond, VA 23235, USA. Phone: (804) 320-7016. In addition
to their own publications, they stock most of the standard references
for mathematical and positional astronomy.</p>
<p>This program was written by:</p>
<p>John Walker<br>
Autodesk, Inc.<br>
2320 Marinship Way<br>
Sausalito, CA 94965<br>
(415) 332-2344 Ext. 829</p>
<p>Usenet: {sun!well}!acad!kelvin</p>
<p>This program is in the public domain: "Do what thou wilt shall be the
whole of the law". I'd appreciate receiving any bug fixes and/or
enhancements, which I'll incorporate in future versions of the
program. Please leave the original attribution information intact so
that credit and blame may be properly apportioned.</p>
*/
private double phase(double julian_date) {
double date_within_epoch;
double sun_eccent;
double sun_mean_anomaly;
double sun_perigree_co_ordinates_to_epoch;
double sun_geocentric_elong;
double moon_evection;
double moon_variation;
double moon_mean_anomaly;
double moon_mean_longitude;
double moon_annual_equation;
double moon_correction_term1;
double moon_correction_term2;
double moon_correction_equation_of_center;
double moon_corrected_anomaly;
double moon_corrected_longitude;
double moon_present_age;
double moon_present_phase;
double moon_present_longitude;
/*
Calculation of the Sun's position.
*/
date_within_epoch = julian_date - EPOCH;
sun_mean_anomaly = FIXANGLE((360.0 / 365.2422) * date_within_epoch);
sun_perigree_co_ordinates_to_epoch = FIXANGLE(sun_mean_anomaly + SUN_ELONG_EPOCH - SUN_ELONG_PERIGEE);
sun_eccent = kepler(sun_perigree_co_ordinates_to_epoch);
sun_eccent = Math.sqrt((1.0 + ECCENT_EARTH_ORBIT) / (1.0 - ECCENT_EARTH_ORBIT)) * Math.tan(sun_eccent / 2.0);
sun_eccent = 2.0 * TODEG(Math.atan(sun_eccent));
sun_geocentric_elong = FIXANGLE(sun_eccent + SUN_ELONG_PERIGEE);
/*
Calculation of the Moon's position.
*/
moon_mean_longitude = FIXANGLE(13.1763966 * date_within_epoch + MOON_MEAN_LONGITUDE_EPOCH);
moon_mean_anomaly = FIXANGLE(moon_mean_longitude - 0.1114041 * date_within_epoch - MOON_MEAN_LONGITUDE_PERIGREE);
moon_evection = 1.2739 * Math.sin(TORAD(2.0 * (moon_mean_longitude - sun_geocentric_elong) - moon_mean_anomaly));
moon_annual_equation = 0.1858 * Math.sin(TORAD(sun_perigree_co_ordinates_to_epoch));
moon_correction_term1 = 0.37 * Math.sin(TORAD(sun_perigree_co_ordinates_to_epoch));
moon_corrected_anomaly = moon_mean_anomaly + moon_evection - moon_annual_equation - moon_correction_term1;
moon_correction_equation_of_center = 6.2886 * Math.sin(TORAD(moon_corrected_anomaly));
moon_correction_term2 = 0.214 * Math.sin(TORAD(2.0 * moon_corrected_anomaly));
moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_correction_equation_of_center
- moon_annual_equation + moon_correction_term2;
moon_variation = 0.6583 * Math.sin(TORAD(2.0 * (moon_corrected_longitude - sun_geocentric_elong)));
// true longitude
moon_present_longitude = moon_corrected_longitude + moon_variation;
moon_present_age = moon_present_longitude - sun_geocentric_elong;
moon_present_phase = 100.0 * ((1.0 - Math.cos(TORAD(moon_present_age))) / 2.0);
if (0.0 < FIXANGLE(moon_present_age) - 180.0) {
moon_present_phase = -moon_present_phase;
}
_moonAgeAsDays = SYNMONTH * (FIXANGLE(moon_present_age) / 360.0);
return moon_present_phase;
}
/** UCTTOJ -- Convert GMT date and time to astronomical
Julian time (i.e. Julian date plus day fraction,
expressed as a double).
@param cal Calendar object
@return JD float Julian date
<p>Converted to Java by [email protected] from original file mooncalc.c,
part of moontool http://www.fourmilab.ch/moontoolw/moont16s.zip</p>
*/
private double calendarToJD(Calendar cal) {
/* Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61*/
long year = cal.get(Calendar.YEAR);
int mon = cal.get(Calendar.MONTH);
int mday = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int a, b, m;
long y;
m = mon + 1;
y = year;
if (m <= 2) {
y--;
m += 12;
}
/* Determine whether date is in Julian or Gregorian
* calendar based on canonical date of calendar reform.
*/
if ((year < 1582) || ((year == 1582) && ((mon < 9) || (mon == 9 && mday < 5)))) {
b = 0;
} else {
a = ((int) (y / 100));
b = 2 - a + (a / 4);
}
return (((long) (365.25 * (y + 4716))) + ((int) (30.6001 * (m + 1))) +
mday + b - 1524.5) +
((sec + 60L * (min + 60L * hour)) / 86400.0);
}
/**
* Returns current phase as double value
* Uses class Calendar field _curCal
* */
public double getPhase(){
_JD = calendarToJD(_curCal);
_phase = phase(_JD);
return _phase;
}
public int getPhaseIndex(){
return computePhaseIndex(_curCal);
}
public String getPhaseName() {
return moon_phase_name[getPhaseIndex()];
}
/**
* Computes the moon phase index as a value from 0 to 7
* Used to display the phase name and the moon image
* for the current phase
* @param cal Calendar calendar object for today's date
* @return moon index 0..7
*
*/
private int computePhaseIndex(Calendar cal){
int day_year[] = { -1, -1, 30, 58, 89, 119,
150, 180, 211, 241, 272,
303, 333 };
int phase; // Moon phase
int year, month, day, hour, min, sec;
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1; // 0 = Jan, 1 = Feb, etc.
day = cal.get(Calendar.DATE);
hour = cal.get(Calendar.HOUR);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
double day_exact = day + hour/24 + min/1440 + sec/86400;
//int phase; // Moon phase
int cent; // Century number (1979 = 20)
int epact; // Age of the moon on Jan. 1
double diy; // Day in the year
int golden; // Moon's golden number
if (month < 0 || month > 12) {
month = 0; // Just in case
} // Just in case
diy = day_exact + day_year[month]; // Day in the year
if ((month > 2) && isLeapYearP(year)) {
diy++;
} // Leapyear fixup
cent = (year / 100) + 1; // Century number
golden = (year % 19) + 1; // Golden number
epact = ((11 * golden) + 20 // Golden number
+ (((8 * cent) + 5) / 25) - 5 // 400 year cycle
- (((3 * cent) / 4) - 12)) % 30; //Leap year correction
if (epact <= 0) {
epact += 30;
} // Age range is 1 .. 30
if ((epact == 25 && golden > 11) ||
epact == 24) {
epact++;
// Calculate the phase, using the magic numbers defined above.
// Note that (phase and 7) is equivalent to (phase mod 8) and
// is needed on two days per year (when the algorithm yields 8).
}
// Calculate the phase, using the magic numbers defined above.
// Note that (phase and 7) is equivalent to (phase mod 8) and
// is needed on two days per year (when the algorithm yields 8).
// this.factor = ((((diy + (double)epact) * 6) + 11) % 100 );
phase = ((((((int)diy + epact) * 6) + 11) % 177) / 22) & 7;
return(phase);
}
/** isLeapYearP
Return true if the year is a leapyear
*/
private boolean isLeapYearP(int year) {
return ((year % 4 == 0) &&
((year % 400 == 0) || (year % 100 != 0)));
}
public String getMoonAgeAsDays() {
int aom_d = (int) _moonAgeAsDays;
int aom_h = (int) (24 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays)));
int aom_m = (int) (1440 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))) % 60;
return "" + aom_d + (aom_d == 1 ? " day, ": " days, " ) +
aom_h + (aom_h == 1 ? " hour, ":" hours, ") +
aom_m + (aom_m == 1 ? " minute":" minutes");
}
/*
public static void main(String args[]) {
System.out.println(new Date());
MoonPhase mp = new MoonPhase(Calendar.getInstance());
System.out.printf("Current phase: %f%n", mp.getPhase());
System.out.println("Moon Age: " + mp.getMoonAgeAsDays());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, -22);
for (int i=0; i< 33; i++){
c.add(Calendar.DAY_OF_WEEK, 1);
mp = new MoonPhase(c);
System.out.format("%1$td %1$tB,%1$tY %1$tH:%1$tM:%1$tS ",c);
System.out.printf("Phase index: %d ", mp.getPhaseIndex());
System.out.printf("Phase string: %s ", mp.getPhaseName());
System.out.printf("%f%n", mp.getPhase());
}
}
*/
private Calendar adjustTimeZone(Calendar c, int offsetInHours){
long currTime = c.getTime().getTime();
c.setTime(new Date(currTime + offsetInHours*1000*60*60 ));
return c;
}
public int getCurrentTimeZone(){
return TimeZone.getDefault().getRawOffset()/1000*60*60;
}
}
| GreatApo/GreatFit | app/src/main/java/com/dinodevs/greatfitwatchface/resource/MoonPhase.java | 6,028 | // Moon's golden number | line_comment | nl | package com.dinodevs.greatfitwatchface.resource;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**<p>Moon phase calculation routines for computing:</p>
* <ol>
* <li> current moon phase as an index from 0 to 7,</li>
* <li> current moon age as days/hours/minutes, and</li>
* <li> percentage of the moon's illuminated portion</li>
* </ol>
* <p>Converted from rc-utils.c in the GCal package
* (http://ftp.gnu.org/gnu/gcal/gcal-2.40.tar.gz)</p>
*/
public class MoonPhase {
//Prefs prefs;
private static final double MY_PI = 3.14159265358979323846;
private static final double EPOCH = 2444238.5; /* 1980 January 0.0. */
private static final double SUN_ELONG_EPOCH = 278.833540; /* Ecliptic longitude of the Sun at epoch 1980.0. */
private static final double SUN_ELONG_PERIGEE = 282.596403; /* Ecliptic longitude of the Sun at perigee. */
private static final double ECCENT_EARTH_ORBIT = 0.016718; /* Eccentricity of Earth's orbit. */
private static final double MOON_MEAN_LONGITUDE_EPOCH = 64.975464; /* Moon's mean lonigitude at the epoch. */
private static final double MOON_MEAN_LONGITUDE_PERIGREE = 349.383063; /* Mean longitude of the perigee at the epoch. */
private static final double KEPLER_EPSILON = 1E-6; /* Accurancy of the Kepler equation. */
private static final double SYNMONTH = 29.53058868; /* Synodic month (new Moon to new Moon) */
private static final boolean orthodox_calendar = false;
public static final int mvec[] =
{
0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334
};
private static final int greg[] = {1582, 10, 5, 14};
private static final int YEAR = 0;
private static final int MONTH = 1;
public static final int FIRST_DAY = 2;
private static final int LAST_DAY = 3;
//private instance fields
private Calendar _curCal;
private double _JD;
private double _phase;
private double _moonAgeAsDays;
private String moon_phase_name[] = {
"New moon", // 0
"Waxing crescent", // 1
"First quarter", // 2
"Waxing gibbous", // 3
"Full moon", // 4
"Waning gibbous", // 5
"Last quarter", // 6
"Waning crescent" // 7
};
public MoonPhase(Calendar c){
_curCal = c;
}
public MoonPhase() {
_curCal = Calendar.getInstance();
}
/*
* Some useful mathematical functions used by John Walkers `phase()' function.
*/
private double FIXANGLE(double a) {
return (a) - 360.0 * (Math.floor((a) / 360.0));
}
private double TORAD(double d) {
return (d) * (MY_PI / 180.0);
}
private double TODEG(double r) {
return (r) * (180.0 / MY_PI);
}
/*
Solves the equation of Kepler.
*/
private double kepler(double m) {
double e;
double delta;
e = m = TORAD(m);
do {
delta = e - ECCENT_EARTH_ORBIT * Math.sin(e) - m;
e -= delta / (1.0 - ECCENT_EARTH_ORBIT * Math.cos(e));
} while (Math.abs(delta) - KEPLER_EPSILON > 0.0);
return (e);
}
// /**
// * Computes the absolute number of days of the given date since
// * 00010101(==YYYYMMDD) respecting the missing period of the
// * Gregorian Reformation.
// * @param day int day as integer value
// * @param month int month as integer value
// * @param year int year as integer value
// */
// public static int date2num(int day,
// int month,
// int year) {
// int julian_days = (year - 1) * (DAY_LAST) + ((year - 1) >> 2);
//
//
// if (year > greg[YEAR]
// || ((year == greg[YEAR])
// && (month > greg[MONTH]
// || ((month == greg[MONTH])
// && (day > greg[LAST_DAY])))))
// julian_days -= greg[LAST_DAY] - greg[FIRST_DAY] + 1;
// if (year > greg[YEAR]) {
// julian_days += (((year - 1) / 400) - (greg[YEAR] / 400));
// julian_days -= (((year - 1) / 100) - (greg[YEAR] / 100));
// if (!((greg[YEAR] % 100) == 0)
// && ((greg[YEAR] % 400) == 0)) {
// julian_days--;
// }
// }
// julian_days += mvec[month - 1];
// julian_days += day;
// if ((days_of_february(year) == 29)
// && (month > 2))
// julian_days++;
//
// return (julian_days);
// }
//
/*
Computes the number of days in February --- respecting the Gregorian
Reformation period likewise the leap year rule as used by the
Eastern orthodox churches --- and returns them.
*/
private int days_of_february(int year) {
int day;
if ((year > greg[YEAR])
|| ((year == greg[YEAR])
&& (greg[MONTH] == 1
|| ((greg[MONTH] == 2)
&& (greg[LAST_DAY] >= 28))))) {
if (orthodox_calendar)
day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0)) ? (((year % 9) == 2 || (year % 9) == 6) ? 29 : 28) : 29);
else
day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0) && ((year % 400) != 0)) ? 28 : 29);
} else
day = ((year & 3) != 0) ? 28 : 29;
/*
Exception, the year 4 AD was historically NO leap year!
*/
if (year == 4)
day--;
return (day);
}
private int SGN(double gc_x) {
return gc_x < 0 ? -1 : gc_x > 0 ? 1 : 0;
}
/**
<p>Calculates the phase of the Moon and returns the illuminated fraction of
the Moon's disc as a value within the range of -99.9~...0.0...+99.9~,
which has a negative sign in case the Moon wanes, otherwise the sign
is positive. The New Moon phase is around the 0.0 value and the Full
Moon phase is around the +/-99.9~ value. The argument is the time for
which the phase is requested, expressed as a Julian date and fraction.</p>
<p>This function is taken from the program "moontool" by John Walker,
February 1988, which is in the public domain. So see it for more
information! It is adapted (crippled) and `pretty-printed' to the
requirements of Gcal, which means it is lacking all the other useful
computations of astronomical values of the original code.</p>
<p>Here is the blurb from "moontool":</p>
<p>...The algorithms used in this program to calculate the positions Sun
and Moon as seen from the Earth are given in the book "Practical Astronomy
With Your Calculator" by Peter Duffett-Smith, Second Edition,
Cambridge University Press, 1981. Ignore the word "Calculator" in the
title; this is an essential reference if you're interested in
developing software which calculates planetary positions, orbits,
eclipses, and the like. If you're interested in pursuing such
programming, you should also obtain:</p>
<p>"Astronomical Formulae for Calculators" by Jean Meeus, Third Edition,
Willmann-Bell, 1985. A must-have.</p>
</p>"Planetary Programs and Tables from -4000 to +2800" by Pierre
Bretagnon and Jean-Louis Simon, Willmann-Bell, 1986. If you want the
utmost (outside of JPL) accuracy for the planets, it's here.</p>
<p>"Celestial BASIC" by Eric Burgess, Revised Edition, Sybex, 1985. Very
cookbook oriented, and many of the algorithms are hard to dig out of
the turgid BASIC code, but you'll probably want it anyway.</p>
<p>Many of these references can be obtained from Willmann-Bell, P.O. Box
35025, Richmond, VA 23235, USA. Phone: (804) 320-7016. In addition
to their own publications, they stock most of the standard references
for mathematical and positional astronomy.</p>
<p>This program was written by:</p>
<p>John Walker<br>
Autodesk, Inc.<br>
2320 Marinship Way<br>
Sausalito, CA 94965<br>
(415) 332-2344 Ext. 829</p>
<p>Usenet: {sun!well}!acad!kelvin</p>
<p>This program is in the public domain: "Do what thou wilt shall be the
whole of the law". I'd appreciate receiving any bug fixes and/or
enhancements, which I'll incorporate in future versions of the
program. Please leave the original attribution information intact so
that credit and blame may be properly apportioned.</p>
*/
private double phase(double julian_date) {
double date_within_epoch;
double sun_eccent;
double sun_mean_anomaly;
double sun_perigree_co_ordinates_to_epoch;
double sun_geocentric_elong;
double moon_evection;
double moon_variation;
double moon_mean_anomaly;
double moon_mean_longitude;
double moon_annual_equation;
double moon_correction_term1;
double moon_correction_term2;
double moon_correction_equation_of_center;
double moon_corrected_anomaly;
double moon_corrected_longitude;
double moon_present_age;
double moon_present_phase;
double moon_present_longitude;
/*
Calculation of the Sun's position.
*/
date_within_epoch = julian_date - EPOCH;
sun_mean_anomaly = FIXANGLE((360.0 / 365.2422) * date_within_epoch);
sun_perigree_co_ordinates_to_epoch = FIXANGLE(sun_mean_anomaly + SUN_ELONG_EPOCH - SUN_ELONG_PERIGEE);
sun_eccent = kepler(sun_perigree_co_ordinates_to_epoch);
sun_eccent = Math.sqrt((1.0 + ECCENT_EARTH_ORBIT) / (1.0 - ECCENT_EARTH_ORBIT)) * Math.tan(sun_eccent / 2.0);
sun_eccent = 2.0 * TODEG(Math.atan(sun_eccent));
sun_geocentric_elong = FIXANGLE(sun_eccent + SUN_ELONG_PERIGEE);
/*
Calculation of the Moon's position.
*/
moon_mean_longitude = FIXANGLE(13.1763966 * date_within_epoch + MOON_MEAN_LONGITUDE_EPOCH);
moon_mean_anomaly = FIXANGLE(moon_mean_longitude - 0.1114041 * date_within_epoch - MOON_MEAN_LONGITUDE_PERIGREE);
moon_evection = 1.2739 * Math.sin(TORAD(2.0 * (moon_mean_longitude - sun_geocentric_elong) - moon_mean_anomaly));
moon_annual_equation = 0.1858 * Math.sin(TORAD(sun_perigree_co_ordinates_to_epoch));
moon_correction_term1 = 0.37 * Math.sin(TORAD(sun_perigree_co_ordinates_to_epoch));
moon_corrected_anomaly = moon_mean_anomaly + moon_evection - moon_annual_equation - moon_correction_term1;
moon_correction_equation_of_center = 6.2886 * Math.sin(TORAD(moon_corrected_anomaly));
moon_correction_term2 = 0.214 * Math.sin(TORAD(2.0 * moon_corrected_anomaly));
moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_correction_equation_of_center
- moon_annual_equation + moon_correction_term2;
moon_variation = 0.6583 * Math.sin(TORAD(2.0 * (moon_corrected_longitude - sun_geocentric_elong)));
// true longitude
moon_present_longitude = moon_corrected_longitude + moon_variation;
moon_present_age = moon_present_longitude - sun_geocentric_elong;
moon_present_phase = 100.0 * ((1.0 - Math.cos(TORAD(moon_present_age))) / 2.0);
if (0.0 < FIXANGLE(moon_present_age) - 180.0) {
moon_present_phase = -moon_present_phase;
}
_moonAgeAsDays = SYNMONTH * (FIXANGLE(moon_present_age) / 360.0);
return moon_present_phase;
}
/** UCTTOJ -- Convert GMT date and time to astronomical
Julian time (i.e. Julian date plus day fraction,
expressed as a double).
@param cal Calendar object
@return JD float Julian date
<p>Converted to Java by [email protected] from original file mooncalc.c,
part of moontool http://www.fourmilab.ch/moontoolw/moont16s.zip</p>
*/
private double calendarToJD(Calendar cal) {
/* Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61*/
long year = cal.get(Calendar.YEAR);
int mon = cal.get(Calendar.MONTH);
int mday = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int a, b, m;
long y;
m = mon + 1;
y = year;
if (m <= 2) {
y--;
m += 12;
}
/* Determine whether date is in Julian or Gregorian
* calendar based on canonical date of calendar reform.
*/
if ((year < 1582) || ((year == 1582) && ((mon < 9) || (mon == 9 && mday < 5)))) {
b = 0;
} else {
a = ((int) (y / 100));
b = 2 - a + (a / 4);
}
return (((long) (365.25 * (y + 4716))) + ((int) (30.6001 * (m + 1))) +
mday + b - 1524.5) +
((sec + 60L * (min + 60L * hour)) / 86400.0);
}
/**
* Returns current phase as double value
* Uses class Calendar field _curCal
* */
public double getPhase(){
_JD = calendarToJD(_curCal);
_phase = phase(_JD);
return _phase;
}
public int getPhaseIndex(){
return computePhaseIndex(_curCal);
}
public String getPhaseName() {
return moon_phase_name[getPhaseIndex()];
}
/**
* Computes the moon phase index as a value from 0 to 7
* Used to display the phase name and the moon image
* for the current phase
* @param cal Calendar calendar object for today's date
* @return moon index 0..7
*
*/
private int computePhaseIndex(Calendar cal){
int day_year[] = { -1, -1, 30, 58, 89, 119,
150, 180, 211, 241, 272,
303, 333 };
int phase; // Moon phase
int year, month, day, hour, min, sec;
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1; // 0 = Jan, 1 = Feb, etc.
day = cal.get(Calendar.DATE);
hour = cal.get(Calendar.HOUR);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
double day_exact = day + hour/24 + min/1440 + sec/86400;
//int phase; // Moon phase
int cent; // Century number (1979 = 20)
int epact; // Age of the moon on Jan. 1
double diy; // Day in the year
int golden; // Moon's golden<SUF>
if (month < 0 || month > 12) {
month = 0; // Just in case
} // Just in case
diy = day_exact + day_year[month]; // Day in the year
if ((month > 2) && isLeapYearP(year)) {
diy++;
} // Leapyear fixup
cent = (year / 100) + 1; // Century number
golden = (year % 19) + 1; // Golden number
epact = ((11 * golden) + 20 // Golden number
+ (((8 * cent) + 5) / 25) - 5 // 400 year cycle
- (((3 * cent) / 4) - 12)) % 30; //Leap year correction
if (epact <= 0) {
epact += 30;
} // Age range is 1 .. 30
if ((epact == 25 && golden > 11) ||
epact == 24) {
epact++;
// Calculate the phase, using the magic numbers defined above.
// Note that (phase and 7) is equivalent to (phase mod 8) and
// is needed on two days per year (when the algorithm yields 8).
}
// Calculate the phase, using the magic numbers defined above.
// Note that (phase and 7) is equivalent to (phase mod 8) and
// is needed on two days per year (when the algorithm yields 8).
// this.factor = ((((diy + (double)epact) * 6) + 11) % 100 );
phase = ((((((int)diy + epact) * 6) + 11) % 177) / 22) & 7;
return(phase);
}
/** isLeapYearP
Return true if the year is a leapyear
*/
private boolean isLeapYearP(int year) {
return ((year % 4 == 0) &&
((year % 400 == 0) || (year % 100 != 0)));
}
public String getMoonAgeAsDays() {
int aom_d = (int) _moonAgeAsDays;
int aom_h = (int) (24 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays)));
int aom_m = (int) (1440 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))) % 60;
return "" + aom_d + (aom_d == 1 ? " day, ": " days, " ) +
aom_h + (aom_h == 1 ? " hour, ":" hours, ") +
aom_m + (aom_m == 1 ? " minute":" minutes");
}
/*
public static void main(String args[]) {
System.out.println(new Date());
MoonPhase mp = new MoonPhase(Calendar.getInstance());
System.out.printf("Current phase: %f%n", mp.getPhase());
System.out.println("Moon Age: " + mp.getMoonAgeAsDays());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, -22);
for (int i=0; i< 33; i++){
c.add(Calendar.DAY_OF_WEEK, 1);
mp = new MoonPhase(c);
System.out.format("%1$td %1$tB,%1$tY %1$tH:%1$tM:%1$tS ",c);
System.out.printf("Phase index: %d ", mp.getPhaseIndex());
System.out.printf("Phase string: %s ", mp.getPhaseName());
System.out.printf("%f%n", mp.getPhase());
}
}
*/
private Calendar adjustTimeZone(Calendar c, int offsetInHours){
long currTime = c.getTime().getTime();
c.setTime(new Date(currTime + offsetInHours*1000*60*60 ));
return c;
}
public int getCurrentTimeZone(){
return TimeZone.getDefault().getRawOffset()/1000*60*60;
}
}
|
33092_2 | package calories2.Model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author Jeroen De Meyer
*/
public class FoodCollection {
// the maximum number of search results that will be displayed.
private final int MAX_NUMBER_RESULTS = 50;
private final Set<Food> foodCollection = new HashSet<>();
public Set<Food> getFoodCollection(){return foodCollection;}
public FoodCollection(){
makeCollection();
}
private void makeCollection(){
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
FoodCollection.class.getResourceAsStream("/resources/Calories.txt")));
String line = reader.readLine();
while(line!=null){
String[]food = dataFromString(line);
foodCollection.add(new Food(
food[0].trim().toLowerCase(),
food[1].trim().toLowerCase(),
Double.parseDouble(food[2]),
//de 5e kolom zijn de eiwitten en de 4e kolom de carbs, daarom indexen omgedraaid.
Double.parseDouble(food[4]),
Double.parseDouble(food[3]),
Double.parseDouble(food[5])));
line = reader.readLine();
}
}catch(IOException e){
System.out.println("Couldn't read file");
}
}
private String[] dataFromString(String s){
return s.split("/");
}
public List<Food> search(String s){
List<Food> results = new ArrayList<>();
for(Food food: foodCollection){
if(food.getName().startsWith(s.trim().toLowerCase())){
results.add(food);
}
if(results.size() >= MAX_NUMBER_RESULTS){
break;
}
}
return results;
}
}
| GrigoriLomonosov/CalorieCounter | src/calories2/Model/FoodCollection.java | 563 | //de 5e kolom zijn de eiwitten en de 4e kolom de carbs, daarom indexen omgedraaid. | line_comment | nl | package calories2.Model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author Jeroen De Meyer
*/
public class FoodCollection {
// the maximum number of search results that will be displayed.
private final int MAX_NUMBER_RESULTS = 50;
private final Set<Food> foodCollection = new HashSet<>();
public Set<Food> getFoodCollection(){return foodCollection;}
public FoodCollection(){
makeCollection();
}
private void makeCollection(){
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
FoodCollection.class.getResourceAsStream("/resources/Calories.txt")));
String line = reader.readLine();
while(line!=null){
String[]food = dataFromString(line);
foodCollection.add(new Food(
food[0].trim().toLowerCase(),
food[1].trim().toLowerCase(),
Double.parseDouble(food[2]),
//de 5e<SUF>
Double.parseDouble(food[4]),
Double.parseDouble(food[3]),
Double.parseDouble(food[5])));
line = reader.readLine();
}
}catch(IOException e){
System.out.println("Couldn't read file");
}
}
private String[] dataFromString(String s){
return s.split("/");
}
public List<Food> search(String s){
List<Food> results = new ArrayList<>();
for(Food food: foodCollection){
if(food.getName().startsWith(s.trim().toLowerCase())){
results.add(food);
}
if(results.size() >= MAX_NUMBER_RESULTS){
break;
}
}
return results;
}
}
|
24342_1 | public class Main {
// maak packages om je practicum opdrachten in 1 project te beheren. Zorg wel dat alle code blijft werken.
public static void main(String[] args) {
//standaard code IntelliJ. Gebruik het voor testjes e.d.
System.out.println("Hello from Automata & Programming. Choose the right class to run!");
}
}
| Grittie/AENP | src/Main.java | 102 | //standaard code IntelliJ. Gebruik het voor testjes e.d. | line_comment | nl | public class Main {
// maak packages om je practicum opdrachten in 1 project te beheren. Zorg wel dat alle code blijft werken.
public static void main(String[] args) {
//standaard code<SUF>
System.out.println("Hello from Automata & Programming. Choose the right class to run!");
}
}
|
3031_1 | package controller;
import java.util.ArrayList;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import model.Docent;
import model.PrIS;
import model.Vak;
import server.Conversation;
import server.Handler;
public class DocentController implements Handler {
private PrIS informatieSysteem;
/**
* De DocentController klasse moet alle docent-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public DocentController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {
mijnVakken(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void mijnVakken(Conversation conversation) {
JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String gebruikersnaam = jsonObjectIn.getString("username");
Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!
ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!
JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met...
for (Vak v : vakken) {
jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object...
.add("vakcode", v.getVakCode())
.add("vaknaam", v.getVakNaam()));
}
conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!
}
}
| Gundraub/PrIS | src/controller/DocentController.java | 697 | /**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/ | block_comment | nl | package controller;
import java.util.ArrayList;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import model.Docent;
import model.PrIS;
import model.Vak;
import server.Conversation;
import server.Handler;
public class DocentController implements Handler {
private PrIS informatieSysteem;
/**
* De DocentController klasse moet alle docent-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public DocentController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {
mijnVakken(conversation);
}
}
/**
* Deze methode haalt<SUF>*/
private void mijnVakken(Conversation conversation) {
JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String gebruikersnaam = jsonObjectIn.getString("username");
Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!
ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!
JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met...
for (Vak v : vakken) {
jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object...
.add("vakcode", v.getVakCode())
.add("vaknaam", v.getVakNaam()));
}
conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!
}
}
|
8794_8 | package com.kit.utils;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* @author Joey.Zhao Email: [email protected]
* @date 2014年3月20日
*/
public class KeyboardUtils {
/**
* 一定要注意,隐藏键盘的时候,要保证view可见
*
* @param context
* @param view
*/
public static void hiddenKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
// if (view.getVisibility() != View.VISIBLE) {
// LogUtils.printLog(KeyboardUtils.class, "view must visible!!!");
// }
view.clearFocus();
if (context != null && imm != null) {
if (view != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} else {
imm.hideSoftInputFromWindow(((Activity) context)
.getCurrentFocus().getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
// @Deprecated
// public static void hiddenKeyboard(Context context) {
// InputMethodManager im = (InputMethodManager) context
// .getSystemService(Context.INPUT_METHOD_SERVICE);
// // 获取输入法是否打开
// boolean isOpen = im.isActive();
// if (context != null && im != null) {
// if (isOpen) {
// try {
// im.hideSoftInputFromWindow(((Activity) context)
// .getCurrentFocus().getApplicationWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// } catch (Exception e) {
// LogUtils.showException(e);
// }
// } else {
// try {
// im.hideSoftInputFromWindow(((Activity) context)
// .getCurrentFocus().getApplicationWindowToken(),
// InputMethodManager.SHOW_FORCED);
// } catch (Exception e) {
// LogUtils.showException(e);
// }
// }
// }
// }
/**
* 强制显示软键盘
*
* @param context
* @param view 为接受软键盘输入的视图
*/
public static void showKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
imm.showSoftInput(view,
InputMethodManager.RESULT_UNCHANGED_SHOWN);
// imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
// InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 键盘是否在打开状态
*
* @param context
* @return
*/
public static boolean isOpen(Context context) {
InputMethodManager im = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
// 获取输入法是否打开
boolean isOpen = im.isActive();
return isOpen;
}
}
| GuoQiQq/BigApp_Discuz_Android-master | libs/ZUtils/src/com/kit/utils/KeyboardUtils.java | 911 | // if (isOpen) { | line_comment | nl | package com.kit.utils;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* @author Joey.Zhao Email: [email protected]
* @date 2014年3月20日
*/
public class KeyboardUtils {
/**
* 一定要注意,隐藏键盘的时候,要保证view可见
*
* @param context
* @param view
*/
public static void hiddenKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
// if (view.getVisibility() != View.VISIBLE) {
// LogUtils.printLog(KeyboardUtils.class, "view must visible!!!");
// }
view.clearFocus();
if (context != null && imm != null) {
if (view != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} else {
imm.hideSoftInputFromWindow(((Activity) context)
.getCurrentFocus().getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
// @Deprecated
// public static void hiddenKeyboard(Context context) {
// InputMethodManager im = (InputMethodManager) context
// .getSystemService(Context.INPUT_METHOD_SERVICE);
// // 获取输入法是否打开
// boolean isOpen = im.isActive();
// if (context != null && im != null) {
// if (isOpen)<SUF>
// try {
// im.hideSoftInputFromWindow(((Activity) context)
// .getCurrentFocus().getApplicationWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// } catch (Exception e) {
// LogUtils.showException(e);
// }
// } else {
// try {
// im.hideSoftInputFromWindow(((Activity) context)
// .getCurrentFocus().getApplicationWindowToken(),
// InputMethodManager.SHOW_FORCED);
// } catch (Exception e) {
// LogUtils.showException(e);
// }
// }
// }
// }
/**
* 强制显示软键盘
*
* @param context
* @param view 为接受软键盘输入的视图
*/
public static void showKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
imm.showSoftInput(view,
InputMethodManager.RESULT_UNCHANGED_SHOWN);
// imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
// InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 键盘是否在打开状态
*
* @param context
* @return
*/
public static boolean isOpen(Context context) {
InputMethodManager im = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
// 获取输入法是否打开
boolean isOpen = im.isActive();
return isOpen;
}
}
|
48070_40 | package edu.caltech.lncrna.bio.datastructures;
import java.util.Iterator;
/**
* This class represents a node of a red-black interval tree.
* <p>
* This class is defined by two different type variables, <code>T</code> and
* <code>U</code>. The first, <code>T</code>, represents the type of interval
* contained in this node's corresponding tree. This type should be obvious,
* and is analogous to the <code>T</code> in <code>List<T></code>. The
* second, <code>U</code>, represents the type contained internally in each
* node. For example, if a node store's multiple intervals in an internal set,
* <code>U</code> might be <code>IntervalSet<T></code>.
* @param <T> - the type of interval that this node's tree contains
* @param <U> - the type of interval or data structure that the node itself
* contains
*/
public abstract class RedBlackNode<T extends Interval, U extends Interval>
implements Interval, Iterable<T> {
protected U data;
protected RedBlackNode<T, U> parent;
protected RedBlackNode<T, U> left;
protected RedBlackNode<T, U> right;
protected boolean isBlack;
protected int maxEnd;
/**
* Class constructor.
* <p>
* Constructs a new, empty <code>RedBlackNode</code> instance.
* <p>
* This constructor is meant to be called when instantiating the sentinel
* node of a tree.
*/
protected RedBlackNode() {
parent = this;
left = this;
right = this;
blacken();
}
/**
* Class constructor.
* <p>
* Constructs a new <code>RedBlackNode</code> instance containing the given
* element.
*
* @param element - the element to be contained by the resulting node
*/
protected RedBlackNode(U element) {
data = element;
parent = nil();
left = nil();
right = nil();
maxEnd = data.getEnd();
redden();
}
/**
* Returns the data contained by this node.
*
* @return the data contained by this node
*/
protected U getData() {
return data;
}
@Override
public int getStart() {
return data.getStart();
}
@Override
public int getEnd() {
return data.getEnd();
}
/**
* Searches this node's tree for the next node.
*
* @return the node following this node, if it exists; otherwise the
* sentinel node
*/
protected RedBlackNode<T, U> successor() {
if (!right.isNil()) {
return right.minimumNode();
}
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> y = parent;
while (!y.isNil() && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* Searches this node's tree for the previous node.
*
* @return the node preceding this node, if it exists; otherwise the
* sentinel node
*/
protected RedBlackNode<T, U> predecessor() {
if (!left.isNil()) {
return left.maximumNode();
}
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> y = parent;
while (!y.isNil() && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* Searches the subtree rooted at this node for the node with the same
* coordinates as the specified {@link Interval}.
*
* @param i - the specified interval
* @return the matching node, if it exists; otherwise, the sentinel
* node
*/
protected RedBlackNode<T, U> search(Interval i) {
RedBlackNode<T, U> n = this;
while (!n.isNil() && i.compareTo(n) != 0) {
n = i.compareTo(n) == -1 ? n.left : n.right;
}
return n;
}
/**
* Searches the subtree rooted at this node for the node with the
* passed start and end coordinates.
*
* @param start - the start coordinate
* @param end - the end coordinate
* @return the matching node, if it exists; otherwise, the sentinel
* node
*/
protected RedBlackNode<T, U> search(int start, int end) {
return search(new SimpleInterval(start, end));
}
/**
* Searches the subtree rooted at this node for the node with the
* minimum {@link Interval}.
*
* @return the node with the minimum interval, if it exists; otherwise,
* the sentinel node
*/
protected RedBlackNode<T, U> minimumNode() {
RedBlackNode<T, U> n = this;
while (!n.left.isNil()) {
n = n.left;
}
return n;
}
/**
* Searches the subtree rooted at this node for the node with the
* maximum {@link Interval}.
*
* @return the node with the maximum interval, if it exists; otherwise
* the sentinel node
*/
protected RedBlackNode<T, U> maximumNode() {
RedBlackNode<T, U> n = this;
while (!n.right.isNil()) {
n = n.right;
}
return n;
}
/**
* Returns whether this node is the root of its tree.
*
* @return <code>true</code> if this node is the root
*/
public boolean isRoot() {
return (!isNil() && parent.isNil());
}
/**
* Returns whether this node is the sentinel node.
*
* @return <code>true</code> if this node is the sentinel node
*/
public boolean isNil() {
return this == nil();
}
/**
* Returns whether this node is the left child of its parent.
*
* @return <code>true</code> if this node is a left child
*/
public boolean isLeftChild() {
return this == parent.left;
}
/**
* Returns whether this node is the right child of its parent.
*
* @return <code>true</code> if this node is a right child
*/
public boolean isRightChild() {
return this == parent.right;
}
/**
* Returns whether this node has no children, i.e., is a leaf.
*
* @return <code>true</code> if this node has no children
*/
public boolean hasNoChildren() {
return left.isNil() && right.isNil();
}
/**
* Returns whether or not this node has two children, i.e., neither of
* its children are leaves
*
* @return <code>true</code> if this node has two children
*/
public boolean hasTwoChildren() {
return !left.isNil() && !right.isNil();
}
/**
* Sets this node's color to black.
*/
protected void blacken() {
isBlack = true;
}
/**
* Sets this node's color to red.
*/
protected void redden() {
isBlack = false;
}
/**
* Returns if this node is red.
*
* @return if this node's color is red
*/
public boolean isRed() {
return !isBlack;
}
/**
* Returns this node's grandparent.
*
* @return a reference to the grandparent of this node
*/
protected RedBlackNode<T, U> grandparent() {
return parent.parent;
}
/**
* Resets the <code>maxEnd</code> field of this node to its correct
* value.
* <p>
* The value of the <code>maxEnd</code> field should be the greatest
* of:
* <ul>
* <li>the end value of this node's data
* <li>the <code>maxEnd</code> value of this node's left child, if not
* nil
* <li>the <code>maxEnd</code> value of this node's right child, if not
* nil
* </ul>
* <p>
* This method will be correct only if the left and right children have
* correct <code>maxEnd</code> values.
*/
protected void resetMaxEnd() {
int val = data.getEnd();
if (!left.isNil()) {
val = Math.max(val, left.maxEnd);
}
if (!right.isNil()) {
val = Math.max(val, right.maxEnd);
}
maxEnd = val;
}
/**
* Copies the data from another node into this node.
* <p>
* Technically, no copying occurs. This method just assigns a reference
* to the other node's data.
*
* @param o - the other node containing the data to be copied
*/
protected void copyData(RedBlackNode<T, U> o) {
data = o.data;
}
protected abstract RedBlackNode<T, U> nil();
protected abstract int size();
///////////////////////////////////////
// Node -- Overlapping query methods //
///////////////////////////////////////
/**
* Returns a node in this node's subtree that overlaps the given interval.
* <p>
* The only guarantee of this method is that the returned
* node overlaps the specified interval. This method is meant to be a
* quick helper method to determine if any overlap exists between an
* interval and any of a tree's intervals. The returned node will be
* the first overlapping one found.
*
* @param i - the overlapping interval
* @return a node from this node's subtree that overlaps the given
* interval, if one exists; otherwise the sentinel node
*/
protected RedBlackNode<T, U> anyOverlappingNode(Interval i) {
RedBlackNode<T, U> x = this;
while (!x.isNil() && !i.overlaps(x.data)) {
x = !x.left.isNil() && x.left.maxEnd > i.getStart() ? x.left : x.right;
}
return x;
}
/**
* Returns the minimum node in this node's subtree that overlaps the given
* interval.
*
* @param i - the specified interval
* @return the minimum node from this node's subtree that overlaps the
* given interval, if one exists; otherwise, the sentinel node
*/
RedBlackNode<T, U> minimumOverlappingNode(Interval i) {
RedBlackNode<T, U> result = nil();
RedBlackNode<T, U> n = this;
if (!n.isNil() && n.maxEnd > i.getStart()) {
while (true) {
if (n.overlaps(i)) {
// This node overlaps. There may be a lesser overlapper
// down the left subtree. No need to consider the right
// as all overlappers there will be greater.
result = n;
n = n.left;
if (n.isNil() || n.maxEnd <= i.getStart()) {
// Either no left subtree, or nodes can't overlap.
break;
}
} else {
// This node doesn't overlap.
// Check the left subtree if an overlapper may be there
RedBlackNode<T, U> left = n.left;
if (!left.isNil() && left.maxEnd > i.getStart()) {
n = left;
} else {
// Left subtree cannot contain an overlapper. Check the
// right sub-tree.
if (n.getStart() >= i.getEnd()) {
// Nothing in the right subtree can overlap
break;
}
n = n.right;
if (n.isNil() || n.maxEnd <= i.getStart()) {
// No right subtree, or nodes can't overlap.
break;
}
}
}
}
}
return result;
}
/**
* Returns the next node in this node's subtree that overlaps the given
* interval.
*
* @param i - the given interval
* @return the next node (relative to this node) that overlaps the
* given interval; if one does not exist, the sentinel node
*/
protected RedBlackNode<T, U> nextOverlappingNode(Interval i) {
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> rtrn = nil();
// First, check the right subtree for its minimum overlapper.
if (!right.isNil()) {
rtrn = x.right.minimumOverlappingNode(i);
}
// If we didn't find it in the right subtree, walk up the tree and
// check the parents of left-children as well as their right subtrees.
while (!x.parent.isNil() && rtrn.isNil()) {
if (x.isLeftChild()) {
rtrn = x.parent.overlaps(i)
? x.parent
: x.parent.right.minimumOverlappingNode(i);
}
x = x.parent;
}
return rtrn;
}
/**
* Returns the number of nodes in this node's subtree that overlap the
* specified interval.
* <p>
* This number includes this node if it overlaps the interval. This
* method iterates over all overlapping nodes, so if you ultimately
* need to inspect the nodes or do anything more than get a count, it
* will be more efficient to simply create the iterator yourself with
* {@link Node#overlappers}.
*
* @param i - the specified interval
* @return the number of overlapping nodes
*/
protected abstract int numOverlappingNodes(Interval i);
/**
* @param i - the specified interval
* @return an iterator over all values in this node's subtree that
* overlap the specified interval
*/
protected abstract Iterator<T> overlappers(Interval i);
///////////////////////////////
// Node -- Debugging methods //
///////////////////////////////
/**
* Returns <code>false</code> if any node in this node's subtree is less
* than its left child or greater than its right child.
* <p>
* Method for testing and debugging.
*
* @param min - a lower-bound node
* @param max - an upper-bound node
* @return whether or not the subtree rooted at this node is a valid
* binary-search tree
*/
protected boolean isBST(RedBlackNode<T, U> min, RedBlackNode<T, U> max) {
if (isNil()) {
return true; // Leaves are a valid BST, trivially.
}
if (min != null && compareTo(min) <= 0) {
return false; // This Node must be greater than min
}
if (max != null && compareTo(max) >= 0) {
return false; // and less than max.
}
// Children recursively call method with updated min/max.
return left.isBST(min, this) && right.isBST(this, max);
}
/**
* Returns <code>false</code> if all of the branches of this node's subtree
* (from root to leaf) do not contain the same number of black nodes.
* (Specifically, the black-number of each branch is compared against the
* black-number of the left-most branch.)
* <p>
* Method for testing and debugging.
* <p>
* Balance determination is done by calculating the black-height.
*
* @param black - the expected black-height of this subtree
* @returns whether or not the subtree rooted at this node is balanced.
*/
protected boolean isBalanced(int black) {
if (isNil()) {
return black == 0; // Leaves have a black-height of zero,
} // even though they are black.
if (isBlack) {
black--;
}
return left.isBalanced(black) && right.isBalanced(black);
}
/**
* Returns <code>true</code> if this node's subtree has a valid
* red-coloring.
* <p>
* Method for testing and debugging.
* <p>
* A red-black tree has a valid red-coloring if every red node has two
* black children. The sentinel node is black.
*
* @return whether or not the subtree rooted at this node has a valid
* red-coloring.
*/
protected boolean hasValidRedColoring() {
if (isNil()) {
return true;
} else if (isBlack) {
return left.hasValidRedColoring() &&
right.hasValidRedColoring();
} else {
return left.isBlack && right.isBlack &&
left.hasValidRedColoring() &&
right.hasValidRedColoring();
}
}
/**
* Returns <code>true</code> if each node in this node's subtree has a
* <code>maxEnd</code> value equal to the greatest interval end value of
* all the intervals in its subtree.
* <p>
* The <code>maxEnd</code> value of an interval-tree node is equal to
* the maximum of the end-values of all intervals contained in the
* node's subtree.
* <p>
* Method for testing and debugging.
*
* @return whether or not the constituent nodes of the subtree rooted
* at this node have consistent values for the <code>maxEnd</code>
* field.
*/
protected boolean hasConsistentMaxEnds() {
if (isNil()) { // 1. sentinel node
return true;
}
if (hasNoChildren()) { // 2. leaf node
return maxEnd == getEnd();
} else {
boolean consistent = maxEnd >= getEnd();
if (hasTwoChildren()) { // 3. two children
return consistent &&
maxEnd >= left.maxEnd &&
maxEnd >= right.maxEnd &&
left.hasConsistentMaxEnds() &&
right.hasConsistentMaxEnds();
} else if (left.isNil()) { // 4. one child -- right
return consistent &&
maxEnd >= right.maxEnd &&
right.hasConsistentMaxEnds();
} else {
return consistent && // 5. one child -- left
maxEnd >= left.maxEnd &&
left.hasConsistentMaxEnds();
}
}
}
/**
* Returns the string representation of this node.
* <p>
* The exact details of this representation are unspecified and subject to
* change, but it will typically contain information about this node's
* start and end values, as well as the values of its parent and children.
* <p>
* This method should be used solely for debugging and testing.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.isNil()) {
sb.append("this: nil\n");
} else {
sb.append("this: [" + getStart() + ", " + getEnd() + ")\n");
}
if (parent.isNil()) {
sb.append("parent: nil\n");
} else {
sb.append("parent: [" + parent.getStart() + ", " +
parent.getEnd() + ")\n");
}
if (left.isNil()) {
sb.append("left: nil\n");
} else {
sb.append("left: [" + left.getStart() + ", " +
left.getEnd() + ")\n");
}
if (right.isNil()) {
sb.append("right: nil\n");
} else {
sb.append("right: [" + left.getStart() + ", " +
right.getEnd() + ")\n");
}
return sb.toString();
}
@Override
public boolean equals(Object other) {
// No need for null check. The instanceof operator returns false
// if (other == null).
if (!(other instanceof RedBlackNode<?, ?>)) {
return false;
}
RedBlackNode<?, ?> o = (RedBlackNode<?, ?>) other;
return data.equals(o.data) &&
isBlack == o.isBlack &&
maxEnd == o.maxEnd &&
parent == o.parent &&
left == o.left &&
right == o.right;
}
@Override
public int hashCode() {
// TODO: What to do about node references? Does this even matter?
int result = 17;
result = 31 * result + data.hashCode();
result = 31 * result + (isBlack ? 1 : 0);
result = 31 * result + maxEnd;
return result;
}
}
| GuttmanLab/bio | src/edu/caltech/lncrna/bio/datastructures/RedBlackNode.java | 5,722 | // Node -- Debugging methods // | line_comment | nl | package edu.caltech.lncrna.bio.datastructures;
import java.util.Iterator;
/**
* This class represents a node of a red-black interval tree.
* <p>
* This class is defined by two different type variables, <code>T</code> and
* <code>U</code>. The first, <code>T</code>, represents the type of interval
* contained in this node's corresponding tree. This type should be obvious,
* and is analogous to the <code>T</code> in <code>List<T></code>. The
* second, <code>U</code>, represents the type contained internally in each
* node. For example, if a node store's multiple intervals in an internal set,
* <code>U</code> might be <code>IntervalSet<T></code>.
* @param <T> - the type of interval that this node's tree contains
* @param <U> - the type of interval or data structure that the node itself
* contains
*/
public abstract class RedBlackNode<T extends Interval, U extends Interval>
implements Interval, Iterable<T> {
protected U data;
protected RedBlackNode<T, U> parent;
protected RedBlackNode<T, U> left;
protected RedBlackNode<T, U> right;
protected boolean isBlack;
protected int maxEnd;
/**
* Class constructor.
* <p>
* Constructs a new, empty <code>RedBlackNode</code> instance.
* <p>
* This constructor is meant to be called when instantiating the sentinel
* node of a tree.
*/
protected RedBlackNode() {
parent = this;
left = this;
right = this;
blacken();
}
/**
* Class constructor.
* <p>
* Constructs a new <code>RedBlackNode</code> instance containing the given
* element.
*
* @param element - the element to be contained by the resulting node
*/
protected RedBlackNode(U element) {
data = element;
parent = nil();
left = nil();
right = nil();
maxEnd = data.getEnd();
redden();
}
/**
* Returns the data contained by this node.
*
* @return the data contained by this node
*/
protected U getData() {
return data;
}
@Override
public int getStart() {
return data.getStart();
}
@Override
public int getEnd() {
return data.getEnd();
}
/**
* Searches this node's tree for the next node.
*
* @return the node following this node, if it exists; otherwise the
* sentinel node
*/
protected RedBlackNode<T, U> successor() {
if (!right.isNil()) {
return right.minimumNode();
}
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> y = parent;
while (!y.isNil() && x == y.right) {
x = y;
y = y.parent;
}
return y;
}
/**
* Searches this node's tree for the previous node.
*
* @return the node preceding this node, if it exists; otherwise the
* sentinel node
*/
protected RedBlackNode<T, U> predecessor() {
if (!left.isNil()) {
return left.maximumNode();
}
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> y = parent;
while (!y.isNil() && x == y.left) {
x = y;
y = y.parent;
}
return y;
}
/**
* Searches the subtree rooted at this node for the node with the same
* coordinates as the specified {@link Interval}.
*
* @param i - the specified interval
* @return the matching node, if it exists; otherwise, the sentinel
* node
*/
protected RedBlackNode<T, U> search(Interval i) {
RedBlackNode<T, U> n = this;
while (!n.isNil() && i.compareTo(n) != 0) {
n = i.compareTo(n) == -1 ? n.left : n.right;
}
return n;
}
/**
* Searches the subtree rooted at this node for the node with the
* passed start and end coordinates.
*
* @param start - the start coordinate
* @param end - the end coordinate
* @return the matching node, if it exists; otherwise, the sentinel
* node
*/
protected RedBlackNode<T, U> search(int start, int end) {
return search(new SimpleInterval(start, end));
}
/**
* Searches the subtree rooted at this node for the node with the
* minimum {@link Interval}.
*
* @return the node with the minimum interval, if it exists; otherwise,
* the sentinel node
*/
protected RedBlackNode<T, U> minimumNode() {
RedBlackNode<T, U> n = this;
while (!n.left.isNil()) {
n = n.left;
}
return n;
}
/**
* Searches the subtree rooted at this node for the node with the
* maximum {@link Interval}.
*
* @return the node with the maximum interval, if it exists; otherwise
* the sentinel node
*/
protected RedBlackNode<T, U> maximumNode() {
RedBlackNode<T, U> n = this;
while (!n.right.isNil()) {
n = n.right;
}
return n;
}
/**
* Returns whether this node is the root of its tree.
*
* @return <code>true</code> if this node is the root
*/
public boolean isRoot() {
return (!isNil() && parent.isNil());
}
/**
* Returns whether this node is the sentinel node.
*
* @return <code>true</code> if this node is the sentinel node
*/
public boolean isNil() {
return this == nil();
}
/**
* Returns whether this node is the left child of its parent.
*
* @return <code>true</code> if this node is a left child
*/
public boolean isLeftChild() {
return this == parent.left;
}
/**
* Returns whether this node is the right child of its parent.
*
* @return <code>true</code> if this node is a right child
*/
public boolean isRightChild() {
return this == parent.right;
}
/**
* Returns whether this node has no children, i.e., is a leaf.
*
* @return <code>true</code> if this node has no children
*/
public boolean hasNoChildren() {
return left.isNil() && right.isNil();
}
/**
* Returns whether or not this node has two children, i.e., neither of
* its children are leaves
*
* @return <code>true</code> if this node has two children
*/
public boolean hasTwoChildren() {
return !left.isNil() && !right.isNil();
}
/**
* Sets this node's color to black.
*/
protected void blacken() {
isBlack = true;
}
/**
* Sets this node's color to red.
*/
protected void redden() {
isBlack = false;
}
/**
* Returns if this node is red.
*
* @return if this node's color is red
*/
public boolean isRed() {
return !isBlack;
}
/**
* Returns this node's grandparent.
*
* @return a reference to the grandparent of this node
*/
protected RedBlackNode<T, U> grandparent() {
return parent.parent;
}
/**
* Resets the <code>maxEnd</code> field of this node to its correct
* value.
* <p>
* The value of the <code>maxEnd</code> field should be the greatest
* of:
* <ul>
* <li>the end value of this node's data
* <li>the <code>maxEnd</code> value of this node's left child, if not
* nil
* <li>the <code>maxEnd</code> value of this node's right child, if not
* nil
* </ul>
* <p>
* This method will be correct only if the left and right children have
* correct <code>maxEnd</code> values.
*/
protected void resetMaxEnd() {
int val = data.getEnd();
if (!left.isNil()) {
val = Math.max(val, left.maxEnd);
}
if (!right.isNil()) {
val = Math.max(val, right.maxEnd);
}
maxEnd = val;
}
/**
* Copies the data from another node into this node.
* <p>
* Technically, no copying occurs. This method just assigns a reference
* to the other node's data.
*
* @param o - the other node containing the data to be copied
*/
protected void copyData(RedBlackNode<T, U> o) {
data = o.data;
}
protected abstract RedBlackNode<T, U> nil();
protected abstract int size();
///////////////////////////////////////
// Node -- Overlapping query methods //
///////////////////////////////////////
/**
* Returns a node in this node's subtree that overlaps the given interval.
* <p>
* The only guarantee of this method is that the returned
* node overlaps the specified interval. This method is meant to be a
* quick helper method to determine if any overlap exists between an
* interval and any of a tree's intervals. The returned node will be
* the first overlapping one found.
*
* @param i - the overlapping interval
* @return a node from this node's subtree that overlaps the given
* interval, if one exists; otherwise the sentinel node
*/
protected RedBlackNode<T, U> anyOverlappingNode(Interval i) {
RedBlackNode<T, U> x = this;
while (!x.isNil() && !i.overlaps(x.data)) {
x = !x.left.isNil() && x.left.maxEnd > i.getStart() ? x.left : x.right;
}
return x;
}
/**
* Returns the minimum node in this node's subtree that overlaps the given
* interval.
*
* @param i - the specified interval
* @return the minimum node from this node's subtree that overlaps the
* given interval, if one exists; otherwise, the sentinel node
*/
RedBlackNode<T, U> minimumOverlappingNode(Interval i) {
RedBlackNode<T, U> result = nil();
RedBlackNode<T, U> n = this;
if (!n.isNil() && n.maxEnd > i.getStart()) {
while (true) {
if (n.overlaps(i)) {
// This node overlaps. There may be a lesser overlapper
// down the left subtree. No need to consider the right
// as all overlappers there will be greater.
result = n;
n = n.left;
if (n.isNil() || n.maxEnd <= i.getStart()) {
// Either no left subtree, or nodes can't overlap.
break;
}
} else {
// This node doesn't overlap.
// Check the left subtree if an overlapper may be there
RedBlackNode<T, U> left = n.left;
if (!left.isNil() && left.maxEnd > i.getStart()) {
n = left;
} else {
// Left subtree cannot contain an overlapper. Check the
// right sub-tree.
if (n.getStart() >= i.getEnd()) {
// Nothing in the right subtree can overlap
break;
}
n = n.right;
if (n.isNil() || n.maxEnd <= i.getStart()) {
// No right subtree, or nodes can't overlap.
break;
}
}
}
}
}
return result;
}
/**
* Returns the next node in this node's subtree that overlaps the given
* interval.
*
* @param i - the given interval
* @return the next node (relative to this node) that overlaps the
* given interval; if one does not exist, the sentinel node
*/
protected RedBlackNode<T, U> nextOverlappingNode(Interval i) {
RedBlackNode<T, U> x = this;
RedBlackNode<T, U> rtrn = nil();
// First, check the right subtree for its minimum overlapper.
if (!right.isNil()) {
rtrn = x.right.minimumOverlappingNode(i);
}
// If we didn't find it in the right subtree, walk up the tree and
// check the parents of left-children as well as their right subtrees.
while (!x.parent.isNil() && rtrn.isNil()) {
if (x.isLeftChild()) {
rtrn = x.parent.overlaps(i)
? x.parent
: x.parent.right.minimumOverlappingNode(i);
}
x = x.parent;
}
return rtrn;
}
/**
* Returns the number of nodes in this node's subtree that overlap the
* specified interval.
* <p>
* This number includes this node if it overlaps the interval. This
* method iterates over all overlapping nodes, so if you ultimately
* need to inspect the nodes or do anything more than get a count, it
* will be more efficient to simply create the iterator yourself with
* {@link Node#overlappers}.
*
* @param i - the specified interval
* @return the number of overlapping nodes
*/
protected abstract int numOverlappingNodes(Interval i);
/**
* @param i - the specified interval
* @return an iterator over all values in this node's subtree that
* overlap the specified interval
*/
protected abstract Iterator<T> overlappers(Interval i);
///////////////////////////////
// Node --<SUF>
///////////////////////////////
/**
* Returns <code>false</code> if any node in this node's subtree is less
* than its left child or greater than its right child.
* <p>
* Method for testing and debugging.
*
* @param min - a lower-bound node
* @param max - an upper-bound node
* @return whether or not the subtree rooted at this node is a valid
* binary-search tree
*/
protected boolean isBST(RedBlackNode<T, U> min, RedBlackNode<T, U> max) {
if (isNil()) {
return true; // Leaves are a valid BST, trivially.
}
if (min != null && compareTo(min) <= 0) {
return false; // This Node must be greater than min
}
if (max != null && compareTo(max) >= 0) {
return false; // and less than max.
}
// Children recursively call method with updated min/max.
return left.isBST(min, this) && right.isBST(this, max);
}
/**
* Returns <code>false</code> if all of the branches of this node's subtree
* (from root to leaf) do not contain the same number of black nodes.
* (Specifically, the black-number of each branch is compared against the
* black-number of the left-most branch.)
* <p>
* Method for testing and debugging.
* <p>
* Balance determination is done by calculating the black-height.
*
* @param black - the expected black-height of this subtree
* @returns whether or not the subtree rooted at this node is balanced.
*/
protected boolean isBalanced(int black) {
if (isNil()) {
return black == 0; // Leaves have a black-height of zero,
} // even though they are black.
if (isBlack) {
black--;
}
return left.isBalanced(black) && right.isBalanced(black);
}
/**
* Returns <code>true</code> if this node's subtree has a valid
* red-coloring.
* <p>
* Method for testing and debugging.
* <p>
* A red-black tree has a valid red-coloring if every red node has two
* black children. The sentinel node is black.
*
* @return whether or not the subtree rooted at this node has a valid
* red-coloring.
*/
protected boolean hasValidRedColoring() {
if (isNil()) {
return true;
} else if (isBlack) {
return left.hasValidRedColoring() &&
right.hasValidRedColoring();
} else {
return left.isBlack && right.isBlack &&
left.hasValidRedColoring() &&
right.hasValidRedColoring();
}
}
/**
* Returns <code>true</code> if each node in this node's subtree has a
* <code>maxEnd</code> value equal to the greatest interval end value of
* all the intervals in its subtree.
* <p>
* The <code>maxEnd</code> value of an interval-tree node is equal to
* the maximum of the end-values of all intervals contained in the
* node's subtree.
* <p>
* Method for testing and debugging.
*
* @return whether or not the constituent nodes of the subtree rooted
* at this node have consistent values for the <code>maxEnd</code>
* field.
*/
protected boolean hasConsistentMaxEnds() {
if (isNil()) { // 1. sentinel node
return true;
}
if (hasNoChildren()) { // 2. leaf node
return maxEnd == getEnd();
} else {
boolean consistent = maxEnd >= getEnd();
if (hasTwoChildren()) { // 3. two children
return consistent &&
maxEnd >= left.maxEnd &&
maxEnd >= right.maxEnd &&
left.hasConsistentMaxEnds() &&
right.hasConsistentMaxEnds();
} else if (left.isNil()) { // 4. one child -- right
return consistent &&
maxEnd >= right.maxEnd &&
right.hasConsistentMaxEnds();
} else {
return consistent && // 5. one child -- left
maxEnd >= left.maxEnd &&
left.hasConsistentMaxEnds();
}
}
}
/**
* Returns the string representation of this node.
* <p>
* The exact details of this representation are unspecified and subject to
* change, but it will typically contain information about this node's
* start and end values, as well as the values of its parent and children.
* <p>
* This method should be used solely for debugging and testing.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.isNil()) {
sb.append("this: nil\n");
} else {
sb.append("this: [" + getStart() + ", " + getEnd() + ")\n");
}
if (parent.isNil()) {
sb.append("parent: nil\n");
} else {
sb.append("parent: [" + parent.getStart() + ", " +
parent.getEnd() + ")\n");
}
if (left.isNil()) {
sb.append("left: nil\n");
} else {
sb.append("left: [" + left.getStart() + ", " +
left.getEnd() + ")\n");
}
if (right.isNil()) {
sb.append("right: nil\n");
} else {
sb.append("right: [" + left.getStart() + ", " +
right.getEnd() + ")\n");
}
return sb.toString();
}
@Override
public boolean equals(Object other) {
// No need for null check. The instanceof operator returns false
// if (other == null).
if (!(other instanceof RedBlackNode<?, ?>)) {
return false;
}
RedBlackNode<?, ?> o = (RedBlackNode<?, ?>) other;
return data.equals(o.data) &&
isBlack == o.isBlack &&
maxEnd == o.maxEnd &&
parent == o.parent &&
left == o.left &&
right == o.right;
}
@Override
public int hashCode() {
// TODO: What to do about node references? Does this even matter?
int result = 17;
result = 31 * result + data.hashCode();
result = 31 * result + (isBlack ? 1 : 0);
result = 31 * result + maxEnd;
return result;
}
}
|
59851_0 | package domein;
//Builder zou dit moeten noemen JapaneseMenuBuilder
public class JapaneseMenuBuilder extends MenuBuilder {
public void buildDrink() {
getMenu().setDrink("Sake");
}
public void buildMainCourse() {
getMenu().setMainCourse("Ramen");
}
public void buildSide() {
getMenu().setSide("Gyoza");
}
}
| GuusDb/ASDII | DesignPatterns/Builder/ASDII_MealAppStarter/src/domein/JapaneseMenuBuilder.java | 107 | //Builder zou dit moeten noemen JapaneseMenuBuilder | line_comment | nl | package domein;
//Builder zou<SUF>
public class JapaneseMenuBuilder extends MenuBuilder {
public void buildDrink() {
getMenu().setDrink("Sake");
}
public void buildMainCourse() {
getMenu().setMainCourse("Ramen");
}
public void buildSide() {
getMenu().setSide("Gyoza");
}
}
|
41417_2 | package domein;
import java.time.LocalDate;
import java.util.List;
public class BonController {
private ReductiebonBeheerder reductiebonBeheerder;
public BonController() {
reductiebonBeheerder = new ReductiebonBeheerder();
}
public void init() {
//versie A dient te werken
// reductiebonBeheerder.storeBon(new Reductiebon("kerstbon", 50, LocalDate.of(2021, 12, 10)));
// reductiebonBeheerder.storeBon(new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31)));
//versie B dient te werken
// List<Reductiebon> bonnen = List.of(new Reductiebon("kerstbon", 50, LocalDate.of(2021, 12, 10)),
// new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31)));
// reductiebonBeheerder.addReeks(bonnen);
//versie C dient te werken
List<Actiebon> bonnen = List.of(new Actiebon("Paasdagen", "paas", 50, LocalDate.of(2022, 4, 1)),
new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31)));
reductiebonBeheerder.addReeks(bonnen);
Reductiebon bon = reductiebonBeheerder.retrieveBon();
System.out.println(bon);
Reductiebon bon2 = reductiebonBeheerder.retrieveBon();
System.out.println(bon2);
}
} | GuusDb/javaASDoefs | java/herhalingsoefeningen/ASDI_Java_CollectionsOpstart_0_start1/src/domein/BonController.java | 471 | // reductiebonBeheerder.storeBon(new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31))); | line_comment | nl | package domein;
import java.time.LocalDate;
import java.util.List;
public class BonController {
private ReductiebonBeheerder reductiebonBeheerder;
public BonController() {
reductiebonBeheerder = new ReductiebonBeheerder();
}
public void init() {
//versie A dient te werken
// reductiebonBeheerder.storeBon(new Reductiebon("kerstbon", 50, LocalDate.of(2021, 12, 10)));
// reductiebonBeheerder.storeBon(new Actiebon("Kerstdagen",<SUF>
//versie B dient te werken
// List<Reductiebon> bonnen = List.of(new Reductiebon("kerstbon", 50, LocalDate.of(2021, 12, 10)),
// new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31)));
// reductiebonBeheerder.addReeks(bonnen);
//versie C dient te werken
List<Actiebon> bonnen = List.of(new Actiebon("Paasdagen", "paas", 50, LocalDate.of(2022, 4, 1)),
new Actiebon("Kerstdagen", "kerst", 15, LocalDate.of(2021, 12, 31)));
reductiebonBeheerder.addReeks(bonnen);
Reductiebon bon = reductiebonBeheerder.retrieveBon();
System.out.println(bon);
Reductiebon bon2 = reductiebonBeheerder.retrieveBon();
System.out.println(bon2);
}
} |
69785_29 | package callofcactus;
import callofcactus.account.Account;
import callofcactus.entities.*;
import callofcactus.entities.ai.AICharacter;
import callofcactus.entities.pickups.*;
import callofcactus.io.DatabaseManager;
import callofcactus.io.PropertyReader;
import callofcactus.map.MapFiles;
import callofcactus.multiplayer.Command;
import callofcactus.multiplayer.ServerS;
import callofcactus.role.Boss;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import org.json.JSONObject;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by guushamm on 16-11-15.
*/
public class MultiPlayerGame implements IGame {
//sets the pixels per steps that are taken with every calculation in calculateNewPosition
protected int steps = 1;
protected CopyOnWriteArrayList<Account> accountsInGame;
protected boolean bossModeActive;
protected int maxScore;
protected int maxNumberOfPlayers;
protected CopyOnWriteArrayList<NotMovingEntity> notMovingEntities;
protected CopyOnWriteArrayList<MovingEntity> movingEntities;
protected CopyOnWriteArrayList<HumanCharacter> players;
protected Vector2 mousePositions = new Vector2(0, 0);
protected PropertyReader propertyReader;
protected Intersector intersector;
protected int waveNumber = 0;
protected int deadPlayers;
// protected GameTexture textures;
protected Random random;
protected boolean godMode = false;
protected boolean muted = true;
protected DatabaseManager databaseManager;
protected boolean shouldEnd =false;
protected HashMap<InetAddress, Account> administraties = new HashMap<>();
// Tiled Map
private TiledMap tiledMap;
private MapLayer collisionLayer;
private ArrayList<MapObject> collisionObjects;
private int mapWidth;
private int mapHeight;
private final SpawnAlgorithm spawnAlgorithm;
public MultiPlayerGame() {
// TODO make this stuff dynamic via the db
this.maxNumberOfPlayers = 1;
this.bossModeActive = false;
this.maxScore = 100;
this.deadPlayers = 0;
this.players = new CopyOnWriteArrayList<>();
this.accountsInGame = new CopyOnWriteArrayList<>();
this.notMovingEntities = new CopyOnWriteArrayList<>();
this.movingEntities = new CopyOnWriteArrayList<>();
// this.textures = new GameTexture();
this.databaseManager = new DatabaseManager();
try {
this.propertyReader = new PropertyReader();
} catch (IOException e) {
e.printStackTrace();
}
this.intersector = new Intersector();
this.random = new Random();
// ServerS ss = new ServerS(this);
// ClientS s = new ClientS();
//s.sendMessage("playrandombulletsound");
//addSinglePlayerHumanCharacter();
// Tiled Map implementation
this.tiledMap = new TmxMapLoader(new InternalFileHandleResolver()).load(MapFiles.getFileName(MapFiles.MAPS.COMPLICATEDMAP));
// Set the layer you want entities to collide with
this.collisionLayer = tiledMap.getLayers().get("CollisionLayer");
// Get all the objects (walls) from the designated collision layer and add them to the arraylist
MapObjects mapObjects = collisionLayer.getObjects();
Iterator<MapObject> iterator = mapObjects.iterator();
this.collisionObjects = new ArrayList<>();
while (iterator.hasNext()) {
this.collisionObjects.add(iterator.next());
}
MapProperties prop = tiledMap.getProperties();
mapWidth = prop.get("width", Integer.class) * prop.get("tilewidth", Integer.class);
mapHeight = prop.get("height", Integer.class) * prop.get("tileheight", Integer.class);
spawnAlgorithm = new SpawnAlgorithm(this);
}
// public void addSinglePlayerHumanCharacter() {
// Player p = new HumanCharacter(this, new Vector2(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2), "CaptainCactus", new Sniper(), GameTexture.texturesEnum.playerTexture, 64, 26);
// this.players.add((HumanCharacter) p);
// }
public boolean getMuted() {
return muted;
}
public void setMuted(boolean muted) {
this.muted = muted;
}
public GameTexture getTextures() {
return null;
}
public void setMousePositions(int x, int y) {
this.mousePositions = new Vector2(x, y);
}
public JSONObject getJSON() {
return propertyReader.getJsonObject();
}
public CopyOnWriteArrayList<NotMovingEntity> getNotMovingEntities() {
return notMovingEntities;
}
public CopyOnWriteArrayList<HumanCharacter> getPlayers() {
return players;
}
public HumanCharacter getPlayer() {
return players.get(0);
}
public CopyOnWriteArrayList<MovingEntity> getMovingEntities() {
return movingEntities;
}
public Vector2 getMouse() {
float x = this.mousePositions.x;//Gdx.input.getX();
float y = this.mousePositions.y;// Gdx.input.getY();
return new Vector2(x, y);
}
public List<Entity> getAllEntities() {
List<Entity> result = new ArrayList<>();
result.addAll(notMovingEntities);
result.addAll(movingEntities);
return Collections.unmodifiableList(result);
}
public CopyOnWriteArrayList<Account> getAccountsInGame() {
return accountsInGame;
}
@Override
public void setAllEntities(List<Entity> entities) {
notMovingEntities.clear();
movingEntities.clear();
players.clear();
for (Entity e : entities) {
if (e instanceof NotMovingEntity) {
notMovingEntities.add((NotMovingEntity) e);
} else if (e instanceof HumanCharacter) {
players.add((HumanCharacter) e);
}
if (e instanceof MovingEntity) {
movingEntities.add((MovingEntity) e);
}
}
}
public void setAllAccounts() {
accountsInGame.clear();
for (HumanCharacter h : players) {
if (h.getAccount() != null)
{
accountsInGame.add(h.getAccount());
}
else {
System.out.println("MultiPlayerGame - SetAllAccounts :: Account from player is null!");
}
}
}
public void setAccountsInGame(CopyOnWriteArrayList<Account> accounts){
accountsInGame = accounts;
}
public boolean getGodMode() {
return this.godMode;
}
public void setGodMode(boolean godMode) {
this.godMode = godMode;
}
public int getWaveNumber() {
return this.waveNumber;
}
@Override
public int getMapWidth() {
return mapWidth;
}
@Override
public int getMapHeight() {
return mapHeight;
}
public DatabaseManager getDatabaseManager() {
return this.databaseManager;
}
/**
* Generates spawnvectors for every entity in the callofcactus that needs to be spawned.
* This includes players (both human and AI), bullets, pickups and all not-moving entities.
*
* @return the spawnvector for the selected entity
* @throws NoValidSpawnException Thrown when no valid spawn position has been found
*/
public Vector2 generateSpawn() throws NoValidSpawnException {
return spawnAlgorithm.findSpawnPosition();
}
/**
* Calculates the angle between two vectors
*
* @param beginVector : The vector that will be used as center
* @param endVector : Where the object has to point to
* @return Returns the angle, this will be between 0 and 360 degrees
*/
public int angle(Vector2 beginVector, Vector2 endVector) {
return (360 - (int) Math.toDegrees(Math.atan2(endVector.y - beginVector.y, endVector.x - beginVector.x))) % 360;
}
/**
* Calculates the new position between the currentPosition to the Endposition.
*
* @param currentPosition : The current position of the object
* @param EndPosition : The position of the end point
* @param speed : The speed that the object can move with
* @return the new position that has been calculated
*/
public Vector2 calculateNewPosition(Vector2 currentPosition, Vector2 EndPosition, double speed) {
float x = currentPosition.x;
float y = currentPosition.y;
//gets the difference of the two x coordinates
double differenceX = EndPosition.x - x;
//gets the difference of the two y coordinates
double differenceY = EndPosition.y - y;
//pythagoras formula
double c = Math.sqrt(Math.pow(Math.abs(differenceX), 2) + Math.pow(Math.abs(differenceY), 2));
if (c <= (steps * speed)) {
return EndPosition;
}
double ratio = c / (steps * speed);
x += (differenceX / ratio);
y += (differenceY / ratio);
return new Vector2(x, y);
}
/**
* Calculates the new position from a beginposition and a angle..
*
* @param currentPosition : The current position of the object
* @param speed : The speed that the object can move with
* @param angle : The angle of where the object should be heading
* @return the new position that has been calculated
*/
public Vector2 calculateNewPosition(Vector2 currentPosition, double speed, double angle) {
double newAngle = angle + 90f;
double x = currentPosition.x;
double y = currentPosition.y;
//uses sin and cos to calculate the EndPosition
x = x + (Math.sin(Math.toRadians(newAngle)) * (steps * speed));
y = y + (Math.cos(Math.toRadians(newAngle)) * (steps * speed));
float xF = Float.parseFloat(Double.toString(x));
float yF = Float.parseFloat(Double.toString(y));
return new Vector2(xF, yF);
}
/**
* Called when an entity needs to be added to the callofcactus (Only in the memory, but it is not actually drawn)
*
* @param entity : Entity that should be added to the callofcactus
*/
// public void addEntityToGame(Entity entity) {
//
// if (entity.getID() == -1) {
// entity.setID(Entity.getNxtID(),false);
// if(entity instanceof HumanCharacter){
// entity.setID(1000 + Entity.getNxtID(), false);
// }
// }
// if (entity instanceof MovingEntity) {
// movingEntities.add((MovingEntity) entity);
// if (entity instanceof HumanCharacter) System.out.println("add human");
// } else {
// notMovingEntities.add((NotMovingEntity) entity);
// }
// }
public void addEntityToGame(Entity entity) {
if (entity.getID() == 0 || entity.getID() == -1) {
entity.setID(Entity.getNxtID(), false);
}
if (entity instanceof MovingEntity) {
movingEntities.add((MovingEntity) entity);
} else {
notMovingEntities.add((NotMovingEntity) entity);
}
// System.out.println("My ideeee is : "+entity.getID());
if(entity instanceof HumanCharacter) {
try {
entity.setLocation(generateSpawn(), true);
} catch (NoValidSpawnException e) {
e.printStackTrace();
}
}
}
/**
* Called when an entity needs to be added to the callofcactus (Only in the memory, but it is not actually drawn)
*
* @param entity : Entity that should be added to the callofcactus
*/
public int addEntityToGameWithIDReturn(Entity entity) {
if (entity.getID() == 0 || entity.getID() == -1) {
entity.setID(Entity.getNxtID(), false);
}
if (entity instanceof MovingEntity) {
movingEntities.add((MovingEntity) entity);
} else {
notMovingEntities.add((NotMovingEntity) entity);
}
// System.out.println("My ideeee is : "+entity.getID());
if(entity instanceof HumanCharacter) {
try {
entity.setLocation(generateSpawn(), true);
} catch (NoValidSpawnException e) {
e.printStackTrace();
}
}
return entity.getID();
}
public void removeEntityFromGame(Entity entity) {
if (entity instanceof MovingEntity) {
movingEntities.remove(entity);
if (entity instanceof HumanCharacter)
System.out.println("remove human");
// TODO change end callofcactus condition for iteration 2 of the callofcactus
} else if (entity instanceof NotMovingEntity) {
notMovingEntities.remove(entity);
}
}
public void createPickup() {
int i = (int) (Math.random() * 5);
Pickup pickup = null;
if (i == 0) {
pickup = new DamagePickup(this, new Vector2(1, 1), GameTexture.texturesEnum.damagePickupTexture, 50, 40, true);
} else if (i == 1) {
pickup = new HealthPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.healthPickupTexture, 35, 17, true);
} else if (i == 2) {
pickup = new SpeedPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.speedPickupTexture, 40, 40, true);
} else if (i == 3) {
pickup = new AmmoPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.bulletTexture, 30, 30, true);
} else if (i == 4) {
pickup = new FireRatePickup(this, new Vector2(1, 1), GameTexture.texturesEnum.fireRatePickupTexture, 30, 40, true);
}
try {
pickup.setLocation(generateSpawn(),true);
} catch (Exception e) {
e.printStackTrace();
}
}
public long secondsToMillis(int seconds) {
return seconds * 1000;
}
/**
* This method checks every entity in callofcactus if two hitboxes overlap, if they do the appropriate action will be taken.
* This method has reached far beyond what should be asked of a single method but it works.
* Follow the comments on its threaturous path and you will succes in finding what you seek.
* This should also be ported to callofcactus in the next itteration.
*/
public void compareHit() {
//Gets all the entities to check
List<Entity> entities = this.getAllEntities();
//A list to put the to remove entities in so they won't be deleted mid-loop.
List<Entity> toRemoveEntities = new ArrayList<>();
//A if to make sure the player is correctly checked in the list of entities
for (HumanCharacter h : players) {
if (!entities.contains(h)) {
addEntityToGame(h);
}
}
//starts a loop of entities that than creates a loop to compare the entity[i] to entity[n]
//n = i+1 to prevent double checking of entities.
//Example:
// entity[1] == entity[2] will be checked
// entity[2] == entity[1] will not be checked
//this could be shorter by checking both
//instead of the ifs but this will be re-evaluated once past the first iteration
for (int i = 0; i < entities.size(); i++) {
//gets the first entity to compare to
Entity a = entities.get(i);
checkTiledMapCollision(a, toRemoveEntities);
for (int n = i + 1; n < entities.size(); n++) {
//gets the second entity to compare to
Entity b = entities.get(n);
//Checks if the hitbox of entity a overlaps with the hitbox of entity b, for the hitboxes we chose to use rectangles
if (a.getHitBox().overlaps(b.getHitBox())) {
//Every check needs to be checked twice for a and b and the other way around to
// make sure everything gets checked.
if (!checkBullet(a, b)) continue;
if (!checkBullet(b, a)) continue;
checkHumanCharacterAndAI(a, b, toRemoveEntities);
checkHumanCharacterAndAI(b, a, toRemoveEntities);
checkPickupAndHumanCharacter(a, b, toRemoveEntities);
checkPickupAndHumanCharacter(b, a, toRemoveEntities);
// checkNotMovingEntity(a, b, toRemoveEntities);
// checkNotMovingEntity(b, a, toRemoveEntities);
}
}
}
//This will destroy all the entities that will need to be destroyed for the previous checks.
//this needs to be outside of the loop because you can't delete objects in a list while you're
//working with the list
for (Entity entity : toRemoveEntities){
entity.destroy();
}
// toRemoveEntities.forEach(Entity::destroy);
}
private void checkTiledMapCollision(Entity a, List<Entity> toRemoveEntities)
{
for (MapObject collisionObject : collisionObjects) {
Rectangle wallHitbox;
if (collisionObject instanceof RectangleMapObject) {
Rectangle entityHitbox = a.getHitBox();
wallHitbox = ((RectangleMapObject) collisionObject).getRectangle();
if (entityHitbox.overlaps(wallHitbox)) {
if (a instanceof MovingEntity) {
if (a instanceof Bullet) {
toRemoveEntities.add(a);
return;
}
a.setToLastLocation(a.getLastLocation(),true);
return;
}
else {
toRemoveEntities.add(a);
return;
}
}
}
else {
System.out.println("Map object instance isn't a rectangle map object");
}
}
}
/**
* Executes actions that need to be executed if a bullet collides with something
*
* @param a
* @param b
* @return
*/
private boolean checkBullet(Entity a, Entity b) {
if (a instanceof Bullet) {
boolean sendBossMode = false;
boolean isBoss = false;
if (b instanceof Pickup && !((Pickup) b).isSolid())
return false;
//makes it so your own bullets wont destroy eachother
if (b instanceof Bullet && ((Bullet) a).getShooter().getID() == (((Bullet) b).getShooter().getID()))
return false;
//if b is the shooter of bullet a then continue to the next check.
//because friendly fire is off standard
if (b instanceof HumanCharacter && ((Bullet) a).getShooter().getID() == b.getID())
return false;
//if the bullet hit something the bullet will disapear by taking damage (this is standard behaviour for bullet.takedamage())
// and the other entity will take the damage of the bullet.
//Bullet bulletACopy = (Bullet) a;
//a.takeDamage(1, true);
if (b instanceof AICharacter) {
((AICharacter) b).takeDamage(b.getDamage(), (HumanCharacter) ((Bullet) a).getShooter());
}
else {
Entity bCopy = b;
if (b instanceof HumanCharacter) {
if (((HumanCharacter) b).getRole() instanceof Boss) {
isBoss = true;
}
if (bossModeActive) {
if (!((HumanCharacter) b).getRole().toString().matches(((Bullet) a).getShooter().getRole().toString())) {
b.takeDamage(a.getDamage(), true);
}
}
else {
b.takeDamage(a.getDamage(), true);
}
}
//Check if a Bullet hits an enemy
if (b instanceof HumanCharacter) {
//Check if the health is less or equal to zero.
if (((HumanCharacter) b).getHealth() <= 0) {
try{
checkBossMode((HumanCharacter) bCopy);
}
catch(NullPointerException e){
System.out.println("No player found");
}
//Add a kill to the person who shot the Bullet
if (((Bullet) a).getShooter() instanceof HumanCharacter) {
try{
HumanCharacter h = this.searchPlayer(((Bullet) a).getShooter().getID());
Account account = h.getAccount();
h.addKill(true);
if (bossModeActive) {
deadPlayers++;
if (checkEnd(deadPlayers)){
return true;
}
}
if (isBoss) {
endGame();
}
//Check for becoming boss
if (account != null) {
if (account.getKillCount() >= account.getKillToBecomeBoss() && account.getCanBecomeBoss()) {
h.becomeBoss();
bossModeActive = true;
sendBossMode = true;
for (HumanCharacter hm : players) {
hm.getAccount().setCanBecomeBoss(false);
}
}
}
}
catch(NullPointerException e){
System.out.println("No player found");
}
}
}
}
}
a.takeDamage(1, true);
//playRandomHitSound();
if (sendBossMode) {
ServerS.getInstance().sendMessagePush(new Command(-22, "bossModeActive", "true", Command.objectEnum.bossModeActive));
}
}
return true;
}
public boolean checkEnd(int deadPlayerss) {
if (accountsInGame.size() - 1 == deadPlayerss) {
endGame();
return true;
}
return false;
}
private void checkHumanCharacterAndAI(Entity a, Entity b, List<Entity> toRemoveEntities) {
//Check collision between AI and player
if (a instanceof HumanCharacter && b instanceof AICharacter) {
if (!this.getGodMode()) {
System.out.println("B: " + b.getDamage() + "; " + b.toString());
a.takeDamage(b.getDamage(), true);
}
toRemoveEntities.add(b);
if (!getMuted()) {
playRandomHitSound();
}
}
}
public void checkPickupAndHumanCharacter(Entity a, Entity b, List<Entity> toRemoveEntities) {
if (a instanceof HumanCharacter && b instanceof Pickup) {
((HumanCharacter) a).setCurrentPickup((Pickup) b);
toRemoveEntities.add(b);
if (!getMuted()) {
playRandomHitSound();
}
}
}
public void checkNotMovingEntity(Entity a, Entity b, List<Entity> toRemoveEntities) {
if (a instanceof Pickup && !((Pickup) a).isSolid()) {
return;
}
//checks if a MovingEntity has collided with a NotMovingEntity
//if so, the current location will be set to the previous location
if (a instanceof NotMovingEntity && ((NotMovingEntity) a).isSolid() && b instanceof MovingEntity) {
b.setLocation(b.getLastLocation(),true);
}
}
public synchronized void playRandomHitSound() {
return;
}
public synchronized void playRandomBulletSound() {
return;
}
@Override
public ArrayList<MapObject> getCollisionObjects()
{
return this.collisionObjects;
}
public HumanCharacter searchPlayer(int id) {
setAllEntities(getAllEntities());
for (HumanCharacter p : players) {
if (p.getID() == id) {
HumanCharacter player = p;
return player;
}
}
return null;
}
public void respawnAllPlayers() {
//This method will be called when the Boss is defeated.
for (Account a : accountsInGame) {
//Respawn all dead players
if (a.getIsDead()) {
//TODO respawn player
}
//Set the value they need to become boss, and make it so they can become the boss
a.setKillToBecomeBoss();
a.setCanBecomeBoss(true);
}
}
/**
* This method will send a message to the client which corresponds with Account 'a'.
* The message is essentially an indicator, telling the client to start the respawn cycle.
* The client will then wait several seconds before calling Administration.addSinglePlayerHumanCharacter.
*
* @param a
*/
public void respawnPlayer(Account a){
System.out.println("Starting respawn cycle for player " + a.getUsername());
}
public void checkBossMode(HumanCharacter h) {
//Check if BossMode active is.
if (!bossModeActive) {
//TODO respawn player
}
else {
h.getAccount().setIsDead(true);
}
//Check if the person who died is the Boss
if (h.getRole() instanceof Boss) {
shouldEnd = true;
//TODO grab the original Role that the player was
respawnAllPlayers();
bossModeActive = false;
ServerS.getInstance().sendMessagePush(new Command(-22, "bossModeActive", "false", Command.objectEnum.bossModeActive));
for (HumanCharacter hm : players) {
hm.getAccount().setCanBecomeBoss(true);
}
}
}
// public void becomeBoss(HumanCharacter h) {
// //Stuur message
// Command c = new Command(h.getID(), "role", "Boss", Command.objectEnum.HumanCharacter);
// ServerS.getInstance().sendMessagePush(c);
//
// h.destroy();
// }
public void endGame(){
//When the game ended
DatabaseManager databaseManager = getDatabaseManager();
int matchID = databaseManager.getNextGameID();
databaseManager.addPlayerMatch();
for (Account account : accountsInGame){
int accountID = databaseManager.getAccountID(account.getUsername());
System.out.println("Putting Account: " + account.getUsername() + "; With MatchID: " + matchID);
databaseManager.addMultiplayerResult(accountID, matchID, account.getScore(), account.getKillCount(), account.getDeathCount());
account.resetKillDeath();
}
Command command = new Command(-20, "matchID", String.valueOf(matchID), Command.objectEnum.MatchID);
ServerS.getInstance().sendMessagePush(command);
}
public void removeEntitybyID(int ID){
int accountID = -1;
for(Entity e : movingEntities){
if(e.getID() == ID){
accountID = ((HumanCharacter)e).getAccount().getID();
movingEntities.remove(e);
players.remove(e);
}
}
for(Account a : accountsInGame){
if(a.getID() == accountID){
accountsInGame.remove(a);
}
}
}
}
| GuusHamm/Call-of-Cactus | src/main/java/callofcactus/MultiPlayerGame.java | 7,776 | // System.out.println("My ideeee is : "+entity.getID()); | line_comment | nl | package callofcactus;
import callofcactus.account.Account;
import callofcactus.entities.*;
import callofcactus.entities.ai.AICharacter;
import callofcactus.entities.pickups.*;
import callofcactus.io.DatabaseManager;
import callofcactus.io.PropertyReader;
import callofcactus.map.MapFiles;
import callofcactus.multiplayer.Command;
import callofcactus.multiplayer.ServerS;
import callofcactus.role.Boss;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import org.json.JSONObject;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by guushamm on 16-11-15.
*/
public class MultiPlayerGame implements IGame {
//sets the pixels per steps that are taken with every calculation in calculateNewPosition
protected int steps = 1;
protected CopyOnWriteArrayList<Account> accountsInGame;
protected boolean bossModeActive;
protected int maxScore;
protected int maxNumberOfPlayers;
protected CopyOnWriteArrayList<NotMovingEntity> notMovingEntities;
protected CopyOnWriteArrayList<MovingEntity> movingEntities;
protected CopyOnWriteArrayList<HumanCharacter> players;
protected Vector2 mousePositions = new Vector2(0, 0);
protected PropertyReader propertyReader;
protected Intersector intersector;
protected int waveNumber = 0;
protected int deadPlayers;
// protected GameTexture textures;
protected Random random;
protected boolean godMode = false;
protected boolean muted = true;
protected DatabaseManager databaseManager;
protected boolean shouldEnd =false;
protected HashMap<InetAddress, Account> administraties = new HashMap<>();
// Tiled Map
private TiledMap tiledMap;
private MapLayer collisionLayer;
private ArrayList<MapObject> collisionObjects;
private int mapWidth;
private int mapHeight;
private final SpawnAlgorithm spawnAlgorithm;
public MultiPlayerGame() {
// TODO make this stuff dynamic via the db
this.maxNumberOfPlayers = 1;
this.bossModeActive = false;
this.maxScore = 100;
this.deadPlayers = 0;
this.players = new CopyOnWriteArrayList<>();
this.accountsInGame = new CopyOnWriteArrayList<>();
this.notMovingEntities = new CopyOnWriteArrayList<>();
this.movingEntities = new CopyOnWriteArrayList<>();
// this.textures = new GameTexture();
this.databaseManager = new DatabaseManager();
try {
this.propertyReader = new PropertyReader();
} catch (IOException e) {
e.printStackTrace();
}
this.intersector = new Intersector();
this.random = new Random();
// ServerS ss = new ServerS(this);
// ClientS s = new ClientS();
//s.sendMessage("playrandombulletsound");
//addSinglePlayerHumanCharacter();
// Tiled Map implementation
this.tiledMap = new TmxMapLoader(new InternalFileHandleResolver()).load(MapFiles.getFileName(MapFiles.MAPS.COMPLICATEDMAP));
// Set the layer you want entities to collide with
this.collisionLayer = tiledMap.getLayers().get("CollisionLayer");
// Get all the objects (walls) from the designated collision layer and add them to the arraylist
MapObjects mapObjects = collisionLayer.getObjects();
Iterator<MapObject> iterator = mapObjects.iterator();
this.collisionObjects = new ArrayList<>();
while (iterator.hasNext()) {
this.collisionObjects.add(iterator.next());
}
MapProperties prop = tiledMap.getProperties();
mapWidth = prop.get("width", Integer.class) * prop.get("tilewidth", Integer.class);
mapHeight = prop.get("height", Integer.class) * prop.get("tileheight", Integer.class);
spawnAlgorithm = new SpawnAlgorithm(this);
}
// public void addSinglePlayerHumanCharacter() {
// Player p = new HumanCharacter(this, new Vector2(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2), "CaptainCactus", new Sniper(), GameTexture.texturesEnum.playerTexture, 64, 26);
// this.players.add((HumanCharacter) p);
// }
public boolean getMuted() {
return muted;
}
public void setMuted(boolean muted) {
this.muted = muted;
}
public GameTexture getTextures() {
return null;
}
public void setMousePositions(int x, int y) {
this.mousePositions = new Vector2(x, y);
}
public JSONObject getJSON() {
return propertyReader.getJsonObject();
}
public CopyOnWriteArrayList<NotMovingEntity> getNotMovingEntities() {
return notMovingEntities;
}
public CopyOnWriteArrayList<HumanCharacter> getPlayers() {
return players;
}
public HumanCharacter getPlayer() {
return players.get(0);
}
public CopyOnWriteArrayList<MovingEntity> getMovingEntities() {
return movingEntities;
}
public Vector2 getMouse() {
float x = this.mousePositions.x;//Gdx.input.getX();
float y = this.mousePositions.y;// Gdx.input.getY();
return new Vector2(x, y);
}
public List<Entity> getAllEntities() {
List<Entity> result = new ArrayList<>();
result.addAll(notMovingEntities);
result.addAll(movingEntities);
return Collections.unmodifiableList(result);
}
public CopyOnWriteArrayList<Account> getAccountsInGame() {
return accountsInGame;
}
@Override
public void setAllEntities(List<Entity> entities) {
notMovingEntities.clear();
movingEntities.clear();
players.clear();
for (Entity e : entities) {
if (e instanceof NotMovingEntity) {
notMovingEntities.add((NotMovingEntity) e);
} else if (e instanceof HumanCharacter) {
players.add((HumanCharacter) e);
}
if (e instanceof MovingEntity) {
movingEntities.add((MovingEntity) e);
}
}
}
public void setAllAccounts() {
accountsInGame.clear();
for (HumanCharacter h : players) {
if (h.getAccount() != null)
{
accountsInGame.add(h.getAccount());
}
else {
System.out.println("MultiPlayerGame - SetAllAccounts :: Account from player is null!");
}
}
}
public void setAccountsInGame(CopyOnWriteArrayList<Account> accounts){
accountsInGame = accounts;
}
public boolean getGodMode() {
return this.godMode;
}
public void setGodMode(boolean godMode) {
this.godMode = godMode;
}
public int getWaveNumber() {
return this.waveNumber;
}
@Override
public int getMapWidth() {
return mapWidth;
}
@Override
public int getMapHeight() {
return mapHeight;
}
public DatabaseManager getDatabaseManager() {
return this.databaseManager;
}
/**
* Generates spawnvectors for every entity in the callofcactus that needs to be spawned.
* This includes players (both human and AI), bullets, pickups and all not-moving entities.
*
* @return the spawnvector for the selected entity
* @throws NoValidSpawnException Thrown when no valid spawn position has been found
*/
public Vector2 generateSpawn() throws NoValidSpawnException {
return spawnAlgorithm.findSpawnPosition();
}
/**
* Calculates the angle between two vectors
*
* @param beginVector : The vector that will be used as center
* @param endVector : Where the object has to point to
* @return Returns the angle, this will be between 0 and 360 degrees
*/
public int angle(Vector2 beginVector, Vector2 endVector) {
return (360 - (int) Math.toDegrees(Math.atan2(endVector.y - beginVector.y, endVector.x - beginVector.x))) % 360;
}
/**
* Calculates the new position between the currentPosition to the Endposition.
*
* @param currentPosition : The current position of the object
* @param EndPosition : The position of the end point
* @param speed : The speed that the object can move with
* @return the new position that has been calculated
*/
public Vector2 calculateNewPosition(Vector2 currentPosition, Vector2 EndPosition, double speed) {
float x = currentPosition.x;
float y = currentPosition.y;
//gets the difference of the two x coordinates
double differenceX = EndPosition.x - x;
//gets the difference of the two y coordinates
double differenceY = EndPosition.y - y;
//pythagoras formula
double c = Math.sqrt(Math.pow(Math.abs(differenceX), 2) + Math.pow(Math.abs(differenceY), 2));
if (c <= (steps * speed)) {
return EndPosition;
}
double ratio = c / (steps * speed);
x += (differenceX / ratio);
y += (differenceY / ratio);
return new Vector2(x, y);
}
/**
* Calculates the new position from a beginposition and a angle..
*
* @param currentPosition : The current position of the object
* @param speed : The speed that the object can move with
* @param angle : The angle of where the object should be heading
* @return the new position that has been calculated
*/
public Vector2 calculateNewPosition(Vector2 currentPosition, double speed, double angle) {
double newAngle = angle + 90f;
double x = currentPosition.x;
double y = currentPosition.y;
//uses sin and cos to calculate the EndPosition
x = x + (Math.sin(Math.toRadians(newAngle)) * (steps * speed));
y = y + (Math.cos(Math.toRadians(newAngle)) * (steps * speed));
float xF = Float.parseFloat(Double.toString(x));
float yF = Float.parseFloat(Double.toString(y));
return new Vector2(xF, yF);
}
/**
* Called when an entity needs to be added to the callofcactus (Only in the memory, but it is not actually drawn)
*
* @param entity : Entity that should be added to the callofcactus
*/
// public void addEntityToGame(Entity entity) {
//
// if (entity.getID() == -1) {
// entity.setID(Entity.getNxtID(),false);
// if(entity instanceof HumanCharacter){
// entity.setID(1000 + Entity.getNxtID(), false);
// }
// }
// if (entity instanceof MovingEntity) {
// movingEntities.add((MovingEntity) entity);
// if (entity instanceof HumanCharacter) System.out.println("add human");
// } else {
// notMovingEntities.add((NotMovingEntity) entity);
// }
// }
public void addEntityToGame(Entity entity) {
if (entity.getID() == 0 || entity.getID() == -1) {
entity.setID(Entity.getNxtID(), false);
}
if (entity instanceof MovingEntity) {
movingEntities.add((MovingEntity) entity);
} else {
notMovingEntities.add((NotMovingEntity) entity);
}
// System.out.println("My ideeee is : "+entity.getID());
if(entity instanceof HumanCharacter) {
try {
entity.setLocation(generateSpawn(), true);
} catch (NoValidSpawnException e) {
e.printStackTrace();
}
}
}
/**
* Called when an entity needs to be added to the callofcactus (Only in the memory, but it is not actually drawn)
*
* @param entity : Entity that should be added to the callofcactus
*/
public int addEntityToGameWithIDReturn(Entity entity) {
if (entity.getID() == 0 || entity.getID() == -1) {
entity.setID(Entity.getNxtID(), false);
}
if (entity instanceof MovingEntity) {
movingEntities.add((MovingEntity) entity);
} else {
notMovingEntities.add((NotMovingEntity) entity);
}
// System.out.println("My ideeee<SUF>
if(entity instanceof HumanCharacter) {
try {
entity.setLocation(generateSpawn(), true);
} catch (NoValidSpawnException e) {
e.printStackTrace();
}
}
return entity.getID();
}
public void removeEntityFromGame(Entity entity) {
if (entity instanceof MovingEntity) {
movingEntities.remove(entity);
if (entity instanceof HumanCharacter)
System.out.println("remove human");
// TODO change end callofcactus condition for iteration 2 of the callofcactus
} else if (entity instanceof NotMovingEntity) {
notMovingEntities.remove(entity);
}
}
public void createPickup() {
int i = (int) (Math.random() * 5);
Pickup pickup = null;
if (i == 0) {
pickup = new DamagePickup(this, new Vector2(1, 1), GameTexture.texturesEnum.damagePickupTexture, 50, 40, true);
} else if (i == 1) {
pickup = new HealthPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.healthPickupTexture, 35, 17, true);
} else if (i == 2) {
pickup = new SpeedPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.speedPickupTexture, 40, 40, true);
} else if (i == 3) {
pickup = new AmmoPickup(this, new Vector2(1, 1), GameTexture.texturesEnum.bulletTexture, 30, 30, true);
} else if (i == 4) {
pickup = new FireRatePickup(this, new Vector2(1, 1), GameTexture.texturesEnum.fireRatePickupTexture, 30, 40, true);
}
try {
pickup.setLocation(generateSpawn(),true);
} catch (Exception e) {
e.printStackTrace();
}
}
public long secondsToMillis(int seconds) {
return seconds * 1000;
}
/**
* This method checks every entity in callofcactus if two hitboxes overlap, if they do the appropriate action will be taken.
* This method has reached far beyond what should be asked of a single method but it works.
* Follow the comments on its threaturous path and you will succes in finding what you seek.
* This should also be ported to callofcactus in the next itteration.
*/
public void compareHit() {
//Gets all the entities to check
List<Entity> entities = this.getAllEntities();
//A list to put the to remove entities in so they won't be deleted mid-loop.
List<Entity> toRemoveEntities = new ArrayList<>();
//A if to make sure the player is correctly checked in the list of entities
for (HumanCharacter h : players) {
if (!entities.contains(h)) {
addEntityToGame(h);
}
}
//starts a loop of entities that than creates a loop to compare the entity[i] to entity[n]
//n = i+1 to prevent double checking of entities.
//Example:
// entity[1] == entity[2] will be checked
// entity[2] == entity[1] will not be checked
//this could be shorter by checking both
//instead of the ifs but this will be re-evaluated once past the first iteration
for (int i = 0; i < entities.size(); i++) {
//gets the first entity to compare to
Entity a = entities.get(i);
checkTiledMapCollision(a, toRemoveEntities);
for (int n = i + 1; n < entities.size(); n++) {
//gets the second entity to compare to
Entity b = entities.get(n);
//Checks if the hitbox of entity a overlaps with the hitbox of entity b, for the hitboxes we chose to use rectangles
if (a.getHitBox().overlaps(b.getHitBox())) {
//Every check needs to be checked twice for a and b and the other way around to
// make sure everything gets checked.
if (!checkBullet(a, b)) continue;
if (!checkBullet(b, a)) continue;
checkHumanCharacterAndAI(a, b, toRemoveEntities);
checkHumanCharacterAndAI(b, a, toRemoveEntities);
checkPickupAndHumanCharacter(a, b, toRemoveEntities);
checkPickupAndHumanCharacter(b, a, toRemoveEntities);
// checkNotMovingEntity(a, b, toRemoveEntities);
// checkNotMovingEntity(b, a, toRemoveEntities);
}
}
}
//This will destroy all the entities that will need to be destroyed for the previous checks.
//this needs to be outside of the loop because you can't delete objects in a list while you're
//working with the list
for (Entity entity : toRemoveEntities){
entity.destroy();
}
// toRemoveEntities.forEach(Entity::destroy);
}
private void checkTiledMapCollision(Entity a, List<Entity> toRemoveEntities)
{
for (MapObject collisionObject : collisionObjects) {
Rectangle wallHitbox;
if (collisionObject instanceof RectangleMapObject) {
Rectangle entityHitbox = a.getHitBox();
wallHitbox = ((RectangleMapObject) collisionObject).getRectangle();
if (entityHitbox.overlaps(wallHitbox)) {
if (a instanceof MovingEntity) {
if (a instanceof Bullet) {
toRemoveEntities.add(a);
return;
}
a.setToLastLocation(a.getLastLocation(),true);
return;
}
else {
toRemoveEntities.add(a);
return;
}
}
}
else {
System.out.println("Map object instance isn't a rectangle map object");
}
}
}
/**
* Executes actions that need to be executed if a bullet collides with something
*
* @param a
* @param b
* @return
*/
private boolean checkBullet(Entity a, Entity b) {
if (a instanceof Bullet) {
boolean sendBossMode = false;
boolean isBoss = false;
if (b instanceof Pickup && !((Pickup) b).isSolid())
return false;
//makes it so your own bullets wont destroy eachother
if (b instanceof Bullet && ((Bullet) a).getShooter().getID() == (((Bullet) b).getShooter().getID()))
return false;
//if b is the shooter of bullet a then continue to the next check.
//because friendly fire is off standard
if (b instanceof HumanCharacter && ((Bullet) a).getShooter().getID() == b.getID())
return false;
//if the bullet hit something the bullet will disapear by taking damage (this is standard behaviour for bullet.takedamage())
// and the other entity will take the damage of the bullet.
//Bullet bulletACopy = (Bullet) a;
//a.takeDamage(1, true);
if (b instanceof AICharacter) {
((AICharacter) b).takeDamage(b.getDamage(), (HumanCharacter) ((Bullet) a).getShooter());
}
else {
Entity bCopy = b;
if (b instanceof HumanCharacter) {
if (((HumanCharacter) b).getRole() instanceof Boss) {
isBoss = true;
}
if (bossModeActive) {
if (!((HumanCharacter) b).getRole().toString().matches(((Bullet) a).getShooter().getRole().toString())) {
b.takeDamage(a.getDamage(), true);
}
}
else {
b.takeDamage(a.getDamage(), true);
}
}
//Check if a Bullet hits an enemy
if (b instanceof HumanCharacter) {
//Check if the health is less or equal to zero.
if (((HumanCharacter) b).getHealth() <= 0) {
try{
checkBossMode((HumanCharacter) bCopy);
}
catch(NullPointerException e){
System.out.println("No player found");
}
//Add a kill to the person who shot the Bullet
if (((Bullet) a).getShooter() instanceof HumanCharacter) {
try{
HumanCharacter h = this.searchPlayer(((Bullet) a).getShooter().getID());
Account account = h.getAccount();
h.addKill(true);
if (bossModeActive) {
deadPlayers++;
if (checkEnd(deadPlayers)){
return true;
}
}
if (isBoss) {
endGame();
}
//Check for becoming boss
if (account != null) {
if (account.getKillCount() >= account.getKillToBecomeBoss() && account.getCanBecomeBoss()) {
h.becomeBoss();
bossModeActive = true;
sendBossMode = true;
for (HumanCharacter hm : players) {
hm.getAccount().setCanBecomeBoss(false);
}
}
}
}
catch(NullPointerException e){
System.out.println("No player found");
}
}
}
}
}
a.takeDamage(1, true);
//playRandomHitSound();
if (sendBossMode) {
ServerS.getInstance().sendMessagePush(new Command(-22, "bossModeActive", "true", Command.objectEnum.bossModeActive));
}
}
return true;
}
public boolean checkEnd(int deadPlayerss) {
if (accountsInGame.size() - 1 == deadPlayerss) {
endGame();
return true;
}
return false;
}
private void checkHumanCharacterAndAI(Entity a, Entity b, List<Entity> toRemoveEntities) {
//Check collision between AI and player
if (a instanceof HumanCharacter && b instanceof AICharacter) {
if (!this.getGodMode()) {
System.out.println("B: " + b.getDamage() + "; " + b.toString());
a.takeDamage(b.getDamage(), true);
}
toRemoveEntities.add(b);
if (!getMuted()) {
playRandomHitSound();
}
}
}
public void checkPickupAndHumanCharacter(Entity a, Entity b, List<Entity> toRemoveEntities) {
if (a instanceof HumanCharacter && b instanceof Pickup) {
((HumanCharacter) a).setCurrentPickup((Pickup) b);
toRemoveEntities.add(b);
if (!getMuted()) {
playRandomHitSound();
}
}
}
public void checkNotMovingEntity(Entity a, Entity b, List<Entity> toRemoveEntities) {
if (a instanceof Pickup && !((Pickup) a).isSolid()) {
return;
}
//checks if a MovingEntity has collided with a NotMovingEntity
//if so, the current location will be set to the previous location
if (a instanceof NotMovingEntity && ((NotMovingEntity) a).isSolid() && b instanceof MovingEntity) {
b.setLocation(b.getLastLocation(),true);
}
}
public synchronized void playRandomHitSound() {
return;
}
public synchronized void playRandomBulletSound() {
return;
}
@Override
public ArrayList<MapObject> getCollisionObjects()
{
return this.collisionObjects;
}
public HumanCharacter searchPlayer(int id) {
setAllEntities(getAllEntities());
for (HumanCharacter p : players) {
if (p.getID() == id) {
HumanCharacter player = p;
return player;
}
}
return null;
}
public void respawnAllPlayers() {
//This method will be called when the Boss is defeated.
for (Account a : accountsInGame) {
//Respawn all dead players
if (a.getIsDead()) {
//TODO respawn player
}
//Set the value they need to become boss, and make it so they can become the boss
a.setKillToBecomeBoss();
a.setCanBecomeBoss(true);
}
}
/**
* This method will send a message to the client which corresponds with Account 'a'.
* The message is essentially an indicator, telling the client to start the respawn cycle.
* The client will then wait several seconds before calling Administration.addSinglePlayerHumanCharacter.
*
* @param a
*/
public void respawnPlayer(Account a){
System.out.println("Starting respawn cycle for player " + a.getUsername());
}
public void checkBossMode(HumanCharacter h) {
//Check if BossMode active is.
if (!bossModeActive) {
//TODO respawn player
}
else {
h.getAccount().setIsDead(true);
}
//Check if the person who died is the Boss
if (h.getRole() instanceof Boss) {
shouldEnd = true;
//TODO grab the original Role that the player was
respawnAllPlayers();
bossModeActive = false;
ServerS.getInstance().sendMessagePush(new Command(-22, "bossModeActive", "false", Command.objectEnum.bossModeActive));
for (HumanCharacter hm : players) {
hm.getAccount().setCanBecomeBoss(true);
}
}
}
// public void becomeBoss(HumanCharacter h) {
// //Stuur message
// Command c = new Command(h.getID(), "role", "Boss", Command.objectEnum.HumanCharacter);
// ServerS.getInstance().sendMessagePush(c);
//
// h.destroy();
// }
public void endGame(){
//When the game ended
DatabaseManager databaseManager = getDatabaseManager();
int matchID = databaseManager.getNextGameID();
databaseManager.addPlayerMatch();
for (Account account : accountsInGame){
int accountID = databaseManager.getAccountID(account.getUsername());
System.out.println("Putting Account: " + account.getUsername() + "; With MatchID: " + matchID);
databaseManager.addMultiplayerResult(accountID, matchID, account.getScore(), account.getKillCount(), account.getDeathCount());
account.resetKillDeath();
}
Command command = new Command(-20, "matchID", String.valueOf(matchID), Command.objectEnum.MatchID);
ServerS.getInstance().sendMessagePush(command);
}
public void removeEntitybyID(int ID){
int accountID = -1;
for(Entity e : movingEntities){
if(e.getID() == ID){
accountID = ((HumanCharacter)e).getAccount().getID();
movingEntities.remove(e);
players.remove(e);
}
}
for(Account a : accountsInGame){
if(a.getID() == accountID){
accountsInGame.remove(a);
}
}
}
}
|
43016_2 | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) 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 FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. 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 OWNER 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 org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
| Guusje2/FTCUnits-SkyStone | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/CraterSide.java | 3,502 | //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen | line_comment | nl | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) 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 FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. 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 OWNER 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 org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten<SUF>
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
|
186117_0 | package com.example.bilabonnement.utility;
public class TerminalInfo {
/**
* Fik ideen fra anden klasse studerende!
* @author Ian(DatJustino)
*/
public static void printToConsole(){
String terminal = "\nDevelopers: \nDaniel Dam, \nIan Justino, \nMikas Baiocchi, \nVeronica Frydkjær \n\n" +
"hjemmeside/Login: http://localhost:8080\n" +
"damagereport: http://localhost:8080/damage-reports\n" +
"LeasingContracts: http://localhost:8080/create-lease-contract\n" +
"Business: http://localhost:8080/business-developer\n\n\n";
System.out.println(terminal);
}
}
| GuyKawaii/bilabonnement | src/main/java/com/example/bilabonnement/utility/TerminalInfo.java | 223 | /**
* Fik ideen fra anden klasse studerende!
* @author Ian(DatJustino)
*/ | block_comment | nl | package com.example.bilabonnement.utility;
public class TerminalInfo {
/**
* Fik ideen fra<SUF>*/
public static void printToConsole(){
String terminal = "\nDevelopers: \nDaniel Dam, \nIan Justino, \nMikas Baiocchi, \nVeronica Frydkjær \n\n" +
"hjemmeside/Login: http://localhost:8080\n" +
"damagereport: http://localhost:8080/damage-reports\n" +
"LeasingContracts: http://localhost:8080/create-lease-contract\n" +
"Business: http://localhost:8080/business-developer\n\n\n";
System.out.println(terminal);
}
}
|
30873_10 | package be.pxl.streams;
import be.pxl.streams.Person.Gender;
import java.util.Arrays;
import java.util.List;
public class Challenge4 {
public static void main(String[] args) {
List<Person> personen = Arrays.asList(
new Person("Sofie", 23, Gender.FEMALE),
new Person("Adam", 31, Gender.MALE),
new Person("Bastiaan", 25, Gender.MALE),
new Person("Berend", 22, Gender.MALE),
new Person("Aagje", 27, Gender.FEMALE)
);
// 1. Geef de gemiddelde leeftijd van alle personen
// Verwachte output: Gemiddelde leeftijd: 25.6
System.out.println("Gemiddelde leeftijd: " + personen.stream().mapToInt(a -> a.getAge()).average().getAsDouble());
// 2. Hoeveel mannen staan er in de lijst
// Verwachte output: Aantal mannen: 3
System.out.println("Aantal mannen: " + personen.stream().filter(s -> s.getGender().equals(Gender.MALE)).count());
// 3. Hoeveel mannen ouder dan 24 staan er in de lijst
// Verwachte output: Aantal mannen boven 24: 2
System.out.println("Aantal mannen boven 24: " + personen.stream().filter(s -> s.getAge() > 24 && s.getGender().equals(Gender.MALE)).count());
// 4. Geef de gemiddelde leeftijd van alle mannen
// Gemiddelde leeftijd mannen: 26.0
System.out.println("Gemiddelde leeftijd mannen: " + personen.stream().filter(s -> s.getGender().equals(Gender.MALE)).mapToInt(s -> s.getAge()).average().getAsDouble());
// 5. Maak een nieuwe persoon met als naam de eerste letter van iedere persoon in de lijst
// en als leeftijd de som van alle leeftijden
// Maak gebruik van de methode .reduce()
Person apple = new Person("klok", personen.stream().mapToInt(s -> s.getAge()).sum(), Gender.MALE);
personen.add(apple);
}
}
| GwenNijssen/week5-streams | src/be/pxl/streams/Challenge4.java | 616 | // Maak gebruik van de methode .reduce() | line_comment | nl | package be.pxl.streams;
import be.pxl.streams.Person.Gender;
import java.util.Arrays;
import java.util.List;
public class Challenge4 {
public static void main(String[] args) {
List<Person> personen = Arrays.asList(
new Person("Sofie", 23, Gender.FEMALE),
new Person("Adam", 31, Gender.MALE),
new Person("Bastiaan", 25, Gender.MALE),
new Person("Berend", 22, Gender.MALE),
new Person("Aagje", 27, Gender.FEMALE)
);
// 1. Geef de gemiddelde leeftijd van alle personen
// Verwachte output: Gemiddelde leeftijd: 25.6
System.out.println("Gemiddelde leeftijd: " + personen.stream().mapToInt(a -> a.getAge()).average().getAsDouble());
// 2. Hoeveel mannen staan er in de lijst
// Verwachte output: Aantal mannen: 3
System.out.println("Aantal mannen: " + personen.stream().filter(s -> s.getGender().equals(Gender.MALE)).count());
// 3. Hoeveel mannen ouder dan 24 staan er in de lijst
// Verwachte output: Aantal mannen boven 24: 2
System.out.println("Aantal mannen boven 24: " + personen.stream().filter(s -> s.getAge() > 24 && s.getGender().equals(Gender.MALE)).count());
// 4. Geef de gemiddelde leeftijd van alle mannen
// Gemiddelde leeftijd mannen: 26.0
System.out.println("Gemiddelde leeftijd mannen: " + personen.stream().filter(s -> s.getGender().equals(Gender.MALE)).mapToInt(s -> s.getAge()).average().getAsDouble());
// 5. Maak een nieuwe persoon met als naam de eerste letter van iedere persoon in de lijst
// en als leeftijd de som van alle leeftijden
// Maak gebruik<SUF>
Person apple = new Person("klok", personen.stream().mapToInt(s -> s.getAge()).sum(), Gender.MALE);
personen.add(apple);
}
}
|
66596_3 | package Testate;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private static char _scPlayfield = '-',
_scPlayer1 = 'x',
_scPlayer2 = 'o';
/**
* @param args
*/
public static void main(String[] args) {
// --| Deklaration |--
int iStars = 20;
char[][] aPlayfield = new char[3][3];
String sInput;
Scanner oScanner = new Scanner(System.in);
Random oRandom = new Random();
// Start-Meldung ausgeben
TicTacToe.outputStardEnd(iStars, "Start");
// --| TicTacToe ausführen |--
while (true) {
// --| TicTacToe starten |--
TicTacToe.startGame(aPlayfield, oScanner, oRandom);
// Abfragen ob der User noch eine Runde spielen möchte
System.out.print("\nWollen Sie noch eine Runde spielen [y/Y]?");
sInput = oScanner.nextLine();
// User möchte noch eine Runde spielen.
// Neues Spiel starten
if (sInput.contains("y") || sInput.contains("Y")) {
System.out.print("\n\n\n\n\n");
continue;
}
// Schleife verlassen und Logik beenden
break;
}
// End-Meldung ausgeben
TicTacToe.outputStardEnd(iStars, "Ende");
oScanner.close();
}
/**
* Start/End Meldung ausgeben
*
* @param iStars
* @param sMessage
*/
private static void outputStardEnd(int iStars, String sMessage) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < iStars; j++) {
System.out.print("*");
}
System.out.print(sMessage);
sMessage = "";
}
System.out.print("\n");
}
/**
* TicTacToe-Spiel starten
* 1. Spielfeld initialisieren und ausgeben
* 2. Abfragen ob der Anwender gegen den Rechner spielen möchte
* 3. Spielernamen auslesen
* 4. Eingaben auslesen und validieren
* 5. Rechner Koordinaten berechnen lassen
* 6. Koordinaten setzen
* 7. Spielfeld ausgeben
* 8. Prüfen ob der aktuelle Spieler gewonnen hat
*
* @param aPlayfield
* @param oScanner
* @param oRandom
*/
private static void startGame(char[][] aPlayfield, Scanner oScanner, Random oRandom) {
// --| Deklaration |--
int iStartIndex;
char cTurnChar;
boolean bPCTurn = false,
bPlayAgainstPC = false;
String sInput,
sCurrPlayer,
sPlayer1,
sPlayer2 = "PC";
// --| Spielfeld initialiseren und ausgeben |--
TicTacToe.printArray2(aPlayfield, true);
/*
* Abfragen ob der User gegen den Rechner spielen möchte oder
* gegen einen weiteren "echten" Menschen
*/
System.out.print("Wollen Sie gegen den Rechner spielen [y/Y]?");
sInput = oScanner.nextLine();
bPlayAgainstPC = (sInput.contains("y") || sInput.contains("Y") ? true : false);
// Namen für Spieler 1 auslesen
System.out.print("Erfassen Sie den Namen des ersten Spielers: ");
sPlayer1 = oScanner.nextLine();
/*
* Es wird nicht gegen den Rechner gespielt
* -> Namen für den zweiten Spieler auslesen
*/
if (!bPlayAgainstPC) {
System.out.print("Erfassen Sie den Namen für den zweiten Spieler: ");
sPlayer2 = oScanner.nextLine();
}
// Start-Spieler Random bestimmen
iStartIndex = oRandom.nextInt(0,2);
// --| Ein Spiel kann max. 9 Runden dauern (3x3) |--
for (int i = 0; i < 9; i++) {
/*
* 1. Setzen des aktuellen Spielers + dessen Spielzeichen
* 2. Setzen ob der Rechner an der Reihe ist
*/
if (iStartIndex % 2 == 0) {
sCurrPlayer = sPlayer1;
cTurnChar = _scPlayer1;
bPCTurn = false;
} else {
sCurrPlayer = sPlayer2;
cTurnChar = _scPlayer2;
bPCTurn = bPlayAgainstPC;
}
/*
* 1. User ist am Zug
* 2.1 Eingabe aus der Konsole auslesen
* 2.2 Eingabe validieren
* 2.3 Koordinaten belegen
* 3. Rechner ist am Zug
* 3.1 Prüfen ob der Rechner gewinnen kann
* 3.2 Prüfen ob der Gegener gewinnen kann
* 3.3 Random eine freie Koordinate ermitteln
* 3.4 Koordinaten belegen
* 4. Koordinaten im Spielfeld setzen
*/
TicTacToe.setTurn(bPCTurn, sCurrPlayer, cTurnChar, aPlayfield, oScanner, oRandom);
// Spielfeld ausgeben
TicTacToe.printArray2(aPlayfield, false);
// --| Prüfen ob der aktuelle Spieler gewonnen hat |--
if (TicTacToe.checkWin(cTurnChar, sCurrPlayer, aPlayfield)) {
break;
}
// --| Unentschieden, keiner hat verloren |--
if ((i + 1) == 9) {
System.out.println("Unentschieden!");
}
iStartIndex++;
}
}
/**
* Spielzug des Rechners
* 1. Prüfen ob Rechner gewinnen kann
* -> Koordinaten belegen
* 2. Prüfen ob Gegner gewinnen könnte
* -> Koordinaten belegen
* 3. Zufällige freie Koordinate im Spielfeld ermitteln
*
* @param cTurnChar
* @param sPlayer
* @param aPlayfield
* @param oRandom
* @return
*/
private static int[] pcTurn(char cTurnChar, String sPlayer, char[][] aPlayfield, Random oRandom) {
// --| Deklaration |--
int iIndex = 0;
int[] aAvailRow = null,
aAvailColumn = null,
aCoordinate = null;
/*
* 1. Durchlauf:
* Prüfen ob Rechner gewinnen kann
* -> Koordinaten belgen
* 2. Durchlauf:
* Prüfen ob Gegner gewinnen kann
* -> Koordinaten belegen
*/
for (int i = 0; i < 2; i++) {
aCoordinate = TicTacToe.checkWinLose(cTurnChar, (i == 0 ? true : false), aPlayfield);
// Schleife verlassen, da Koordinaten ermittelt wurden
if (aCoordinate != null) {
break;
}
}
// --| Ermittlung der freien Koordinaten auf dem Spielfeld |--
if (aCoordinate == null) {
aCoordinate = new int[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < aPlayfield.length; i++) {
for (int j = 0; j < aPlayfield[i].length; j++) {
if (aPlayfield[i][j] == _scPlayfield) {
if (k > 0) {
aAvailRow[iIndex] = (i + 1);
aAvailColumn[iIndex] = (j + 1);
}
iIndex++;
}
}
}
// Arrays erzeugen und Index zurücksetzen für zweiten durchlauf
if (k == 0) {
aAvailRow = new int[iIndex];
aAvailColumn = new int[iIndex];
iIndex = 0;
}
}
// Koordinaten zufällig bestimmen
iIndex = oRandom.nextInt(0, aAvailRow.length);
aCoordinate[0] = aAvailRow[iIndex];
aCoordinate[1] = aAvailColumn[iIndex];
}
System.out.println(sPlayer + " - hat folgende Koordinaten gewählt [Zeile,Spalte]: " + aCoordinate[0] + ","
+ aCoordinate[1]);
return aCoordinate;
}
/**
* Ermittlung der Koordinaten für den Sieg des Rechners
* bzw. um den Sieg des Gegners zu verhindern
*
* @param cTurnChar
* @param bTryToWin
* @param aPlayfield
* @return
*/
private static int[] checkWinLose(char cTurnChar, boolean bTryToWin, char[][] aPlayfield) {
// --| Deklaration |--
int iXY;
char cTurn = (cTurnChar == _scPlayer1 ? _scPlayer2 : _scPlayer1);
int[] aCoordinate = new int[2];
// --| Horizontale, vertikale und schräge Siege (verhindern) |--
try {
cTurn = (bTryToWin ? cTurnChar : cTurn);
for (int i = 0; i < aPlayfield.length; i++) {
iXY = (i + 1);
// Horizontalen Sieg (verhindern) -> |x|x|-|
if (aPlayfield[i][0] == cTurn && aPlayfield[i][1] == cTurn
&& aPlayfield[i][2] == _scPlayfield) {
aCoordinate[0] = iXY;
aCoordinate[1] = 3;
throw new Exception();
}
// Horizontalen Sieg (verhindern) -> |-|x|x|
else if (aPlayfield[i][0] == _scPlayfield && aPlayfield[i][1] == cTurn
&& aPlayfield[i][2] == cTurn) {
aCoordinate[0] = iXY;
aCoordinate[1] = 1;
throw new Exception();
}
// Horizontaler Sieg (verhindern) -> |x|-|x|
else if (aPlayfield[i][0] == cTurn && aPlayfield[i][1] == _scPlayfield
&& aPlayfield[i][2] == cTurn) {
aCoordinate[0] = iXY;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |x|
* |x|
* |-|
*/
else if (aPlayfield[0][i] == cTurn && aPlayfield[1][i] == cTurn
&& aPlayfield[2][i] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = iXY;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |-|
* |x|
* |x|
*/
else if (aPlayfield[0][i] == _scPlayfield && aPlayfield[1][i] == cTurn
&& aPlayfield[2][i] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = iXY;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |x|
* |-|
* |x|
*/
else if (aPlayfield[0][i] == cTurn && aPlayfield[1][i] == _scPlayfield
&& aPlayfield[2][i] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = iXY;
throw new Exception();
}
}
/*
* Schrägen Sieg (verhindern):
* |x|
* |-|x|
* |-|-|-|
*/
if (aPlayfield[0][0] == cTurn && aPlayfield[1][1] == cTurn && aPlayfield[2][2] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = 3;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|
* |-|x|
* |-|-|x|
*/
else if (aPlayfield[0][0] == _scPlayfield && aPlayfield[1][1] == cTurn
&& aPlayfield[2][2] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = 1;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |x|
* |-|-|
* |-|-|x|
*/
else if (aPlayfield[0][0] == cTurn && aPlayfield[1][1] == _scPlayfield
&& aPlayfield[2][2] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|x|
* |-|x|
* |-|
*/
else if (aPlayfield[0][2] == cTurn && aPlayfield[1][1] == cTurn
&& aPlayfield[2][0] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = 1;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|-|
* |-|x|
* |x|
*/
else if (aPlayfield[0][2] == _scPlayfield && aPlayfield[1][1] == cTurn
&& aPlayfield[2][0] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = 3;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|x|
* |-|-|
* |x|
*/
else if (aPlayfield[0][2] == cTurn && aPlayfield[1][1] == _scPlayfield
&& aPlayfield[2][0] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Es muss noch kein Sieg verhindert werden
* -> Koordinaten-Array auf null setzen
*/
aCoordinate = null;
} catch (Exception e) {
}
return aCoordinate;
}
/**
* Prüfungen durchführen, ob der aktuelle Spieler gewonnen hat:
* 1. Horizontal gewonnen
* 2. Vertikal gewonnen
* 3. Schräg gewonnen
*
* @param cTurnChar
* @param sPlayer
* @param aPlayfield
* @return
*/
private static boolean checkWin(char cTurnChar, String sPlayer, char[][] aPlayfield) {
// --| Deklaration |--
String sWinOutput = sPlayer + " hat";
boolean bWin = false;
// --| Überprüfung ob der aktuelle Spieler gewonnen hat |--
for (int i = 0; i < aPlayfield.length; i++) {
// Horrizontal gewonnen
if (aPlayfield[i][0] == cTurnChar && aPlayfield[i][1] == cTurnChar && aPlayfield[i][2] == cTurnChar) {
bWin = true;
sWinOutput = sWinOutput + " horizontal gewonnen!";
break;
}
// Vertikal gewonnen
if (aPlayfield[0][i] == cTurnChar && aPlayfield[1][i] == cTurnChar && aPlayfield[2][i] == cTurnChar) {
bWin = true;
sWinOutput = sWinOutput + " vertikal gewonnen!";
break;
}
}
// Schräg gewonnen
if ((aPlayfield[0][0] == cTurnChar && aPlayfield[1][1] == cTurnChar && aPlayfield[2][2] == cTurnChar)
|| (aPlayfield[0][2] == cTurnChar && aPlayfield[1][1] == cTurnChar && aPlayfield[2][0] == cTurnChar)) {
bWin = true;
sWinOutput = sWinOutput + " schräg gewonnen!";
}
// Aktueller Spieler hat gewonnen!
if (bWin) {
System.out.println(sWinOutput);
}
return bWin;
}
/**
* Spielzug durchführen
* Unterscheidung zwischen:
* - Spielzug eines Menschen
* - Spielzug des Rechners
*
* @param bPCTurn
* @param sPlayer
* @param cTurnChar
* @param aPlayfield
* @param aCoordinate
* @param oScanner
* @param oRandom
*/
private static void setTurn(boolean bPCTurn, String sPlayer, char cTurnChar, char[][] aPlayfield,
Scanner oScanner, Random oRandom) {
// --| Deklaration |--
int[] aCoordinate;
// --| Eingabe aus der Konsole auslesen und validieren |--
if (!bPCTurn) {
aCoordinate = TicTacToe.getInput(sPlayer, aPlayfield, oScanner);
}
// --| PC hat sich Koordinaten ausgewählt |--
else {
aCoordinate = TicTacToe.pcTurn(cTurnChar, sPlayer, aPlayfield, oRandom);
}
// Koordinaten setzen
aPlayfield[(aCoordinate[0] - 1)][(aCoordinate[1] - 1)] = cTurnChar;
}
/**
* Konsolen-Eingabe des Users auslesen und validieren
*
* @param sPlayer
* @param aPlayfield
* @param aCoordinate
* @param oScanner
*/
private static int[] getInput(String sPlayer, char[][] aPlayfield, Scanner oScanner) {
// --| Deklaration |--
String sInput;
int[] aCoordinate;
// --| Eingabe aus der Konsole lesen |--
while (true) {
try {
System.out.print(
sPlayer + " - Koordinaten (1-3) im folgenden Format erfassen [Zeile,Spalte]: ");
sInput = oScanner.nextLine();
// Eingabe bei dem Zeichen ',' aufsplitten und dem
// int-Array zuweisen
try {
aCoordinate = Arrays.stream(sInput.split(",")).mapToInt(Integer::parseInt).toArray();
} catch (NumberFormatException eConvError) {
throw new Exception("Eingabe war kein numerischer Wert!");
}
// Eingabe hat das falsche Format gehabt!
if (aCoordinate.length < 2 || aCoordinate.length > 2) {
throw new Exception("Bitte folgendes Format beachten [Zeile,Spalte].");
}
/*
* Eingabe wird auf folgendes überprüft:
* 1. Liegt die Eingabe für die Zeile im Wertebereich 1-3
* 2. Liegt die Eingabe für die Spalte im Wertebereich 1-3
* 3. Sind die erfassten Koordinaten bereits belegt?
*/
TicTacToe.validateTurn(aPlayfield, aCoordinate);
break;
} catch (Exception eError) {
System.out.println("****************************************************");
System.out.println("ERROR !!! -> " + eError.getMessage());
System.out.println("****************************************************\n");
}
}
return aCoordinate;
}
/**
* Eingabe wird auf folgendes überprüft:
* 1. Liegt die Eingabe für die Zeile im Wertebereich 1-3
* 2. Liegt die Eingabe für die Spalte im Wertebereich 1-3
* 3. Sind die erfassten Koordinaten bereits belegt?
*
* @param aPlayfield
* @param iRow
* @param iColumn
* @throws Exception
*/
private static void validateTurn(char[][] aPlayfield, int[] aCoordinate) throws Exception {
// Zeileneingabe liegt nicht im Wertebereich 1-3
if (aCoordinate[0] <= 0 || aCoordinate[0] > 3) {
throw new Exception("Eingabe Zeile (Wert: " + aCoordinate[0] + ") liegt nicht im Bereich 1-3.");
}
// Spalteneingabe liegt nicht im Wertebereich 1-3
if (aCoordinate[1] <= 0 || aCoordinate[1] > 3) {
throw new Exception("Eingabe Spalte (Wert: " + aCoordinate[1] + ") liegt nicht im Bereich 1-3.");
}
// Erfasste Koordinaten sind bereits belegt
if (aPlayfield[(aCoordinate[0] - 1)][(aCoordinate[1] - 1)] != _scPlayfield) {
throw new Exception("Koordinaten sind bereits belegt!");
}
}
/**
* Gebe das TicTacToe-Spielfeld aus
* -> bCreateField == true -> Spielfeld wird erstellt
*
* @param aPlayfield
* @param bCreateField
*/
private static void printArray2(char[][] aPlayfield, boolean bCreateField) {
// Spielfeld ausgeben
for (int i = 0; i < aPlayfield.length; i++) {
for (int j = 0; j < aPlayfield[i].length; j++) {
// Kenner gesetzt, dass das Spielfeld initialisiert wurde
aPlayfield[i][j] = (bCreateField == true ? aPlayfield[i][j] = _scPlayfield : aPlayfield[i][j]);
System.out.print("|" + aPlayfield[i][j]);
}
System.out.println("|");
}
System.out.print("\n");
}
} | Gwengal/Grundlagen_der_Programmierung | src/Testate/TicTacToe.java | 6,278 | // --| TicTacToe starten |-- | line_comment | nl | package Testate;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private static char _scPlayfield = '-',
_scPlayer1 = 'x',
_scPlayer2 = 'o';
/**
* @param args
*/
public static void main(String[] args) {
// --| Deklaration |--
int iStars = 20;
char[][] aPlayfield = new char[3][3];
String sInput;
Scanner oScanner = new Scanner(System.in);
Random oRandom = new Random();
// Start-Meldung ausgeben
TicTacToe.outputStardEnd(iStars, "Start");
// --| TicTacToe ausführen |--
while (true) {
// --| TicTacToe<SUF>
TicTacToe.startGame(aPlayfield, oScanner, oRandom);
// Abfragen ob der User noch eine Runde spielen möchte
System.out.print("\nWollen Sie noch eine Runde spielen [y/Y]?");
sInput = oScanner.nextLine();
// User möchte noch eine Runde spielen.
// Neues Spiel starten
if (sInput.contains("y") || sInput.contains("Y")) {
System.out.print("\n\n\n\n\n");
continue;
}
// Schleife verlassen und Logik beenden
break;
}
// End-Meldung ausgeben
TicTacToe.outputStardEnd(iStars, "Ende");
oScanner.close();
}
/**
* Start/End Meldung ausgeben
*
* @param iStars
* @param sMessage
*/
private static void outputStardEnd(int iStars, String sMessage) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < iStars; j++) {
System.out.print("*");
}
System.out.print(sMessage);
sMessage = "";
}
System.out.print("\n");
}
/**
* TicTacToe-Spiel starten
* 1. Spielfeld initialisieren und ausgeben
* 2. Abfragen ob der Anwender gegen den Rechner spielen möchte
* 3. Spielernamen auslesen
* 4. Eingaben auslesen und validieren
* 5. Rechner Koordinaten berechnen lassen
* 6. Koordinaten setzen
* 7. Spielfeld ausgeben
* 8. Prüfen ob der aktuelle Spieler gewonnen hat
*
* @param aPlayfield
* @param oScanner
* @param oRandom
*/
private static void startGame(char[][] aPlayfield, Scanner oScanner, Random oRandom) {
// --| Deklaration |--
int iStartIndex;
char cTurnChar;
boolean bPCTurn = false,
bPlayAgainstPC = false;
String sInput,
sCurrPlayer,
sPlayer1,
sPlayer2 = "PC";
// --| Spielfeld initialiseren und ausgeben |--
TicTacToe.printArray2(aPlayfield, true);
/*
* Abfragen ob der User gegen den Rechner spielen möchte oder
* gegen einen weiteren "echten" Menschen
*/
System.out.print("Wollen Sie gegen den Rechner spielen [y/Y]?");
sInput = oScanner.nextLine();
bPlayAgainstPC = (sInput.contains("y") || sInput.contains("Y") ? true : false);
// Namen für Spieler 1 auslesen
System.out.print("Erfassen Sie den Namen des ersten Spielers: ");
sPlayer1 = oScanner.nextLine();
/*
* Es wird nicht gegen den Rechner gespielt
* -> Namen für den zweiten Spieler auslesen
*/
if (!bPlayAgainstPC) {
System.out.print("Erfassen Sie den Namen für den zweiten Spieler: ");
sPlayer2 = oScanner.nextLine();
}
// Start-Spieler Random bestimmen
iStartIndex = oRandom.nextInt(0,2);
// --| Ein Spiel kann max. 9 Runden dauern (3x3) |--
for (int i = 0; i < 9; i++) {
/*
* 1. Setzen des aktuellen Spielers + dessen Spielzeichen
* 2. Setzen ob der Rechner an der Reihe ist
*/
if (iStartIndex % 2 == 0) {
sCurrPlayer = sPlayer1;
cTurnChar = _scPlayer1;
bPCTurn = false;
} else {
sCurrPlayer = sPlayer2;
cTurnChar = _scPlayer2;
bPCTurn = bPlayAgainstPC;
}
/*
* 1. User ist am Zug
* 2.1 Eingabe aus der Konsole auslesen
* 2.2 Eingabe validieren
* 2.3 Koordinaten belegen
* 3. Rechner ist am Zug
* 3.1 Prüfen ob der Rechner gewinnen kann
* 3.2 Prüfen ob der Gegener gewinnen kann
* 3.3 Random eine freie Koordinate ermitteln
* 3.4 Koordinaten belegen
* 4. Koordinaten im Spielfeld setzen
*/
TicTacToe.setTurn(bPCTurn, sCurrPlayer, cTurnChar, aPlayfield, oScanner, oRandom);
// Spielfeld ausgeben
TicTacToe.printArray2(aPlayfield, false);
// --| Prüfen ob der aktuelle Spieler gewonnen hat |--
if (TicTacToe.checkWin(cTurnChar, sCurrPlayer, aPlayfield)) {
break;
}
// --| Unentschieden, keiner hat verloren |--
if ((i + 1) == 9) {
System.out.println("Unentschieden!");
}
iStartIndex++;
}
}
/**
* Spielzug des Rechners
* 1. Prüfen ob Rechner gewinnen kann
* -> Koordinaten belegen
* 2. Prüfen ob Gegner gewinnen könnte
* -> Koordinaten belegen
* 3. Zufällige freie Koordinate im Spielfeld ermitteln
*
* @param cTurnChar
* @param sPlayer
* @param aPlayfield
* @param oRandom
* @return
*/
private static int[] pcTurn(char cTurnChar, String sPlayer, char[][] aPlayfield, Random oRandom) {
// --| Deklaration |--
int iIndex = 0;
int[] aAvailRow = null,
aAvailColumn = null,
aCoordinate = null;
/*
* 1. Durchlauf:
* Prüfen ob Rechner gewinnen kann
* -> Koordinaten belgen
* 2. Durchlauf:
* Prüfen ob Gegner gewinnen kann
* -> Koordinaten belegen
*/
for (int i = 0; i < 2; i++) {
aCoordinate = TicTacToe.checkWinLose(cTurnChar, (i == 0 ? true : false), aPlayfield);
// Schleife verlassen, da Koordinaten ermittelt wurden
if (aCoordinate != null) {
break;
}
}
// --| Ermittlung der freien Koordinaten auf dem Spielfeld |--
if (aCoordinate == null) {
aCoordinate = new int[2];
for (int k = 0; k < 2; k++) {
for (int i = 0; i < aPlayfield.length; i++) {
for (int j = 0; j < aPlayfield[i].length; j++) {
if (aPlayfield[i][j] == _scPlayfield) {
if (k > 0) {
aAvailRow[iIndex] = (i + 1);
aAvailColumn[iIndex] = (j + 1);
}
iIndex++;
}
}
}
// Arrays erzeugen und Index zurücksetzen für zweiten durchlauf
if (k == 0) {
aAvailRow = new int[iIndex];
aAvailColumn = new int[iIndex];
iIndex = 0;
}
}
// Koordinaten zufällig bestimmen
iIndex = oRandom.nextInt(0, aAvailRow.length);
aCoordinate[0] = aAvailRow[iIndex];
aCoordinate[1] = aAvailColumn[iIndex];
}
System.out.println(sPlayer + " - hat folgende Koordinaten gewählt [Zeile,Spalte]: " + aCoordinate[0] + ","
+ aCoordinate[1]);
return aCoordinate;
}
/**
* Ermittlung der Koordinaten für den Sieg des Rechners
* bzw. um den Sieg des Gegners zu verhindern
*
* @param cTurnChar
* @param bTryToWin
* @param aPlayfield
* @return
*/
private static int[] checkWinLose(char cTurnChar, boolean bTryToWin, char[][] aPlayfield) {
// --| Deklaration |--
int iXY;
char cTurn = (cTurnChar == _scPlayer1 ? _scPlayer2 : _scPlayer1);
int[] aCoordinate = new int[2];
// --| Horizontale, vertikale und schräge Siege (verhindern) |--
try {
cTurn = (bTryToWin ? cTurnChar : cTurn);
for (int i = 0; i < aPlayfield.length; i++) {
iXY = (i + 1);
// Horizontalen Sieg (verhindern) -> |x|x|-|
if (aPlayfield[i][0] == cTurn && aPlayfield[i][1] == cTurn
&& aPlayfield[i][2] == _scPlayfield) {
aCoordinate[0] = iXY;
aCoordinate[1] = 3;
throw new Exception();
}
// Horizontalen Sieg (verhindern) -> |-|x|x|
else if (aPlayfield[i][0] == _scPlayfield && aPlayfield[i][1] == cTurn
&& aPlayfield[i][2] == cTurn) {
aCoordinate[0] = iXY;
aCoordinate[1] = 1;
throw new Exception();
}
// Horizontaler Sieg (verhindern) -> |x|-|x|
else if (aPlayfield[i][0] == cTurn && aPlayfield[i][1] == _scPlayfield
&& aPlayfield[i][2] == cTurn) {
aCoordinate[0] = iXY;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |x|
* |x|
* |-|
*/
else if (aPlayfield[0][i] == cTurn && aPlayfield[1][i] == cTurn
&& aPlayfield[2][i] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = iXY;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |-|
* |x|
* |x|
*/
else if (aPlayfield[0][i] == _scPlayfield && aPlayfield[1][i] == cTurn
&& aPlayfield[2][i] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = iXY;
throw new Exception();
}
/*
* Vertikalen Sieg (verhindern):
* |x|
* |-|
* |x|
*/
else if (aPlayfield[0][i] == cTurn && aPlayfield[1][i] == _scPlayfield
&& aPlayfield[2][i] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = iXY;
throw new Exception();
}
}
/*
* Schrägen Sieg (verhindern):
* |x|
* |-|x|
* |-|-|-|
*/
if (aPlayfield[0][0] == cTurn && aPlayfield[1][1] == cTurn && aPlayfield[2][2] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = 3;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|
* |-|x|
* |-|-|x|
*/
else if (aPlayfield[0][0] == _scPlayfield && aPlayfield[1][1] == cTurn
&& aPlayfield[2][2] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = 1;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |x|
* |-|-|
* |-|-|x|
*/
else if (aPlayfield[0][0] == cTurn && aPlayfield[1][1] == _scPlayfield
&& aPlayfield[2][2] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|x|
* |-|x|
* |-|
*/
else if (aPlayfield[0][2] == cTurn && aPlayfield[1][1] == cTurn
&& aPlayfield[2][0] == _scPlayfield) {
aCoordinate[0] = 3;
aCoordinate[1] = 1;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|-|
* |-|x|
* |x|
*/
else if (aPlayfield[0][2] == _scPlayfield && aPlayfield[1][1] == cTurn
&& aPlayfield[2][0] == cTurn) {
aCoordinate[0] = 1;
aCoordinate[1] = 3;
throw new Exception();
}
/*
* Schrägen Sieg (verhindern):
* |-|-|x|
* |-|-|
* |x|
*/
else if (aPlayfield[0][2] == cTurn && aPlayfield[1][1] == _scPlayfield
&& aPlayfield[2][0] == cTurn) {
aCoordinate[0] = 2;
aCoordinate[1] = 2;
throw new Exception();
}
/*
* Es muss noch kein Sieg verhindert werden
* -> Koordinaten-Array auf null setzen
*/
aCoordinate = null;
} catch (Exception e) {
}
return aCoordinate;
}
/**
* Prüfungen durchführen, ob der aktuelle Spieler gewonnen hat:
* 1. Horizontal gewonnen
* 2. Vertikal gewonnen
* 3. Schräg gewonnen
*
* @param cTurnChar
* @param sPlayer
* @param aPlayfield
* @return
*/
private static boolean checkWin(char cTurnChar, String sPlayer, char[][] aPlayfield) {
// --| Deklaration |--
String sWinOutput = sPlayer + " hat";
boolean bWin = false;
// --| Überprüfung ob der aktuelle Spieler gewonnen hat |--
for (int i = 0; i < aPlayfield.length; i++) {
// Horrizontal gewonnen
if (aPlayfield[i][0] == cTurnChar && aPlayfield[i][1] == cTurnChar && aPlayfield[i][2] == cTurnChar) {
bWin = true;
sWinOutput = sWinOutput + " horizontal gewonnen!";
break;
}
// Vertikal gewonnen
if (aPlayfield[0][i] == cTurnChar && aPlayfield[1][i] == cTurnChar && aPlayfield[2][i] == cTurnChar) {
bWin = true;
sWinOutput = sWinOutput + " vertikal gewonnen!";
break;
}
}
// Schräg gewonnen
if ((aPlayfield[0][0] == cTurnChar && aPlayfield[1][1] == cTurnChar && aPlayfield[2][2] == cTurnChar)
|| (aPlayfield[0][2] == cTurnChar && aPlayfield[1][1] == cTurnChar && aPlayfield[2][0] == cTurnChar)) {
bWin = true;
sWinOutput = sWinOutput + " schräg gewonnen!";
}
// Aktueller Spieler hat gewonnen!
if (bWin) {
System.out.println(sWinOutput);
}
return bWin;
}
/**
* Spielzug durchführen
* Unterscheidung zwischen:
* - Spielzug eines Menschen
* - Spielzug des Rechners
*
* @param bPCTurn
* @param sPlayer
* @param cTurnChar
* @param aPlayfield
* @param aCoordinate
* @param oScanner
* @param oRandom
*/
private static void setTurn(boolean bPCTurn, String sPlayer, char cTurnChar, char[][] aPlayfield,
Scanner oScanner, Random oRandom) {
// --| Deklaration |--
int[] aCoordinate;
// --| Eingabe aus der Konsole auslesen und validieren |--
if (!bPCTurn) {
aCoordinate = TicTacToe.getInput(sPlayer, aPlayfield, oScanner);
}
// --| PC hat sich Koordinaten ausgewählt |--
else {
aCoordinate = TicTacToe.pcTurn(cTurnChar, sPlayer, aPlayfield, oRandom);
}
// Koordinaten setzen
aPlayfield[(aCoordinate[0] - 1)][(aCoordinate[1] - 1)] = cTurnChar;
}
/**
* Konsolen-Eingabe des Users auslesen und validieren
*
* @param sPlayer
* @param aPlayfield
* @param aCoordinate
* @param oScanner
*/
private static int[] getInput(String sPlayer, char[][] aPlayfield, Scanner oScanner) {
// --| Deklaration |--
String sInput;
int[] aCoordinate;
// --| Eingabe aus der Konsole lesen |--
while (true) {
try {
System.out.print(
sPlayer + " - Koordinaten (1-3) im folgenden Format erfassen [Zeile,Spalte]: ");
sInput = oScanner.nextLine();
// Eingabe bei dem Zeichen ',' aufsplitten und dem
// int-Array zuweisen
try {
aCoordinate = Arrays.stream(sInput.split(",")).mapToInt(Integer::parseInt).toArray();
} catch (NumberFormatException eConvError) {
throw new Exception("Eingabe war kein numerischer Wert!");
}
// Eingabe hat das falsche Format gehabt!
if (aCoordinate.length < 2 || aCoordinate.length > 2) {
throw new Exception("Bitte folgendes Format beachten [Zeile,Spalte].");
}
/*
* Eingabe wird auf folgendes überprüft:
* 1. Liegt die Eingabe für die Zeile im Wertebereich 1-3
* 2. Liegt die Eingabe für die Spalte im Wertebereich 1-3
* 3. Sind die erfassten Koordinaten bereits belegt?
*/
TicTacToe.validateTurn(aPlayfield, aCoordinate);
break;
} catch (Exception eError) {
System.out.println("****************************************************");
System.out.println("ERROR !!! -> " + eError.getMessage());
System.out.println("****************************************************\n");
}
}
return aCoordinate;
}
/**
* Eingabe wird auf folgendes überprüft:
* 1. Liegt die Eingabe für die Zeile im Wertebereich 1-3
* 2. Liegt die Eingabe für die Spalte im Wertebereich 1-3
* 3. Sind die erfassten Koordinaten bereits belegt?
*
* @param aPlayfield
* @param iRow
* @param iColumn
* @throws Exception
*/
private static void validateTurn(char[][] aPlayfield, int[] aCoordinate) throws Exception {
// Zeileneingabe liegt nicht im Wertebereich 1-3
if (aCoordinate[0] <= 0 || aCoordinate[0] > 3) {
throw new Exception("Eingabe Zeile (Wert: " + aCoordinate[0] + ") liegt nicht im Bereich 1-3.");
}
// Spalteneingabe liegt nicht im Wertebereich 1-3
if (aCoordinate[1] <= 0 || aCoordinate[1] > 3) {
throw new Exception("Eingabe Spalte (Wert: " + aCoordinate[1] + ") liegt nicht im Bereich 1-3.");
}
// Erfasste Koordinaten sind bereits belegt
if (aPlayfield[(aCoordinate[0] - 1)][(aCoordinate[1] - 1)] != _scPlayfield) {
throw new Exception("Koordinaten sind bereits belegt!");
}
}
/**
* Gebe das TicTacToe-Spielfeld aus
* -> bCreateField == true -> Spielfeld wird erstellt
*
* @param aPlayfield
* @param bCreateField
*/
private static void printArray2(char[][] aPlayfield, boolean bCreateField) {
// Spielfeld ausgeben
for (int i = 0; i < aPlayfield.length; i++) {
for (int j = 0; j < aPlayfield[i].length; j++) {
// Kenner gesetzt, dass das Spielfeld initialisiert wurde
aPlayfield[i][j] = (bCreateField == true ? aPlayfield[i][j] = _scPlayfield : aPlayfield[i][j]);
System.out.print("|" + aPlayfield[i][j]);
}
System.out.println("|");
}
System.out.print("\n");
}
} |
50742_10 | package nl.hhs.group8d;
import nl.hhs.group8d.ui.Menu;
import nl.hhs.group8d.ui.menus.StartMenu;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MenuManager {
private final Scanner scanner = new Scanner(System.in);
//Arraylist die houd alle vorige menuopties bij voor backtracking
private final ArrayList<Menu> listOfPreviousMenus = new ArrayList<>();
//Arraylist houd de huidige menu opties bij
private Menu currentMenu;
public void start() {
this.currentMenu = new StartMenu();
printMenuAndAskInput();
}
public void printMenuAndAskInput() {
boolean repeat = true;
while (repeat) {
printMenu();
repeat = processUserInput(getUserInput());
}
}
private boolean processUserInput(int userInput) {
//Als de 0: exit menu is gekozen
if (userInput == 0) {
//Kijken of we in de main menu zitten en zowel gwn weg gaan
if (listOfPreviousMenus.isEmpty()) {
return false;
}
//De huidige menu options terug zetten naar de vorige menu opties
currentMenu = listOfPreviousMenus.get(listOfPreviousMenus.size() - 1);
//de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben
listOfPreviousMenus.remove(listOfPreviousMenus.size() - 1);
return true;
}
//Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen
userInput -= 1;
//Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable
currentMenu.getMenuOptions().get(userInput).executeMenuOption();
Menu nextMenu = currentMenu.getMenuOptions().get(userInput).getNextSubMenu();
//Als er geen volgende menu opties zijn checken we voor nieuwe input
if (nextMenu == null) {
return true;
}
//het huidige menu opslaan voor backtracking
listOfPreviousMenus.add(currentMenu);
//het huidige menu updaten met de nieuwe submenu
currentMenu = nextMenu;
return true;
}
private int getUserInput() {
boolean noValidAnswer = true;
int answer = -1;
while (noValidAnswer) {
try {
answer = scanner.nextInt();
//See if the answer is inbetween the actual posible answers.
if (answer > currentMenu.getMenuOptions().size() || answer < 0) {
System.out.println("Vul alstublieft een geldig getal in.");
} else {
// Stop de loop
noValidAnswer = false;
}
} catch (InputMismatchException e) {
//input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome.
System.out.println("Vul alstublieft een geldig getal in.");
scanner.nextLine();
}
}
// Return de waarde and add empty line between menu's
System.out.println();
return answer;
}
private void printMenu() {
System.out.println("Kies een optie:");
//Ga langs elke submenu optie en print de naam
for (int i = 0; i < currentMenu.getMenuOptions().size(); i++) {
System.out.println(i + 1 + ": " + currentMenu.getMenuOptions().get(i).getTitle());
}
System.out.println("0: Exit");
System.out.print("Keuze: ");
}
}
| H-SE-1-8D-2022/PROJ1 | src/main/java/nl/hhs/group8d/MenuManager.java | 1,019 | //het huidige menu updaten met de nieuwe submenu | line_comment | nl | package nl.hhs.group8d;
import nl.hhs.group8d.ui.Menu;
import nl.hhs.group8d.ui.menus.StartMenu;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MenuManager {
private final Scanner scanner = new Scanner(System.in);
//Arraylist die houd alle vorige menuopties bij voor backtracking
private final ArrayList<Menu> listOfPreviousMenus = new ArrayList<>();
//Arraylist houd de huidige menu opties bij
private Menu currentMenu;
public void start() {
this.currentMenu = new StartMenu();
printMenuAndAskInput();
}
public void printMenuAndAskInput() {
boolean repeat = true;
while (repeat) {
printMenu();
repeat = processUserInput(getUserInput());
}
}
private boolean processUserInput(int userInput) {
//Als de 0: exit menu is gekozen
if (userInput == 0) {
//Kijken of we in de main menu zitten en zowel gwn weg gaan
if (listOfPreviousMenus.isEmpty()) {
return false;
}
//De huidige menu options terug zetten naar de vorige menu opties
currentMenu = listOfPreviousMenus.get(listOfPreviousMenus.size() - 1);
//de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben
listOfPreviousMenus.remove(listOfPreviousMenus.size() - 1);
return true;
}
//Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen
userInput -= 1;
//Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable
currentMenu.getMenuOptions().get(userInput).executeMenuOption();
Menu nextMenu = currentMenu.getMenuOptions().get(userInput).getNextSubMenu();
//Als er geen volgende menu opties zijn checken we voor nieuwe input
if (nextMenu == null) {
return true;
}
//het huidige menu opslaan voor backtracking
listOfPreviousMenus.add(currentMenu);
//het huidige<SUF>
currentMenu = nextMenu;
return true;
}
private int getUserInput() {
boolean noValidAnswer = true;
int answer = -1;
while (noValidAnswer) {
try {
answer = scanner.nextInt();
//See if the answer is inbetween the actual posible answers.
if (answer > currentMenu.getMenuOptions().size() || answer < 0) {
System.out.println("Vul alstublieft een geldig getal in.");
} else {
// Stop de loop
noValidAnswer = false;
}
} catch (InputMismatchException e) {
//input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome.
System.out.println("Vul alstublieft een geldig getal in.");
scanner.nextLine();
}
}
// Return de waarde and add empty line between menu's
System.out.println();
return answer;
}
private void printMenu() {
System.out.println("Kies een optie:");
//Ga langs elke submenu optie en print de naam
for (int i = 0; i < currentMenu.getMenuOptions().size(); i++) {
System.out.println(i + 1 + ": " + currentMenu.getMenuOptions().get(i).getTitle());
}
System.out.println("0: Exit");
System.out.print("Keuze: ");
}
}
|
75992_8 | import menus.*;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MenuManager {
private Scanner scanner = new Scanner(System.in);
//Arraylist houd de huidige menu opties bij
private Submenu menuOptions;
//Arraylist die houd alle vorige menuopties bij voor backtracking
private ArrayList<Submenu> previousMenu = new ArrayList<>();
public void start(){
this.menuOptions = getDefaultMenuOptions();
print();
}
public void print(){
printMenu();
processUserInput(getUserInput());
}
public void reCheckUserInput(){
printMenu();
processUserInput(getUserInput());
}
private void processUserInput(int index){
//Als de 0: exit menu is gekozen
if(index == 0){
//Kijken of we in de main menu zitten en zowel gwn weg gaan
if(previousMenu.size() == 0){
return;
}
//De huidige menu options terug zetten naar de vorige menu opties
menuOptions = previousMenu.get(previousMenu.size() -1);
//de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben
previousMenu.remove(previousMenu.size()-1);
print();
return;
}
//Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen
index--;
//Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable
menuOptions.getMenuOptions().get(index).executeMenuOption();
var newMenuOptions = menuOptions.getMenuOptions().get(index).getNextSubMenu();
//Als er geen volgende menu opties zijn checken we voor nieuwe input
if(newMenuOptions == null){
reCheckUserInput();
return;
}
//het huidige menu opslaan voor backtracking
previousMenu.add(menuOptions);
//het huidige menu updaten met de nieuwe submenu
menuOptions = newMenuOptions;
print() ;
}
private int getUserInput(){
boolean noValidAnswer = true;
while(noValidAnswer) {
try {
int answer = scanner.nextInt();
//See if the answer is inbetween the actual posible answers.
if (answer > menuOptions.getMenuOptions().size() || answer < 0) {
System.out.println("Please enter a valid number.");
} else {
//Return statement haalt ons uit de while loop
return answer;
}
} catch (InputMismatchException e) {
//input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome.
System.out.println("Please enter a valid number.");
}
}
//Mandatory return statement, actually does nothing
return 0;
}
private void printMenu(){
//Ga langs elke submenu optie en print de naam
for(int i = 0; i < menuOptions.getMenuOptions().size(); i++){
System.out.println(i+1 + ": "+menuOptions.getMenuOptions().get(i).getTitle());
}
System.out.println("0: Exit");
}
private Submenu getDefaultMenuOptions(){
//Dit is het startmenu
ArrayList<iMenuOption> menuOptions = new ArrayList<>();
menuOptions.add(new DierenMenuOption());
menuOptions.add(new ExamenMenuOption());
menuOptions.add(new StudentenMenuOption());
Submenu submenu = new Submenu();
submenu.setMenuOptions(menuOptions);
return submenu;
}
}
| H-SE-1-8D-2022/voorbeeld-code-menu | src/MenuManager.java | 986 | //Als er geen volgende menu opties zijn checken we voor nieuwe input | line_comment | nl | import menus.*;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MenuManager {
private Scanner scanner = new Scanner(System.in);
//Arraylist houd de huidige menu opties bij
private Submenu menuOptions;
//Arraylist die houd alle vorige menuopties bij voor backtracking
private ArrayList<Submenu> previousMenu = new ArrayList<>();
public void start(){
this.menuOptions = getDefaultMenuOptions();
print();
}
public void print(){
printMenu();
processUserInput(getUserInput());
}
public void reCheckUserInput(){
printMenu();
processUserInput(getUserInput());
}
private void processUserInput(int index){
//Als de 0: exit menu is gekozen
if(index == 0){
//Kijken of we in de main menu zitten en zowel gwn weg gaan
if(previousMenu.size() == 0){
return;
}
//De huidige menu options terug zetten naar de vorige menu opties
menuOptions = previousMenu.get(previousMenu.size() -1);
//de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben
previousMenu.remove(previousMenu.size()-1);
print();
return;
}
//Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen
index--;
//Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable
menuOptions.getMenuOptions().get(index).executeMenuOption();
var newMenuOptions = menuOptions.getMenuOptions().get(index).getNextSubMenu();
//Als er<SUF>
if(newMenuOptions == null){
reCheckUserInput();
return;
}
//het huidige menu opslaan voor backtracking
previousMenu.add(menuOptions);
//het huidige menu updaten met de nieuwe submenu
menuOptions = newMenuOptions;
print() ;
}
private int getUserInput(){
boolean noValidAnswer = true;
while(noValidAnswer) {
try {
int answer = scanner.nextInt();
//See if the answer is inbetween the actual posible answers.
if (answer > menuOptions.getMenuOptions().size() || answer < 0) {
System.out.println("Please enter a valid number.");
} else {
//Return statement haalt ons uit de while loop
return answer;
}
} catch (InputMismatchException e) {
//input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome.
System.out.println("Please enter a valid number.");
}
}
//Mandatory return statement, actually does nothing
return 0;
}
private void printMenu(){
//Ga langs elke submenu optie en print de naam
for(int i = 0; i < menuOptions.getMenuOptions().size(); i++){
System.out.println(i+1 + ": "+menuOptions.getMenuOptions().get(i).getTitle());
}
System.out.println("0: Exit");
}
private Submenu getDefaultMenuOptions(){
//Dit is het startmenu
ArrayList<iMenuOption> menuOptions = new ArrayList<>();
menuOptions.add(new DierenMenuOption());
menuOptions.add(new ExamenMenuOption());
menuOptions.add(new StudentenMenuOption());
Submenu submenu = new Submenu();
submenu.setMenuOptions(menuOptions);
return submenu;
}
}
|
208933_4 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class TreinGroen here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TreinGroen extends Treinen
{
/**
* Act - do whatever the TreinGroen wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
move(0);
int x = getX();
int y = getY();
int ny = getY()+1;
World world=getWorld();// new
setLocation (x, ny);
if(getY() == 297) {
setLocation(getX(), getY() - 1);
}
if (isTouching(ContainerGroenDek3.class) || isTouching (ContainerGroenDek2.class) || isTouching(ContainerGroenDek1.class)){
//int x = getX();
// int y = getY();
//int ny = getY()+1;
setLocation (x, ny);
}
if (Greenfoot.isKeyDown("down")){
setLocation(x, ny);
}
if (getX() <= 5 || getX() >= getWorld() . getWidth() -5)
{
getWorld().removeObject(this);
}
if (getY() <= 5 || getY() >= getWorld() . getHeight() -5)
{
getWorld().removeObject(this);
world.removeObject(this);//new
int count = Greenfoot.getRandomNumber(4);
if (count == 3){ world.addObject(new TreinRood(), 179, 77);}
else if (count == 2) {world.addObject(new TreinBlauw(),179, 77);}
else if (count == 1) {world.addObject(new TreinGroen(),179, 77);}
else {world.addObject(new TreinGeel(), 179, 77);};
}
}
}
| H35am/MiniGame2 | TreinGroen.java | 571 | //int x = getX(); | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class TreinGroen here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TreinGroen extends Treinen
{
/**
* Act - do whatever the TreinGroen wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
move(0);
int x = getX();
int y = getY();
int ny = getY()+1;
World world=getWorld();// new
setLocation (x, ny);
if(getY() == 297) {
setLocation(getX(), getY() - 1);
}
if (isTouching(ContainerGroenDek3.class) || isTouching (ContainerGroenDek2.class) || isTouching(ContainerGroenDek1.class)){
//int x<SUF>
// int y = getY();
//int ny = getY()+1;
setLocation (x, ny);
}
if (Greenfoot.isKeyDown("down")){
setLocation(x, ny);
}
if (getX() <= 5 || getX() >= getWorld() . getWidth() -5)
{
getWorld().removeObject(this);
}
if (getY() <= 5 || getY() >= getWorld() . getHeight() -5)
{
getWorld().removeObject(this);
world.removeObject(this);//new
int count = Greenfoot.getRandomNumber(4);
if (count == 3){ world.addObject(new TreinRood(), 179, 77);}
else if (count == 2) {world.addObject(new TreinBlauw(),179, 77);}
else if (count == 1) {world.addObject(new TreinGroen(),179, 77);}
else {world.addObject(new TreinGeel(), 179, 77);};
}
}
}
|
37717_2 | package be.SabahLeanderSteven.endtermandroidproject.model;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface LocationDAO {
@Insert
void insert(Location location);
@Query("DELETE FROM locations")
void deleteAll();
//vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd
//livedata werkt enkel met List, niet met ArrayList
//wordt geen list,
@Query("SELECT * from locations")
LiveData<List<Location>> getAllLocations();
@Query("SELECT * FROM locations WHERE id LIKE :id")
Location findLocationById(String id);
@Query("SELECT * FROM locations WHERE type LIKE :type")
LiveData<List<Location>> getAllLocationsOfType(String type);
}
| H3AR7B3A7/EndTermAndroidProject | app/src/main/java/be/SabahLeanderSteven/endtermandroidproject/model/LocationDAO.java | 241 | //wordt geen list, | line_comment | nl | package be.SabahLeanderSteven.endtermandroidproject.model;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface LocationDAO {
@Insert
void insert(Location location);
@Query("DELETE FROM locations")
void deleteAll();
//vermijd het zelf aanspreken van getters etc., sowieso al geobserveerd
//livedata werkt enkel met List, niet met ArrayList
//wordt geen<SUF>
@Query("SELECT * from locations")
LiveData<List<Location>> getAllLocations();
@Query("SELECT * FROM locations WHERE id LIKE :id")
Location findLocationById(String id);
@Query("SELECT * FROM locations WHERE type LIKE :type")
LiveData<List<Location>> getAllLocationsOfType(String type);
}
|
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();
}
}
}
}
|
69594_0 | package AbsentieLijst.userInterfaceLaag;
import AbsentieLijst.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.sql.Time;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
public class ToekomstigAfmeldenController {
public Button ButtonOpslaan;
public Button ButtonAnnuleren;
public DatePicker DatePickerDate;
public ComboBox ComboBoxReden;
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();
public Button overzicht;
public Label label;
public ComboBox tijd;
School HU = School.getSchool();
ObservableList<String> options =
FXCollections.observableArrayList(
"Bruiloft",
"Tandarts afspraak",
"Begravenis", "Wegens corona.", "Overig"
);
public void initialize() {
ComboBoxReden.setItems(options);
}
public void ActionOpslaan(ActionEvent actionEvent) {
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {
LocalDate datum = DatePickerDate.getValue();
Object time = tijd.getValue();
try {
for (Klas klas : HU.getKlassen()) {
for (Student student : klas.getStudenten()) {
if (student.getisIngelogd()) {
HashMap<String, Les> alleLessen = klas.getLessen();
for (String lesNaam : alleLessen.keySet()) {
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {
alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les
student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student.
Button source = (Button) actionEvent.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
}
}
}
}
} catch (Exception e) {
label.setText("ddddd");
}
} else label.setText("Je moet Datum en reden kiezen");
}
public void ActionAnnuleren(ActionEvent actionEvent) {
Button source = (Button) actionEvent.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
public void DatapickerOnAction(ActionEvent actionEvent) {
ObservableList<String> lessen = FXCollections.observableArrayList();
for (Klas klas : HU.getKlassen()) {
for (Student student : klas.getStudenten()) {
if (student.getisIngelogd()) {
ArrayList<String> les = new ArrayList<>();
HashMap<String, Les> alleLessen = klas.getLessen();
for (Les lesNaam : alleLessen.values())
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {
// for (String les1 : alleLessen.keySet()) {
les.add(lesNaam.getNaam());
lessen.addAll(les);
tijd.setItems(lessen);
}
}
}
}
}
}
| HBO-ICT-GP-SD/Laatsteversie | AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java | 1,160 | //afgemeld_lijst in de les
| line_comment | nl | package AbsentieLijst.userInterfaceLaag;
import AbsentieLijst.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.sql.Time;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
public class ToekomstigAfmeldenController {
public Button ButtonOpslaan;
public Button ButtonAnnuleren;
public DatePicker DatePickerDate;
public ComboBox ComboBoxReden;
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();
public Button overzicht;
public Label label;
public ComboBox tijd;
School HU = School.getSchool();
ObservableList<String> options =
FXCollections.observableArrayList(
"Bruiloft",
"Tandarts afspraak",
"Begravenis", "Wegens corona.", "Overig"
);
public void initialize() {
ComboBoxReden.setItems(options);
}
public void ActionOpslaan(ActionEvent actionEvent) {
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {
LocalDate datum = DatePickerDate.getValue();
Object time = tijd.getValue();
try {
for (Klas klas : HU.getKlassen()) {
for (Student student : klas.getStudenten()) {
if (student.getisIngelogd()) {
HashMap<String, Les> alleLessen = klas.getLessen();
for (String lesNaam : alleLessen.keySet()) {
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {
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.
Button source = (Button) actionEvent.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
}
}
}
}
} catch (Exception e) {
label.setText("ddddd");
}
} else label.setText("Je moet Datum en reden kiezen");
}
public void ActionAnnuleren(ActionEvent actionEvent) {
Button source = (Button) actionEvent.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
public void DatapickerOnAction(ActionEvent actionEvent) {
ObservableList<String> lessen = FXCollections.observableArrayList();
for (Klas klas : HU.getKlassen()) {
for (Student student : klas.getStudenten()) {
if (student.getisIngelogd()) {
ArrayList<String> les = new ArrayList<>();
HashMap<String, Les> alleLessen = klas.getLessen();
for (Les lesNaam : alleLessen.values())
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {
// for (String les1 : alleLessen.keySet()) {
les.add(lesNaam.getNaam());
lessen.addAll(les);
tijd.setItems(lessen);
}
}
}
}
}
}
|
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();
}
}
|
40780_6 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
Klasse der Standard-Welt
(Also die normale Weltkarte mit allen Kontinenten)
@author GruenerWal, MaxiJohl
@version 1.0.0
*/
public class Map_World extends GeneralMap
{
/**
Konstruktor der Weltkarte;
konstruiert eine GeneralMap mit den Ausmassen 1600 auf 900 Pixel.
*/
public Map_World(String[] playerList, int[] colorList)
{
super(playerList,colorList);
setBackground("MapWorld.png");
provinceCount = 42;
armyMinimum = 3;
/*
Hier werden später sämtliche Provinzen der Standard-Map erstellt.
Dies funktioniert folgendermassen:
=================================================================
Dieses kürzere Format ersetzt den langen Code und sorgt eventuell sogar für einen Geschwindigkeitsschub. Dabei sollte diesselbe Funktionalität erhalten bleiben.
provinces[<Provinz-ID>] = new Province(<Provinz-ID>,<Kontinent-ID>,<X-Position>,<Y-Position>,<Anzahl Sterne>,"<Anzeigename>", new int[] { <Liste aller Nachbarprovinzen> });
=================================================================
Der Speicherplatz für provinces[0] bleibt leer, da es keine Provinz mit der ID 0 gibt!
Und ja, ich weiss, dass das scheisse viel Schreibarbeit ist.
Aber da muss man durch, wir habens auch hinbekommen :P
~GruenerWal
*/
continentBoni = new int[] {0,5,5,2,3,7,2};
// Festlegung der Provinz-Anzahl
provinces = new Province[provinceCount + 1];
// Implementierung sämtlicher Provinzen
// ACHTUNG! Gaaaaanz viel Code!
// cID 1 - Nordamerika
provinces[1] = new Province( 1 , 1 , 64 , 106 , 1 , "Alaska" , new int[] {2 , 3 , 36});
provinces[2] = new Province( 2 , 1 , 162 , 106 , 1 , "NW-Territorien" , new int[] {1 , 3 , 4 , 9});
provinces[3] = new Province( 3 , 1 , 153 , 170 , 1 , "Alberta" , new int[] {1 , 2 , 4 , 5});
provinces[4] = new Province( 4 , 1 , 223 , 177 , 2 , "Ontario" , new int[] {2 , 3 , 5 , 6 , 7 , 9});
provinces[5] = new Province( 5 , 1 , 160 , 236 , 2 , "Weststaaten" , new int[] {3 , 4 , 6 , 8});
provinces[6] = new Province( 6 , 1 , 232 , 273 , 2 , "Oststaaten" , new int[] {4 , 5 , 7 , 8});
provinces[7] = new Province( 7 , 1 , 300 , 180 , 2 , "Quebec" , new int[] {4 , 6 , 9});
provinces[8] = new Province( 8 , 1 , 181 , 347 , 1 , "Mittelamerika" , new int[] {5 , 6 , 17});
provinces[9] = new Province( 9 , 1 , 365 , 55 , 1 , "Grönland" , new int[] {2 , 4 , 7 , 10});
// cID 2 - Europa
provinces[10] = new Province(10 , 2 , 454 , 142 , 1 , "Island" , new int[] {9 , 11 , 12});
provinces[11] = new Province(11 , 2 , 424 , 221 , 2 , "Großbritannien" , new int[] {10 , 12 , 14 , 15});
provinces[12] = new Province(12 , 2 , 520 , 153 , 1 , "Skandinavien" , new int[] {10 , 11 , 13 , 14});
provinces[13] = new Province(13 , 2 , 636 , 180 , 2 , "Russland" , new int[] {12 , 14 , 16 , 27 , 31 , 32});
provinces[14] = new Province(14 , 2 , 528 , 232 , 2 , "Nordeuropa" , new int[] {11 , 12 , 13 , 15 , 16});
provinces[15] = new Province(15 , 2 , 449 , 335 , 2 , "Westeuropa" , new int[] {11 , 14 , 16 , 25});
provinces[16] = new Province(16 , 2 , 537 , 296 , 2 , "Südeuropa" , new int[] {13 , 14 , 15 , 25 , 26 , 27});
// cID 3 - Suedamerika
provinces[17] = new Province(17 , 3 , 245 , 396 , 1 , "Venezuela" , new int[] {8 , 18 , 19});
provinces[18] = new Province(18 , 3 , 255 , 498 , 1 , "Peru" , new int[] {17 , 19 , 20});
provinces[19] = new Province(19 , 3 , 327 , 467 , 2 , "Brasilien" , new int[] {17 , 18 , 20 , 25});
provinces[20] = new Province(20 , 3 , 274 , 572 , 1 , "Argentinien" , new int[] {18 , 19});
// cID 4 - Afrika
provinces[21] = new Province(21 , 4 , 680 , 630 , 1 , "Madagaskar" , new int[] {24 , 22});
provinces[22] = new Province(22 , 4 , 580 , 624 , 1 , "Südafrika" , new int[] {21 , 23 , 24});
provinces[23] = new Province(23 , 4 , 572 , 537 , 2 , "Zentralafrika" , new int[] {22 , 25 , 24});
provinces[24] = new Province(24 , 4 , 632 , 500 , 2 , "Ostafrika" , new int[] {21 , 22 , 25 , 23 , 26});
provinces[25] = new Province(25 , 4 , 491 , 444 , 1 , "Nordafrika" , new int[] {15 , 16 , 26 , 23 , 24});
provinces[26] = new Province(26 , 4 , 574 , 414 , 1 , "Ägypten" , new int[] {27 , 25 , 24 , 16});
// cID 5 - Asien
provinces[27] = new Province(27 , 5 , 664 , 345 , 2 , "Mittlerer Osten" , new int[] {24 , 26 , 16 , 23 , 31 , 28});
provinces[28] = new Province(28 , 5 , 784 , 370 , 2 , "Indien" , new int[] {29 , 31 , 27 , 30});
provinces[29] = new Province(29 , 5 , 863 , 322 , 2 , "China" , new int[] {30 , 28 , 31 , 32 , 33 , 37});
provinces[30] = new Province(30 , 5 , 867 , 400 , 1 , "Südost Asien" , new int[] {29 , 39 , 28});
provinces[31] = new Province(31 , 5 , 724 , 262 , 1 , "Afganistan" , new int[] {29 , 28 , 27 , 13 , 32});
provinces[32] = new Province(32 , 5 , 740 , 163 , 1 , "Ural" , new int[] {29 , 33 , 31 , 13});
provinces[33] = new Province(33 , 5 , 802 , 128 , 1 , "Sibirien" , new int[] {34 , 35 , 37 , 29 , 32});
provinces[34] = new Province(34 , 5 , 884 , 82 , 1 , "Jakutien" , new int[] {36 , 35 , 33});
provinces[35] = new Province(35 , 5 , 867 , 176 , 2 , "Irkutsk" , new int[] {34 , 36 , 37 , 33});
provinces[36] = new Province(36 , 5 , 973 , 89 , 1 , "Kamtschatka" , new int[] {1 , 38 , 37 , 35 , 34});
provinces[37] = new Province(37 , 5 , 882 , 243 , 1 , "Mongolei" , new int[] {29 , 33 , 35 , 36 , 38});
provinces[38] = new Province(38 , 5 , 994 , 249 , 2 , "Japan" , new int[] {37 , 36});
// cID 6 - Ozeanien
provinces[39] = new Province(39 , 6 , 889 , 519 , 1 , "Indonesien" , new int[] {30 , 40 , 42});
provinces[40] = new Province(40 , 6 , 983 , 492 , 2 , "Neuguinea" , new int[] {39 , 41 , 42});
provinces[41] = new Province(41 , 6 , 1000, 595 , 1 , "Ost Australien" , new int[] {40 , 42});
provinces[42] = new Province(42 , 6 , 934 , 628 , 1 , "West Australien" , new int[] {40 , 41 , 39});
initProvinces();
/*
Legt die Startprovincen der Spieler fest.
*/
int[] dataL = new int[(provinces.length-1)*2];
/*
dataL speichert folgende Daten:
0. Spieler-ID des Besitzers (Provinz 1)
1. Einheitenanzahl (Provinz 1)
2. Spieler-ID des Besitzers (Provinz 2)
3. [...]
*/
if(players.length==3) {
/*
Spieler 1 darf beginnen; Hauptstadt: 40
Spieler 2 ist als zweites dran; Hauptstadt: 20
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt: 9
*/
dataL = new int[] {0,1,2,2,1,2,1,1,0,1,0,1,2,2,0,1,2,4,2,1,1,2,0,2,0,2,2,3,2,3,2,3,0,1,1,2,1,4,1,3,0,1,2,4,0,2,2,4,1,2,1,1,2,1,0,3,0,3,0,4,2,1,1,1,1,1,0,2,1,2,2,1,1,2,1,4,1,3,0,4,2,1,0,2};
} else if(players.length==4) {
/*
Spieler 1 darf beginnen; Hauptstadt:22
Spieler 2 ist als zweites dran; Hauptstadt:20
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt:2
Spieler 4 ist als viertes dran und bekommt eine Karte; Hauptstadt:39
*/
dataL = new int[] {0,1,2,3,2,3,2,2,2,2,2,3,1,2,0,2,1,2,2,2,1,3,2,2,1,3,0,3,0,3,0,3,2,2,3,2,1,4,1,4,0,1,0,2,0,5,0,3,1,2,3,3,3,1,3,2,1,2,1,2,3,1,1,1,3,5,2,2,2,2,2,2,3,1,3,1,3,4,3,1,0,2,3,4};
} else if(players.length==5) {
/*
Spieler 1 darf beginnen; Hauptstadt:13
Spieler 2 ist als zweites dran; Hauptstadt:7
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt:22
Spieler 4 ist als viertes dran und bekommt eine Karte; Hauptstadt:20
Spieler 5 ist als fünftes dran und bekommt zwei Karte; Hauptstadt:41
*/
dataL = new int[] {2,1,0,2,3,2,1,2,1,2,1,2,1,4,3,1,1,2,3,1,3,3,2,1,0,4,0,2,2,3,0,2,1,3,3,2,3,5,3,3,1,2,2,5,2,3,0,2,2,3,2,2,1,3,4,2,4,3,4,3,0,3,0,3,3,1,4,1,4,1,4,2,2,2,3,2,4,2,0,2,4,4,4,2};
}
for(int i = 1; i < provinces.length; i++) {
Province p = provinces[i];
p.setOwner(dataL[(i-1)*2]);
p.setEntityCount(dataL[(i*2)-1]);
}
redrawPlayers();
}
}
| HGE-IT-Course-2016/zweiundvierzig | Map_World.java | 3,598 | // ACHTUNG! Gaaaaanz viel Code! | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
Klasse der Standard-Welt
(Also die normale Weltkarte mit allen Kontinenten)
@author GruenerWal, MaxiJohl
@version 1.0.0
*/
public class Map_World extends GeneralMap
{
/**
Konstruktor der Weltkarte;
konstruiert eine GeneralMap mit den Ausmassen 1600 auf 900 Pixel.
*/
public Map_World(String[] playerList, int[] colorList)
{
super(playerList,colorList);
setBackground("MapWorld.png");
provinceCount = 42;
armyMinimum = 3;
/*
Hier werden später sämtliche Provinzen der Standard-Map erstellt.
Dies funktioniert folgendermassen:
=================================================================
Dieses kürzere Format ersetzt den langen Code und sorgt eventuell sogar für einen Geschwindigkeitsschub. Dabei sollte diesselbe Funktionalität erhalten bleiben.
provinces[<Provinz-ID>] = new Province(<Provinz-ID>,<Kontinent-ID>,<X-Position>,<Y-Position>,<Anzahl Sterne>,"<Anzeigename>", new int[] { <Liste aller Nachbarprovinzen> });
=================================================================
Der Speicherplatz für provinces[0] bleibt leer, da es keine Provinz mit der ID 0 gibt!
Und ja, ich weiss, dass das scheisse viel Schreibarbeit ist.
Aber da muss man durch, wir habens auch hinbekommen :P
~GruenerWal
*/
continentBoni = new int[] {0,5,5,2,3,7,2};
// Festlegung der Provinz-Anzahl
provinces = new Province[provinceCount + 1];
// Implementierung sämtlicher Provinzen
// ACHTUNG! Gaaaaanz<SUF>
// cID 1 - Nordamerika
provinces[1] = new Province( 1 , 1 , 64 , 106 , 1 , "Alaska" , new int[] {2 , 3 , 36});
provinces[2] = new Province( 2 , 1 , 162 , 106 , 1 , "NW-Territorien" , new int[] {1 , 3 , 4 , 9});
provinces[3] = new Province( 3 , 1 , 153 , 170 , 1 , "Alberta" , new int[] {1 , 2 , 4 , 5});
provinces[4] = new Province( 4 , 1 , 223 , 177 , 2 , "Ontario" , new int[] {2 , 3 , 5 , 6 , 7 , 9});
provinces[5] = new Province( 5 , 1 , 160 , 236 , 2 , "Weststaaten" , new int[] {3 , 4 , 6 , 8});
provinces[6] = new Province( 6 , 1 , 232 , 273 , 2 , "Oststaaten" , new int[] {4 , 5 , 7 , 8});
provinces[7] = new Province( 7 , 1 , 300 , 180 , 2 , "Quebec" , new int[] {4 , 6 , 9});
provinces[8] = new Province( 8 , 1 , 181 , 347 , 1 , "Mittelamerika" , new int[] {5 , 6 , 17});
provinces[9] = new Province( 9 , 1 , 365 , 55 , 1 , "Grönland" , new int[] {2 , 4 , 7 , 10});
// cID 2 - Europa
provinces[10] = new Province(10 , 2 , 454 , 142 , 1 , "Island" , new int[] {9 , 11 , 12});
provinces[11] = new Province(11 , 2 , 424 , 221 , 2 , "Großbritannien" , new int[] {10 , 12 , 14 , 15});
provinces[12] = new Province(12 , 2 , 520 , 153 , 1 , "Skandinavien" , new int[] {10 , 11 , 13 , 14});
provinces[13] = new Province(13 , 2 , 636 , 180 , 2 , "Russland" , new int[] {12 , 14 , 16 , 27 , 31 , 32});
provinces[14] = new Province(14 , 2 , 528 , 232 , 2 , "Nordeuropa" , new int[] {11 , 12 , 13 , 15 , 16});
provinces[15] = new Province(15 , 2 , 449 , 335 , 2 , "Westeuropa" , new int[] {11 , 14 , 16 , 25});
provinces[16] = new Province(16 , 2 , 537 , 296 , 2 , "Südeuropa" , new int[] {13 , 14 , 15 , 25 , 26 , 27});
// cID 3 - Suedamerika
provinces[17] = new Province(17 , 3 , 245 , 396 , 1 , "Venezuela" , new int[] {8 , 18 , 19});
provinces[18] = new Province(18 , 3 , 255 , 498 , 1 , "Peru" , new int[] {17 , 19 , 20});
provinces[19] = new Province(19 , 3 , 327 , 467 , 2 , "Brasilien" , new int[] {17 , 18 , 20 , 25});
provinces[20] = new Province(20 , 3 , 274 , 572 , 1 , "Argentinien" , new int[] {18 , 19});
// cID 4 - Afrika
provinces[21] = new Province(21 , 4 , 680 , 630 , 1 , "Madagaskar" , new int[] {24 , 22});
provinces[22] = new Province(22 , 4 , 580 , 624 , 1 , "Südafrika" , new int[] {21 , 23 , 24});
provinces[23] = new Province(23 , 4 , 572 , 537 , 2 , "Zentralafrika" , new int[] {22 , 25 , 24});
provinces[24] = new Province(24 , 4 , 632 , 500 , 2 , "Ostafrika" , new int[] {21 , 22 , 25 , 23 , 26});
provinces[25] = new Province(25 , 4 , 491 , 444 , 1 , "Nordafrika" , new int[] {15 , 16 , 26 , 23 , 24});
provinces[26] = new Province(26 , 4 , 574 , 414 , 1 , "Ägypten" , new int[] {27 , 25 , 24 , 16});
// cID 5 - Asien
provinces[27] = new Province(27 , 5 , 664 , 345 , 2 , "Mittlerer Osten" , new int[] {24 , 26 , 16 , 23 , 31 , 28});
provinces[28] = new Province(28 , 5 , 784 , 370 , 2 , "Indien" , new int[] {29 , 31 , 27 , 30});
provinces[29] = new Province(29 , 5 , 863 , 322 , 2 , "China" , new int[] {30 , 28 , 31 , 32 , 33 , 37});
provinces[30] = new Province(30 , 5 , 867 , 400 , 1 , "Südost Asien" , new int[] {29 , 39 , 28});
provinces[31] = new Province(31 , 5 , 724 , 262 , 1 , "Afganistan" , new int[] {29 , 28 , 27 , 13 , 32});
provinces[32] = new Province(32 , 5 , 740 , 163 , 1 , "Ural" , new int[] {29 , 33 , 31 , 13});
provinces[33] = new Province(33 , 5 , 802 , 128 , 1 , "Sibirien" , new int[] {34 , 35 , 37 , 29 , 32});
provinces[34] = new Province(34 , 5 , 884 , 82 , 1 , "Jakutien" , new int[] {36 , 35 , 33});
provinces[35] = new Province(35 , 5 , 867 , 176 , 2 , "Irkutsk" , new int[] {34 , 36 , 37 , 33});
provinces[36] = new Province(36 , 5 , 973 , 89 , 1 , "Kamtschatka" , new int[] {1 , 38 , 37 , 35 , 34});
provinces[37] = new Province(37 , 5 , 882 , 243 , 1 , "Mongolei" , new int[] {29 , 33 , 35 , 36 , 38});
provinces[38] = new Province(38 , 5 , 994 , 249 , 2 , "Japan" , new int[] {37 , 36});
// cID 6 - Ozeanien
provinces[39] = new Province(39 , 6 , 889 , 519 , 1 , "Indonesien" , new int[] {30 , 40 , 42});
provinces[40] = new Province(40 , 6 , 983 , 492 , 2 , "Neuguinea" , new int[] {39 , 41 , 42});
provinces[41] = new Province(41 , 6 , 1000, 595 , 1 , "Ost Australien" , new int[] {40 , 42});
provinces[42] = new Province(42 , 6 , 934 , 628 , 1 , "West Australien" , new int[] {40 , 41 , 39});
initProvinces();
/*
Legt die Startprovincen der Spieler fest.
*/
int[] dataL = new int[(provinces.length-1)*2];
/*
dataL speichert folgende Daten:
0. Spieler-ID des Besitzers (Provinz 1)
1. Einheitenanzahl (Provinz 1)
2. Spieler-ID des Besitzers (Provinz 2)
3. [...]
*/
if(players.length==3) {
/*
Spieler 1 darf beginnen; Hauptstadt: 40
Spieler 2 ist als zweites dran; Hauptstadt: 20
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt: 9
*/
dataL = new int[] {0,1,2,2,1,2,1,1,0,1,0,1,2,2,0,1,2,4,2,1,1,2,0,2,0,2,2,3,2,3,2,3,0,1,1,2,1,4,1,3,0,1,2,4,0,2,2,4,1,2,1,1,2,1,0,3,0,3,0,4,2,1,1,1,1,1,0,2,1,2,2,1,1,2,1,4,1,3,0,4,2,1,0,2};
} else if(players.length==4) {
/*
Spieler 1 darf beginnen; Hauptstadt:22
Spieler 2 ist als zweites dran; Hauptstadt:20
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt:2
Spieler 4 ist als viertes dran und bekommt eine Karte; Hauptstadt:39
*/
dataL = new int[] {0,1,2,3,2,3,2,2,2,2,2,3,1,2,0,2,1,2,2,2,1,3,2,2,1,3,0,3,0,3,0,3,2,2,3,2,1,4,1,4,0,1,0,2,0,5,0,3,1,2,3,3,3,1,3,2,1,2,1,2,3,1,1,1,3,5,2,2,2,2,2,2,3,1,3,1,3,4,3,1,0,2,3,4};
} else if(players.length==5) {
/*
Spieler 1 darf beginnen; Hauptstadt:13
Spieler 2 ist als zweites dran; Hauptstadt:7
Spieler 3 ist als drittes dran und bekommt eine Karte; Hauptstadt:22
Spieler 4 ist als viertes dran und bekommt eine Karte; Hauptstadt:20
Spieler 5 ist als fünftes dran und bekommt zwei Karte; Hauptstadt:41
*/
dataL = new int[] {2,1,0,2,3,2,1,2,1,2,1,2,1,4,3,1,1,2,3,1,3,3,2,1,0,4,0,2,2,3,0,2,1,3,3,2,3,5,3,3,1,2,2,5,2,3,0,2,2,3,2,2,1,3,4,2,4,3,4,3,0,3,0,3,3,1,4,1,4,1,4,2,2,2,3,2,4,2,0,2,4,4,4,2};
}
for(int i = 1; i < provinces.length; i++) {
Province p = provinces[i];
p.setOwner(dataL[(i-1)*2]);
p.setEntityCount(dataL[(i*2)-1]);
}
redrawPlayers();
}
}
|
40046_2 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
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.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
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.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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(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;
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;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
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);
}
}
| HGitMaster/geotools-osgi | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,349 | // check of vorig vertex opgeslagen kan worden
| line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
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.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
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.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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(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;
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;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
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<SUF>
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);
}
}
|
42916_0 | package nl.hr.cmtprg037.week5huiswerksoundboard;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Log tag voor logging van deze app
public final static String LOG_TAG = "Week5HW";
// Mediaplayer wil je tussen functieaanroepen door bewaren
private MediaPlayer mp = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Koppel aan beide knoppen dezelfde listener (this) omdat ze beiden ongeveer hetzelfde doen
Button b1 = findViewById(R.id.button_mariome);
Button b2 = findViewById(R.id.button_oneup);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
protected void onResume() {
// Zet volume knop op stream music
setVolumeControlStream(AudioManager.STREAM_MUSIC);
super.onResume();
}
@Override
public void onClick(View view) {
// debug
Log.d(LOG_TAG, "Klik");
// zet media uit als deze speelt
if (mp != null) {
mp.release();
}
// haal image view op uit layout
ImageView iv = findViewById(R.id.imageView);
// check welke knop er ingedrukt is
switch(view.getId()) {
case R.id.button_mariome:
// speel geluid af
mp = MediaPlayer.create(this, R.raw.mariome);
mp.start();
// wissel plaatje
iv.setImageResource(R.drawable.mariome);
break;
case R.id.button_oneup:
mp = MediaPlayer.create(this, R.raw.mario1up);
mp.start();
iv.setImageResource(R.drawable.mario1up);
break;
}
}
}
| HR-CMGT/PRG07-Mobile | Week5HuiswerkSoundboard/app/src/main/java/nl/hr/cmtprg037/week5huiswerksoundboard/MainActivity.java | 630 | // Log tag voor logging van deze app | line_comment | nl | package nl.hr.cmtprg037.week5huiswerksoundboard;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Log tag<SUF>
public final static String LOG_TAG = "Week5HW";
// Mediaplayer wil je tussen functieaanroepen door bewaren
private MediaPlayer mp = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Koppel aan beide knoppen dezelfde listener (this) omdat ze beiden ongeveer hetzelfde doen
Button b1 = findViewById(R.id.button_mariome);
Button b2 = findViewById(R.id.button_oneup);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
protected void onResume() {
// Zet volume knop op stream music
setVolumeControlStream(AudioManager.STREAM_MUSIC);
super.onResume();
}
@Override
public void onClick(View view) {
// debug
Log.d(LOG_TAG, "Klik");
// zet media uit als deze speelt
if (mp != null) {
mp.release();
}
// haal image view op uit layout
ImageView iv = findViewById(R.id.imageView);
// check welke knop er ingedrukt is
switch(view.getId()) {
case R.id.button_mariome:
// speel geluid af
mp = MediaPlayer.create(this, R.raw.mariome);
mp.start();
// wissel plaatje
iv.setImageResource(R.drawable.mariome);
break;
case R.id.button_oneup:
mp = MediaPlayer.create(this, R.raw.mario1up);
mp.start();
iv.setImageResource(R.drawable.mario1up);
break;
}
}
}
|
64553_1 | package Iterator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Halil Teker on 6/24/2017.
*/
public class HogeschoolRotterdam implements Iterable {
private List<Student> studenten;
public HogeschoolRotterdam() {
// TODO Maak de studenten list, en voeg enkele studenten toe
studenten = new ArrayList<Student>();
studenten.add(new Student("Jan", "Janssen", "Rotterdam"));
studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam"));
studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam"));
}
public List<Student> getStudenten() {
return this.studenten;
}
@Override
public Iterator iterator() {
return new HogeschoolRotterdamIterator(studenten);
}
}
| HTeker/Dessign-Patterns-Implementation | Opdrachten/src/Iterator/HogeschoolRotterdam.java | 243 | // TODO Maak de studenten list, en voeg enkele studenten toe | line_comment | nl | package Iterator;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Halil Teker on 6/24/2017.
*/
public class HogeschoolRotterdam implements Iterable {
private List<Student> studenten;
public HogeschoolRotterdam() {
// TODO Maak<SUF>
studenten = new ArrayList<Student>();
studenten.add(new Student("Jan", "Janssen", "Rotterdam"));
studenten.add(new Student("Chukwuemeka", "Aziz", "Rotterdam"));
studenten.add(new Student("Ravindra", "Dushyant", "Rotterdam"));
}
public List<Student> getStudenten() {
return this.studenten;
}
@Override
public Iterator iterator() {
return new HogeschoolRotterdamIterator(studenten);
}
}
|
106316_5 | package Opdracht_7;
/**
* Created by H.Teker on 16-3-2017.
* @author Halil Teker
* @version 1.0
*/
public class Fiets extends Vervoersmiddel {
/**
* Aantal fleshouders van de fiets
*/
int aantalFleshouders;
/**
* Bevat een true of false waarde of de fiets een terugtraprem systeem heeft
*/
boolean terugtraprem;
/**
* Zet de waarde voor de aantal fleshouders van de fiets
* @param aantalFleshouders
*/
public void setAantalFleshouders(int aantalFleshouders){
this.aantalFleshouders = aantalFleshouders;
}
/**
* Geeft het aantal fleshouders van de fiets terug
* @return
*/
public int getAantalFleshouders(){
return this.aantalFleshouders;
}
/**
* Zet de waarde of de fiets een terugtraprem heeft
* @param terugtraprem
*/
public void setTerugtraprem(boolean terugtraprem){
this.terugtraprem = terugtraprem;
}
/**
* Geeft of de fiets een terugtraprem heeft
* @return
*/
public boolean getTerugtraprem(){
return this.terugtraprem;
}
public void print(){
printRowOutlined("Capaciteit:", Integer.toString(this.getCapaciteit()));
printRowOutlined("Snelheid:", Float.toString(this.getSnelheid()));
printRowOutlined("Prijs:", Float.toString(this.getPrijs()));
printRowOutlined("Massa:", Float.toString(this.getMassa()));
printRowOutlined("Aantal fleshouders:", Integer.toString(this.getAantalFleshouders()));
printRowOutlined("Terugtraprem:", (this.getTerugtraprem()) ? "Ja" : "Nee");
System.out.printf("\n");
}
} | HTeker/Programmeeropdrachten-LJ1-OP3 | src/Opdracht_7/Fiets.java | 577 | /**
* Zet de waarde of de fiets een terugtraprem heeft
* @param terugtraprem
*/ | block_comment | nl | package Opdracht_7;
/**
* Created by H.Teker on 16-3-2017.
* @author Halil Teker
* @version 1.0
*/
public class Fiets extends Vervoersmiddel {
/**
* Aantal fleshouders van de fiets
*/
int aantalFleshouders;
/**
* Bevat een true of false waarde of de fiets een terugtraprem systeem heeft
*/
boolean terugtraprem;
/**
* Zet de waarde voor de aantal fleshouders van de fiets
* @param aantalFleshouders
*/
public void setAantalFleshouders(int aantalFleshouders){
this.aantalFleshouders = aantalFleshouders;
}
/**
* Geeft het aantal fleshouders van de fiets terug
* @return
*/
public int getAantalFleshouders(){
return this.aantalFleshouders;
}
/**
* Zet de waarde<SUF>*/
public void setTerugtraprem(boolean terugtraprem){
this.terugtraprem = terugtraprem;
}
/**
* Geeft of de fiets een terugtraprem heeft
* @return
*/
public boolean getTerugtraprem(){
return this.terugtraprem;
}
public void print(){
printRowOutlined("Capaciteit:", Integer.toString(this.getCapaciteit()));
printRowOutlined("Snelheid:", Float.toString(this.getSnelheid()));
printRowOutlined("Prijs:", Float.toString(this.getPrijs()));
printRowOutlined("Massa:", Float.toString(this.getMassa()));
printRowOutlined("Aantal fleshouders:", Integer.toString(this.getAantalFleshouders()));
printRowOutlined("Terugtraprem:", (this.getTerugtraprem()) ? "Ja" : "Nee");
System.out.printf("\n");
}
} |
21114_19 | package com.weatheradviceapp;
import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.evernote.android.job.JobManager;
import com.evernote.android.job.JobRequest;
import com.survivingwithandroid.weather.lib.model.Weather;
import com.weatheradviceapp.fragments.HomeFragment;
import com.weatheradviceapp.fragments.SettingsFragment;
import com.weatheradviceapp.helpers.AdviceFactory;
import com.weatheradviceapp.helpers.WeatherAdviceGenerator;
import com.weatheradviceapp.jobs.DemoCalendarJob;
import com.weatheradviceapp.jobs.DemoWeatherJob;
import com.weatheradviceapp.jobs.SyncCalendarJob;
import com.weatheradviceapp.jobs.SyncWeatherJob;
import com.weatheradviceapp.models.Advice;
import com.weatheradviceapp.models.User;
import com.weatheradviceapp.models.WeatherCondition;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private JobManager mJobManager;
private User user;
private BroadcastReceiver mMessageReceiver;
private static final String[] REQUIRED_PERMS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_CALENDAR
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get user or create user if we don't have one yet.
user = User.getOrCreateUser();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Require proper permissions.
if (!hasRequiredPermissions()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(REQUIRED_PERMS, 1);
}
}
// Initialize navigation drawer.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Allow intents for data updates.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SyncWeatherJob.WEATHER_AVAILABLE);
intentFilter.addAction(SyncCalendarJob.WEATHER_AVAILABLE);
// Intent receiver.
mMessageReceiver = new WeatherReceiver(new Handler());
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, intentFilter);
// Job manager for background processing.
mJobManager = JobManager.instance();
// Reset the job manager if we had any scheduled jobs.
mJobManager.cancelAll();
// Fetch weather/calendar data.
fetchWeather();
scheduleWeatherFetching();
// Schedule weather/calendar fetchers for background processing.
fetchCalendarWeather();
scheduleCalendarWeatherFetching();
// Init home fragment by default.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "home");
ft.commit();
}
private class WeatherReceiver extends BroadcastReceiver {
private final Handler uiHandler; // Handler used to execute code on the UI thread
public WeatherReceiver(Handler handler) {
this.uiHandler = handler;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(SyncWeatherJob.WEATHER_AVAILABLE)) {
// Post the UI updating code to our Handler.
uiHandler.post(new Runnable() {
@Override
public void run() {
HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("home");
if (homeFragment != null) {
homeFragment.refreshWeatherData();
homeFragment.disableRefresh();
}
checkForNotifications();
}
});
}
if (intent.getAction().equalsIgnoreCase(SyncCalendarJob.WEATHER_AVAILABLE)) {
// Post the UI updating code to our Handler.
uiHandler.post(new Runnable() {
@Override
public void run() {
HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("home");
if (homeFragment != null) {
homeFragment.refreshCalendarData();
homeFragment.disableRefresh();
}
}
});
}
}
}
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
public void fetchWeather() {
new JobRequest.Builder(user.isEnabledDemoMode() ? DemoWeatherJob.TAG : SyncWeatherJob.TAG)
.setExecutionWindow(3_000L, 4_000L)
.setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.LINEAR)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setPersisted(true)
.build()
.schedule();
}
private void scheduleWeatherFetching() {
new JobRequest.Builder(SyncWeatherJob.TAG)
.setPeriodic(JobRequest.MIN_INTERVAL, JobRequest.MIN_FLEX)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.build()
.schedule();
}
public void fetchCalendarWeather() {
new JobRequest.Builder(user.isEnabledDemoMode() ? DemoCalendarJob.TAG : SyncCalendarJob.TAG)
.setExecutionWindow(3_000L, 4_000L)
.setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.LINEAR)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setPersisted(true)
.build()
.schedule();
}
private void scheduleCalendarWeatherFetching() {
new JobRequest.Builder(SyncCalendarJob.TAG)
.setPeriodic(JobRequest.MIN_INTERVAL, JobRequest.MIN_FLEX)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.build()
.schedule();
}
@Override
public void onBackPressed() {
// Fix back back press, when backbutton is pressed, see if we had a fragment on the stack.
// Imitate activity behaviour.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
displayView(id);
break;
default:
displayView(id);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private boolean hasRequiredPermissions() {
for (String permision : REQUIRED_PERMS) {
if (!hasPermission(permision)) {
return false;
}
}
return true;
}
private boolean hasPermission(String perm) {
return (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, perm));
}
/**
* Helper to display a new fragment by menu item id.
*
* @param viewId
* The menu item ID to display the fragment for.
*/
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.weather_app_name);
switch (viewId) {
case R.id.nav_home:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case R.id.nav_settings:
fragment = new SettingsFragment();
title = getString(R.string.title_settings);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(title);
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
private PendingIntent preparePushNotification() {
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
return resultPendingIntent;
}
public void showPushNotification(Advice advice, int messageId) {
// @Gabriel, hier is een kopie van jouw code maar dan geparametriseerd met de advice. Omdat
// alle notifications het zelfde doen hoef je alleen de eigenschappen van de advice te
// gebruiken. Als je iets anders wilt weergeven dan moet je dat op de advice class toevoegen
// en in de concrete implementaties geef je dan de gewenste waarde terug. Bijvoorbeeld een
// andere tekst bij de herinnering.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(advice.getAdviceIconResource())
.setContentTitle(getString(R.string.weather_app_name))
.setContentText(advice.toString())
.setAutoCancel(true)
.setContentIntent(preparePushNotification());
mNotificationManager.notify(messageId, nBuilder.build());
// Nu nog uitvinden wanneer we de notificatie moeten aanroepen, ik denk dat we dat moeten
// doen als we niet weer ontvangen.
}
public void checkForNotifications() {
// Dit is van de HomeFragment.refreshWeatherData() gepakt. Ik weet nog niet wat de bedoeling
// precies is met de notifications maar ik kan me voorstellen dat deze code nog verplaatst
// moet worden naar een plek waarbij de adviezen maar 1 maal worden gegenereerd.
WeatherCondition latestWeatherCondition = WeatherCondition.getLatestWeatherCondition();
if (latestWeatherCondition != null) {
ArrayList<Weather> allWeathers = new ArrayList<>();
allWeathers.add(latestWeatherCondition.getWeather());
// Generate advice for all weather conditions
WeatherAdviceGenerator advGen = new WeatherAdviceGenerator(allWeathers, AdviceFactory.Filter.CLOTHING);
// En nu dus de eerste advice pakken en controleren of er wel positief advies is
if (advGen.size() > 0) {
Advice activity = advGen.get(0);
if (activity.getScore() > 40.0f) {
showPushNotification(activity, 1);
}
}
}
}
} | HTeker/Project-App | app/src/main/java/com/weatheradviceapp/MainActivity.java | 3,660 | // alle notifications het zelfde doen hoef je alleen de eigenschappen van de advice te | line_comment | nl | package com.weatheradviceapp;
import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.evernote.android.job.JobManager;
import com.evernote.android.job.JobRequest;
import com.survivingwithandroid.weather.lib.model.Weather;
import com.weatheradviceapp.fragments.HomeFragment;
import com.weatheradviceapp.fragments.SettingsFragment;
import com.weatheradviceapp.helpers.AdviceFactory;
import com.weatheradviceapp.helpers.WeatherAdviceGenerator;
import com.weatheradviceapp.jobs.DemoCalendarJob;
import com.weatheradviceapp.jobs.DemoWeatherJob;
import com.weatheradviceapp.jobs.SyncCalendarJob;
import com.weatheradviceapp.jobs.SyncWeatherJob;
import com.weatheradviceapp.models.Advice;
import com.weatheradviceapp.models.User;
import com.weatheradviceapp.models.WeatherCondition;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private JobManager mJobManager;
private User user;
private BroadcastReceiver mMessageReceiver;
private static final String[] REQUIRED_PERMS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_CALENDAR
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get user or create user if we don't have one yet.
user = User.getOrCreateUser();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Require proper permissions.
if (!hasRequiredPermissions()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(REQUIRED_PERMS, 1);
}
}
// Initialize navigation drawer.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Allow intents for data updates.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SyncWeatherJob.WEATHER_AVAILABLE);
intentFilter.addAction(SyncCalendarJob.WEATHER_AVAILABLE);
// Intent receiver.
mMessageReceiver = new WeatherReceiver(new Handler());
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, intentFilter);
// Job manager for background processing.
mJobManager = JobManager.instance();
// Reset the job manager if we had any scheduled jobs.
mJobManager.cancelAll();
// Fetch weather/calendar data.
fetchWeather();
scheduleWeatherFetching();
// Schedule weather/calendar fetchers for background processing.
fetchCalendarWeather();
scheduleCalendarWeatherFetching();
// Init home fragment by default.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "home");
ft.commit();
}
private class WeatherReceiver extends BroadcastReceiver {
private final Handler uiHandler; // Handler used to execute code on the UI thread
public WeatherReceiver(Handler handler) {
this.uiHandler = handler;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(SyncWeatherJob.WEATHER_AVAILABLE)) {
// Post the UI updating code to our Handler.
uiHandler.post(new Runnable() {
@Override
public void run() {
HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("home");
if (homeFragment != null) {
homeFragment.refreshWeatherData();
homeFragment.disableRefresh();
}
checkForNotifications();
}
});
}
if (intent.getAction().equalsIgnoreCase(SyncCalendarJob.WEATHER_AVAILABLE)) {
// Post the UI updating code to our Handler.
uiHandler.post(new Runnable() {
@Override
public void run() {
HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("home");
if (homeFragment != null) {
homeFragment.refreshCalendarData();
homeFragment.disableRefresh();
}
}
});
}
}
}
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
public void fetchWeather() {
new JobRequest.Builder(user.isEnabledDemoMode() ? DemoWeatherJob.TAG : SyncWeatherJob.TAG)
.setExecutionWindow(3_000L, 4_000L)
.setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.LINEAR)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setPersisted(true)
.build()
.schedule();
}
private void scheduleWeatherFetching() {
new JobRequest.Builder(SyncWeatherJob.TAG)
.setPeriodic(JobRequest.MIN_INTERVAL, JobRequest.MIN_FLEX)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.build()
.schedule();
}
public void fetchCalendarWeather() {
new JobRequest.Builder(user.isEnabledDemoMode() ? DemoCalendarJob.TAG : SyncCalendarJob.TAG)
.setExecutionWindow(3_000L, 4_000L)
.setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.LINEAR)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setPersisted(true)
.build()
.schedule();
}
private void scheduleCalendarWeatherFetching() {
new JobRequest.Builder(SyncCalendarJob.TAG)
.setPeriodic(JobRequest.MIN_INTERVAL, JobRequest.MIN_FLEX)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.build()
.schedule();
}
@Override
public void onBackPressed() {
// Fix back back press, when backbutton is pressed, see if we had a fragment on the stack.
// Imitate activity behaviour.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
displayView(id);
break;
default:
displayView(id);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private boolean hasRequiredPermissions() {
for (String permision : REQUIRED_PERMS) {
if (!hasPermission(permision)) {
return false;
}
}
return true;
}
private boolean hasPermission(String perm) {
return (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, perm));
}
/**
* Helper to display a new fragment by menu item id.
*
* @param viewId
* The menu item ID to display the fragment for.
*/
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.weather_app_name);
switch (viewId) {
case R.id.nav_home:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case R.id.nav_settings:
fragment = new SettingsFragment();
title = getString(R.string.title_settings);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(title);
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
private PendingIntent preparePushNotification() {
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
return resultPendingIntent;
}
public void showPushNotification(Advice advice, int messageId) {
// @Gabriel, hier is een kopie van jouw code maar dan geparametriseerd met de advice. Omdat
// alle notifications<SUF>
// gebruiken. Als je iets anders wilt weergeven dan moet je dat op de advice class toevoegen
// en in de concrete implementaties geef je dan de gewenste waarde terug. Bijvoorbeeld een
// andere tekst bij de herinnering.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(advice.getAdviceIconResource())
.setContentTitle(getString(R.string.weather_app_name))
.setContentText(advice.toString())
.setAutoCancel(true)
.setContentIntent(preparePushNotification());
mNotificationManager.notify(messageId, nBuilder.build());
// Nu nog uitvinden wanneer we de notificatie moeten aanroepen, ik denk dat we dat moeten
// doen als we niet weer ontvangen.
}
public void checkForNotifications() {
// Dit is van de HomeFragment.refreshWeatherData() gepakt. Ik weet nog niet wat de bedoeling
// precies is met de notifications maar ik kan me voorstellen dat deze code nog verplaatst
// moet worden naar een plek waarbij de adviezen maar 1 maal worden gegenereerd.
WeatherCondition latestWeatherCondition = WeatherCondition.getLatestWeatherCondition();
if (latestWeatherCondition != null) {
ArrayList<Weather> allWeathers = new ArrayList<>();
allWeathers.add(latestWeatherCondition.getWeather());
// Generate advice for all weather conditions
WeatherAdviceGenerator advGen = new WeatherAdviceGenerator(allWeathers, AdviceFactory.Filter.CLOTHING);
// En nu dus de eerste advice pakken en controleren of er wel positief advies is
if (advGen.size() > 0) {
Advice activity = advGen.get(0);
if (activity.getScore() > 40.0f) {
showPushNotification(activity, 1);
}
}
}
}
} |
37915_1 | package bep.chatapp.client;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatAppController {
@FXML private TextField chatField;
@FXML private TextArea chatBox;
@FXML private Button submit;
@FXML private TextField chatName;
private Socket connection;
private PrintWriter serverWriter;
public ChatAppController() {
/*
* Open hier een socket naar de server (waarschijnlijk localhost),
* en ken deze socket toe (assignment) aan het attribuut 'verbinding'.
*
* Start een MessageListener-thread (zie onder).
* Geef een melding in de chatBox als er iets misgaat (exception).
*/
}
@FXML
private void sendMessage() {
/*
* Controleer of er een gebruikersnaam is ingevoerd, of geef een melding in de chatBox
* Controleer of er een bericht is ingevoerd, of geef een melding in de chatBox!
*
* Disable het TextField waarin de gebruikersnaam is ingevoerd zodat deze niet gewijzigd kan worden!
* Gebruik het attribuut 'serverWriter' om een bericht naar de server te printen!
* Het bericht moet bevatten: "Naam" : "Bericht"
*
* Maak het chatField leeg om weer een nieuw bericht te kunnen typen!
*/
}
private class MessageListener extends Thread {
public void run() {
/*
* Open de inputstream van de socket, en bekijk met (bijv.)
* een Scanner of 'next lines' zijn. Als er een nieuwe regel
* (chatbericht) binnenkomt, print deze dan in de chatBox.
*
* Dit proces moet doorgaan totdat er geen 'next lines' meer
* zijn (wat betekent dat de socket is gesloten).
*/
}
}
public void closeConnection() {
/* Sluit hier de Socket! */
}
} | HU-BEP/ChatApp | src/bep/chatapp/client/ChatAppController.java | 566 | /*
* Controleer of er een gebruikersnaam is ingevoerd, of geef een melding in de chatBox
* Controleer of er een bericht is ingevoerd, of geef een melding in de chatBox!
*
* Disable het TextField waarin de gebruikersnaam is ingevoerd zodat deze niet gewijzigd kan worden!
* Gebruik het attribuut 'serverWriter' om een bericht naar de server te printen!
* Het bericht moet bevatten: "Naam" : "Bericht"
*
* Maak het chatField leeg om weer een nieuw bericht te kunnen typen!
*/ | block_comment | nl | package bep.chatapp.client;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatAppController {
@FXML private TextField chatField;
@FXML private TextArea chatBox;
@FXML private Button submit;
@FXML private TextField chatName;
private Socket connection;
private PrintWriter serverWriter;
public ChatAppController() {
/*
* Open hier een socket naar de server (waarschijnlijk localhost),
* en ken deze socket toe (assignment) aan het attribuut 'verbinding'.
*
* Start een MessageListener-thread (zie onder).
* Geef een melding in de chatBox als er iets misgaat (exception).
*/
}
@FXML
private void sendMessage() {
/*
* Controleer of er<SUF>*/
}
private class MessageListener extends Thread {
public void run() {
/*
* Open de inputstream van de socket, en bekijk met (bijv.)
* een Scanner of 'next lines' zijn. Als er een nieuwe regel
* (chatbericht) binnenkomt, print deze dan in de chatBox.
*
* Dit proces moet doorgaan totdat er geen 'next lines' meer
* zijn (wat betekent dat de socket is gesloten).
*/
}
}
public void closeConnection() {
/* Sluit hier de Socket! */
}
} |
140208_0 | package nl.hu.sd.inno.basicboot.shop.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE) //In geval van twijfel is Sequence beter dan Identity
private Long id;
private int nrAvailable;
private double price;
private String name;
protected Product() {
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public int getNrAvailable() {
return nrAvailable;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void deliver(int nr) {
this.nrAvailable += nr;
}
public void order(int nr) {
this.nrAvailable -= nr;
}
}
| HU-Inno-SD/demos | basicboot/src/main/java/nl/hu/sd/inno/basicboot/shop/domain/Product.java | 279 | //In geval van twijfel is Sequence beter dan Identity | line_comment | nl | package nl.hu.sd.inno.basicboot.shop.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE) //In geval<SUF>
private Long id;
private int nrAvailable;
private double price;
private String name;
protected Product() {
}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public int getNrAvailable() {
return nrAvailable;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void deliver(int nr) {
this.nrAvailable += nr;
}
public void order(int nr) {
this.nrAvailable -= nr;
}
}
|
20865_0 | package nl.hu.inno.thuusbezorgd.orders.application;
import nl.hu.inno.thuusbezorgd.orders.data.UserRepository;
import nl.hu.inno.thuusbezorgd.orders.domain.User;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.server.ResponseStatusException;
import java.util.Optional;
/**
* Dit is natuurlijk -juist geen- security, maar ik merkte dat hier nette voorbeeldcode van aanleveren meer was dan de rest
* van de applicatie bij elkaar. Dus dat leek me een beetje onhandig
*/
public class UserResolver implements HandlerMethodArgumentResolver {
private final UserRepository users;
public UserResolver(UserRepository users) {
this.users = users;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameter().getType() == User.class;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String username = webRequest.getHeader("Authentication-Hack");
Exception unauthorized = new ResponseStatusException(HttpStatus.UNAUTHORIZED, "No user found, use Authentication-Hack header");
if (username == null) {
throw unauthorized;
}
Optional<User> result = users.findById(username);
return result.orElseThrow(() -> unauthorized);
}
} | HU-Inno-SD/thuusbezorgd-Martenelsinga | order/src/main/java/nl/hu/inno/thuusbezorgd/orders/application/UserResolver.java | 460 | /**
* Dit is natuurlijk -juist geen- security, maar ik merkte dat hier nette voorbeeldcode van aanleveren meer was dan de rest
* van de applicatie bij elkaar. Dus dat leek me een beetje onhandig
*/ | block_comment | nl | package nl.hu.inno.thuusbezorgd.orders.application;
import nl.hu.inno.thuusbezorgd.orders.data.UserRepository;
import nl.hu.inno.thuusbezorgd.orders.domain.User;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.server.ResponseStatusException;
import java.util.Optional;
/**
* Dit is natuurlijk<SUF>*/
public class UserResolver implements HandlerMethodArgumentResolver {
private final UserRepository users;
public UserResolver(UserRepository users) {
this.users = users;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameter().getType() == User.class;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
String username = webRequest.getHeader("Authentication-Hack");
Exception unauthorized = new ResponseStatusException(HttpStatus.UNAUTHORIZED, "No user found, use Authentication-Hack header");
if (username == null) {
throw unauthorized;
}
Optional<User> result = users.findById(username);
return result.orElseThrow(() -> unauthorized);
}
} |
108604_0 | package nl.hu.inno.thuusbezorgd;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@Primary
public class FakeTimeProvider implements TimeProvider{
private LocalDateTime now;
public FakeTimeProvider(){
//We gaan eten bestellen alsof het 1999 is!
this.now = LocalDateTime.of(1999, 7, 31, 17, 25);
}
@Override
public LocalDateTime now() {
return now;
}
public void setNow(LocalDateTime now) {
this.now = now;
}
public void advanceDay() {
this.now = this.now.plusDays(1);
}
public synchronized void advanceMinute(){
this.now = this.now.plusMinutes(1);
}
}
| HU-Inno-SD/thuusbezorgd-RobertLanting | src/main/java/nl/hu/inno/thuusbezorgd/FakeTimeProvider.java | 231 | //We gaan eten bestellen alsof het 1999 is! | line_comment | nl | package nl.hu.inno.thuusbezorgd;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@Primary
public class FakeTimeProvider implements TimeProvider{
private LocalDateTime now;
public FakeTimeProvider(){
//We gaan<SUF>
this.now = LocalDateTime.of(1999, 7, 31, 17, 25);
}
@Override
public LocalDateTime now() {
return now;
}
public void setNow(LocalDateTime now) {
this.now = now;
}
public void advanceDay() {
this.now = this.now.plusDays(1);
}
public synchronized void advanceMinute(){
this.now = this.now.plusMinutes(1);
}
}
|
87627_0 |
import Presentiesysteem.*;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.print.Doc;
import java.sql.Time;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class PresentieSysteem extends Application {
public static void main(String[] args){
try {
SysteemGebruikers sg = new SysteemGebruikers();
Klas k1 = new Klas("KL13-A");
Klas k2 = new Klas("KL13-B");
School HU = new School("Hogeschool Utrecht");
HU.klasToevoegen(k1);
HU.klasToevoegen(k2);
//voorbeeld studenten en docenten aanmaken en aan klassen toevoegen
Docent d1 = new Docent("Harry Haar","[email protected]","wachtwoordharry","docent");
Docent d2 = new Docent("Karen Kaal","[email protected]","wachtwoordkaren","docent");
Docent d3 = new Docent("Karel Klein","[email protected]","wachtwoordkarel","docent");
Docent d4 = new Docent("Harry Baals","[email protected]","wachtwoordharry","docent");
Docent d5 = new Docent("Vera Plant","[email protected]","wachtwoordvera","docent");
Student s1 = new Student("Bob Bouwers", "[email protected]", "wachtwoordbob", 1234,"student","","","Aangemeld");
Student s2 = new Student("Dirk Droog", "[email protected]", "wachtwoorddirk", 1235,"student","","","Aangemeld");
Student s3 = new Student("Kate Boom", "[email protected]", "wachtwoordkate", 1236,"student","","","Aangemeld");
Student s4 = new Student("Piet Vis", "[email protected]", "wachtwoordpiet", 1237,"student","","","Aangemeld");
Student s5 = new Student("Ronald Ding", "[email protected]", "wachtwoordRondald", 1238,"student","","","Aangemeld");
Student s6 = new Student("Steven Droogbrood", "[email protected]", "wachtwoordsteven", 1239,"student","","","Aangemeld");
Student s7 = new Student("Peter Steelpan", "[email protected]", "wachtwoordpeter", 1240,"student","","","Aangemeld");
k1.studentToevoegen(s1) ;
k1.studentToevoegen(s2);
k1.studentToevoegen(s3);
k1.studentToevoegen(s4);
k1.studentToevoegen(s5);
k1.studentToevoegen(s6);
k1.studentToevoegen(s7);
Student s8 = new Student("Ding Dong", "[email protected]", "wachtwoordding", 1241,"student","","","Aangemeld");
Student s9 = new Student("Appel Boom", "[email protected]", "wachtwoordappel", 1242,"student","","","Aangemeld");
Student s10 = new Student("Man Super", "[email protected]", "wachtwoordman", 1243,"student","","","Aangemeld");
Student s11 = new Student("Karel Doei", "[email protected]", "wachtwoordkarel", 1244,"student","","","Aangemeld");
Student s12 = new Student("Pieter Vlieger", "[email protected]", "wachtwoordpieter", 1245,"student","","","Aangemeld");
Student s13 = new Student("Nick Bloem", "[email protected]", "wachtwoordnick", 1246,"student","","","Aangemeld");
Student s14 = new Student("Jan Spons", "[email protected]", "wachtwoordjan", 1247,"student","","","Aangemeld");
k2.studentToevoegen(s8);
k2.studentToevoegen(s9);
k2.studentToevoegen(s10);
k2.studentToevoegen(s11);
k2.studentToevoegen(s12);
k2.studentToevoegen(s13);
k2.studentToevoegen(s14);
//voorbeeld student presentie inzien
LocalDate datum1 = LocalDate.now().minusDays(1);
LocalDate datum2 = LocalDate.now().minusDays(2);
LocalDate datum3 = LocalDate.now().minusDays(3);
LocalDate datum4 = LocalDate.now().minusDays(4);
LocalDate datum5 = LocalDate.now().minusYears(5);
s2.presentietoevoegen(s2.getNaam(), datum5, "Nederlands", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum4,"Duits", "absent","weg gestuurd" );
s2.presentietoevoegen(s2.getNaam(), datum3,"Biologie", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum2,"Frans", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum1,"", "Afgemeld","Ziek" );
//studenten en docenten als gebruikers toevoegen
for(Student s : k1.getStudenten()){
sg.gebruikerToevoegen(s);
}
for(Student s : k2.getStudenten()){
sg.gebruikerToevoegen(s);
}
sg.gebruikerToevoegen(d1);
sg.gebruikerToevoegen(d2);
sg.gebruikerToevoegen(d3);
sg.gebruikerToevoegen(d4);
sg.gebruikerToevoegen(d5);
//klas KL13-A
// voorbeeld lessen maandag
Les l1 = new Les("Nederlands", DayOfWeek.MONDAY , "09:00", "12:00", d1,"HL15-6.321","");
Les l2 = new Les("Duits",DayOfWeek.MONDAY , "12:30", "13:20", d2,"HL15-5.085","");
Les l3 = new Les("Rekenen",DayOfWeek.MONDAY , "13:25", "14:15", d3,"HL15-6.321","");
Les l4 = new Les("Gym",DayOfWeek.MONDAY , "14:20", "15:10", d4,"HL15-5.085","");
Les l5 = new Les("Biologie",DayOfWeek.MONDAY , "15:25", "16:15", d5,"HL15-5.080","");
k1.lesToevoegen(l1);
k1.lesToevoegen(l2);
k1.lesToevoegen(l3);
k1.lesToevoegen(l4);
k1.lesToevoegen(l5);
// voorbeeld lessen dinsdag
Les l6 = new Les("Rekenen",DayOfWeek.TUESDAY, "12:30", "13:20", d3,"HL15-6.030","");
Les l7 = new Les("Biologie",DayOfWeek.TUESDAY , "13:25", "14:15", d1,"HL15-6.321","");
Les l8 = new Les("Gym",DayOfWeek.TUESDAY , "14:20", "15:10", d4,"HL15-5.080","");
Les l9 = new Les("Frans",DayOfWeek.TUESDAY , "15:25", "16:15", d1,"HL15-5.085","");
k1.lesToevoegen(l6);
k1.lesToevoegen(l7);
k1.lesToevoegen(l8);
k1.lesToevoegen(l9);
// voorbeeld lessen woensdag
Les l10 = new Les("Nederlands", DayOfWeek.WEDNESDAY , "09:00", "12:00", d1,"HL15-5.080","");
Les l12 = new Les("Duits",DayOfWeek.WEDNESDAY , "12:30", "13:20", d2,"HL15-6.030","");
Les l13 = new Les("Rekenen",DayOfWeek.WEDNESDAY , "13:25", "14:15", d3,"HL15-6.321","");
Les l14 = new Les("Gym",DayOfWeek.WEDNESDAY , "14:20", "15:10", d4,"HL15-5.085","");
Les l15 = new Les("Biologie",DayOfWeek.WEDNESDAY , "15:25", "16:15", d5,"HL15-5.080","");
k1.lesToevoegen(l10);
k1.lesToevoegen(l12);
k1.lesToevoegen(l13);
k1.lesToevoegen(l14);
k1.lesToevoegen(l15);
// voorbeeld lessen donderdag
Les l16 = new Les("Rekenen",DayOfWeek.THURSDAY, "12:30", "13:20", d3,"HL15-6.321","");
Les l17 = new Les("Biologie",DayOfWeek.THURSDAY , "13:25", "14:15", d1,"HL15-5.085","");
Les l18 = new Les("Gym",DayOfWeek.THURSDAY , "14:20", "15:10", d4,"HL15-5.080","");
Les l19 = new Les("Frans",DayOfWeek.THURSDAY , "15:25", "16:15", d1,"HL15-6.321","");
k1.lesToevoegen(l16);
k1.lesToevoegen(l17);
k1.lesToevoegen(l18);
k1.lesToevoegen(l19);
// voorbeeld lessen vrijdag
Les l20 = new Les("Nederlands", DayOfWeek.FRIDAY, "09:00", "12:00", d1,"HL15-5.080","");
Les l21 = new Les("Duits",DayOfWeek.FRIDAY , "12:30", "13:20", d2,"HL15-6.321","");
k1.lesToevoegen(l20);
k1.lesToevoegen(l21);
}catch (Exception e){
System.out.println(e);
}
launch(args);
}
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("GUI_Presentiesysteem/inlogScherm.fxml"));
Parent root = loader.load();
stage.setTitle("inlogscherm");
stage.setScene(new Scene(root));
stage.setResizable(false);
stage.show();
}
}
| HU-SD-GP-studenten-2122/v1b-groep-6 | SD Group Project/ProjectRegistratieSysteem/src/PresentieSysteem.java | 3,064 | //voorbeeld studenten en docenten aanmaken en aan klassen toevoegen
| line_comment | nl |
import Presentiesysteem.*;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.print.Doc;
import java.sql.Time;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class PresentieSysteem extends Application {
public static void main(String[] args){
try {
SysteemGebruikers sg = new SysteemGebruikers();
Klas k1 = new Klas("KL13-A");
Klas k2 = new Klas("KL13-B");
School HU = new School("Hogeschool Utrecht");
HU.klasToevoegen(k1);
HU.klasToevoegen(k2);
//voorbeeld studenten<SUF>
Docent d1 = new Docent("Harry Haar","[email protected]","wachtwoordharry","docent");
Docent d2 = new Docent("Karen Kaal","[email protected]","wachtwoordkaren","docent");
Docent d3 = new Docent("Karel Klein","[email protected]","wachtwoordkarel","docent");
Docent d4 = new Docent("Harry Baals","[email protected]","wachtwoordharry","docent");
Docent d5 = new Docent("Vera Plant","[email protected]","wachtwoordvera","docent");
Student s1 = new Student("Bob Bouwers", "[email protected]", "wachtwoordbob", 1234,"student","","","Aangemeld");
Student s2 = new Student("Dirk Droog", "[email protected]", "wachtwoorddirk", 1235,"student","","","Aangemeld");
Student s3 = new Student("Kate Boom", "[email protected]", "wachtwoordkate", 1236,"student","","","Aangemeld");
Student s4 = new Student("Piet Vis", "[email protected]", "wachtwoordpiet", 1237,"student","","","Aangemeld");
Student s5 = new Student("Ronald Ding", "[email protected]", "wachtwoordRondald", 1238,"student","","","Aangemeld");
Student s6 = new Student("Steven Droogbrood", "[email protected]", "wachtwoordsteven", 1239,"student","","","Aangemeld");
Student s7 = new Student("Peter Steelpan", "[email protected]", "wachtwoordpeter", 1240,"student","","","Aangemeld");
k1.studentToevoegen(s1) ;
k1.studentToevoegen(s2);
k1.studentToevoegen(s3);
k1.studentToevoegen(s4);
k1.studentToevoegen(s5);
k1.studentToevoegen(s6);
k1.studentToevoegen(s7);
Student s8 = new Student("Ding Dong", "[email protected]", "wachtwoordding", 1241,"student","","","Aangemeld");
Student s9 = new Student("Appel Boom", "[email protected]", "wachtwoordappel", 1242,"student","","","Aangemeld");
Student s10 = new Student("Man Super", "[email protected]", "wachtwoordman", 1243,"student","","","Aangemeld");
Student s11 = new Student("Karel Doei", "[email protected]", "wachtwoordkarel", 1244,"student","","","Aangemeld");
Student s12 = new Student("Pieter Vlieger", "[email protected]", "wachtwoordpieter", 1245,"student","","","Aangemeld");
Student s13 = new Student("Nick Bloem", "[email protected]", "wachtwoordnick", 1246,"student","","","Aangemeld");
Student s14 = new Student("Jan Spons", "[email protected]", "wachtwoordjan", 1247,"student","","","Aangemeld");
k2.studentToevoegen(s8);
k2.studentToevoegen(s9);
k2.studentToevoegen(s10);
k2.studentToevoegen(s11);
k2.studentToevoegen(s12);
k2.studentToevoegen(s13);
k2.studentToevoegen(s14);
//voorbeeld student presentie inzien
LocalDate datum1 = LocalDate.now().minusDays(1);
LocalDate datum2 = LocalDate.now().minusDays(2);
LocalDate datum3 = LocalDate.now().minusDays(3);
LocalDate datum4 = LocalDate.now().minusDays(4);
LocalDate datum5 = LocalDate.now().minusYears(5);
s2.presentietoevoegen(s2.getNaam(), datum5, "Nederlands", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum4,"Duits", "absent","weg gestuurd" );
s2.presentietoevoegen(s2.getNaam(), datum3,"Biologie", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum2,"Frans", "present","" );
s2.presentietoevoegen(s2.getNaam(), datum1,"", "Afgemeld","Ziek" );
//studenten en docenten als gebruikers toevoegen
for(Student s : k1.getStudenten()){
sg.gebruikerToevoegen(s);
}
for(Student s : k2.getStudenten()){
sg.gebruikerToevoegen(s);
}
sg.gebruikerToevoegen(d1);
sg.gebruikerToevoegen(d2);
sg.gebruikerToevoegen(d3);
sg.gebruikerToevoegen(d4);
sg.gebruikerToevoegen(d5);
//klas KL13-A
// voorbeeld lessen maandag
Les l1 = new Les("Nederlands", DayOfWeek.MONDAY , "09:00", "12:00", d1,"HL15-6.321","");
Les l2 = new Les("Duits",DayOfWeek.MONDAY , "12:30", "13:20", d2,"HL15-5.085","");
Les l3 = new Les("Rekenen",DayOfWeek.MONDAY , "13:25", "14:15", d3,"HL15-6.321","");
Les l4 = new Les("Gym",DayOfWeek.MONDAY , "14:20", "15:10", d4,"HL15-5.085","");
Les l5 = new Les("Biologie",DayOfWeek.MONDAY , "15:25", "16:15", d5,"HL15-5.080","");
k1.lesToevoegen(l1);
k1.lesToevoegen(l2);
k1.lesToevoegen(l3);
k1.lesToevoegen(l4);
k1.lesToevoegen(l5);
// voorbeeld lessen dinsdag
Les l6 = new Les("Rekenen",DayOfWeek.TUESDAY, "12:30", "13:20", d3,"HL15-6.030","");
Les l7 = new Les("Biologie",DayOfWeek.TUESDAY , "13:25", "14:15", d1,"HL15-6.321","");
Les l8 = new Les("Gym",DayOfWeek.TUESDAY , "14:20", "15:10", d4,"HL15-5.080","");
Les l9 = new Les("Frans",DayOfWeek.TUESDAY , "15:25", "16:15", d1,"HL15-5.085","");
k1.lesToevoegen(l6);
k1.lesToevoegen(l7);
k1.lesToevoegen(l8);
k1.lesToevoegen(l9);
// voorbeeld lessen woensdag
Les l10 = new Les("Nederlands", DayOfWeek.WEDNESDAY , "09:00", "12:00", d1,"HL15-5.080","");
Les l12 = new Les("Duits",DayOfWeek.WEDNESDAY , "12:30", "13:20", d2,"HL15-6.030","");
Les l13 = new Les("Rekenen",DayOfWeek.WEDNESDAY , "13:25", "14:15", d3,"HL15-6.321","");
Les l14 = new Les("Gym",DayOfWeek.WEDNESDAY , "14:20", "15:10", d4,"HL15-5.085","");
Les l15 = new Les("Biologie",DayOfWeek.WEDNESDAY , "15:25", "16:15", d5,"HL15-5.080","");
k1.lesToevoegen(l10);
k1.lesToevoegen(l12);
k1.lesToevoegen(l13);
k1.lesToevoegen(l14);
k1.lesToevoegen(l15);
// voorbeeld lessen donderdag
Les l16 = new Les("Rekenen",DayOfWeek.THURSDAY, "12:30", "13:20", d3,"HL15-6.321","");
Les l17 = new Les("Biologie",DayOfWeek.THURSDAY , "13:25", "14:15", d1,"HL15-5.085","");
Les l18 = new Les("Gym",DayOfWeek.THURSDAY , "14:20", "15:10", d4,"HL15-5.080","");
Les l19 = new Les("Frans",DayOfWeek.THURSDAY , "15:25", "16:15", d1,"HL15-6.321","");
k1.lesToevoegen(l16);
k1.lesToevoegen(l17);
k1.lesToevoegen(l18);
k1.lesToevoegen(l19);
// voorbeeld lessen vrijdag
Les l20 = new Les("Nederlands", DayOfWeek.FRIDAY, "09:00", "12:00", d1,"HL15-5.080","");
Les l21 = new Les("Duits",DayOfWeek.FRIDAY , "12:30", "13:20", d2,"HL15-6.321","");
k1.lesToevoegen(l20);
k1.lesToevoegen(l21);
}catch (Exception e){
System.out.println(e);
}
launch(args);
}
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("GUI_Presentiesysteem/inlogScherm.fxml"));
Parent root = loader.load();
stage.setTitle("inlogscherm");
stage.setScene(new Scene(root));
stage.setResizable(false);
stage.show();
}
}
|
187315_0 | package nl.hu.bep;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
//TODO: Deze class moet uiteraard weg zodra je zelf nuttige tests hebt geschreven!
public class DemoTest {
@Test
public void junitDoetHet() {
assertEquals(2, 1 + 1);
}
}
| HU-SD-V1BEP-studenten-2122/finalassignment-Lookie4Fun | src/test/java/nl/hu/bep/DemoTest.java | 108 | //TODO: Deze class moet uiteraard weg zodra je zelf nuttige tests hebt geschreven! | line_comment | nl | package nl.hu.bep;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
//TODO: Deze<SUF>
public class DemoTest {
@Test
public void junitDoetHet() {
assertEquals(2, 1 + 1);
}
}
|
65454_6 | package technology.direct.dao;
public class CallInstanceOuterClassDAO {
// create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public CallInstanceOuterClassDAO() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// print out values of even indices of the array
CallInstanceInnerClassDAO iterator = this.new CallInstanceInnerClassDAO();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
public void callConstructorInnerClass() {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO();
}
public void callDefaultConstructorInnerClass() {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO();
}
// inner class implements the Iterator pattern
public class CallInstanceInnerClassDAO {
// start stepping through the array from the beginning
private int next = 0;
private TestConstructorCallOfInnerClass otherInnerClass;
public String text;
public CallInstanceInnerClassDAO() {
this.text = "s";
}
public CallInstanceInnerClassDAO(String s) {
this.text = s;
}
public CallInstanceInnerClassDAO(TestConstructorCallOfInnerClass otherInner) {
this.otherInnerClass = otherInner;
}
public boolean hasNext() {
return true ;
}
public int getNext() {
// record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public enum InnerEnumeration {
ONE,TWO,THREE,FOUR;
}
public interface CallInstanceInnerInterfaceDAO {
public void InterfaceMethod();
}
public static class StaticNestedClass {
CallInstanceOuterClassDAO outer;
String var;
public StaticNestedClass() {
this.var = "s";
}
public StaticNestedClass(String var) {
this.var = var;
}
public CallInstanceOuterClassDAO getOuter() {
return outer;
}
}
public class TestConstructorCallOfInnerClass {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO(this);
}
} | HUSACCT/HUSACCT | testresources/java/accuracy/src/technology/direct/dao/CallInstanceOuterClassDAO.java | 803 | //get the next even element
| line_comment | nl | package technology.direct.dao;
public class CallInstanceOuterClassDAO {
// create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public CallInstanceOuterClassDAO() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// print out values of even indices of the array
CallInstanceInnerClassDAO iterator = this.new CallInstanceInnerClassDAO();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
public void callConstructorInnerClass() {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO();
}
public void callDefaultConstructorInnerClass() {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO();
}
// inner class implements the Iterator pattern
public class CallInstanceInnerClassDAO {
// start stepping through the array from the beginning
private int next = 0;
private TestConstructorCallOfInnerClass otherInnerClass;
public String text;
public CallInstanceInnerClassDAO() {
this.text = "s";
}
public CallInstanceInnerClassDAO(String s) {
this.text = s;
}
public CallInstanceInnerClassDAO(TestConstructorCallOfInnerClass otherInner) {
this.otherInnerClass = otherInner;
}
public boolean hasNext() {
return true ;
}
public int getNext() {
// record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the<SUF>
next += 2;
return retValue;
}
}
public enum InnerEnumeration {
ONE,TWO,THREE,FOUR;
}
public interface CallInstanceInnerInterfaceDAO {
public void InterfaceMethod();
}
public static class StaticNestedClass {
CallInstanceOuterClassDAO outer;
String var;
public StaticNestedClass() {
this.var = "s";
}
public StaticNestedClass(String var) {
this.var = var;
}
public CallInstanceOuterClassDAO getOuter() {
return outer;
}
}
public class TestConstructorCallOfInnerClass {
CallInstanceOuterClassDAO.CallInstanceInnerClassDAO i = new CallInstanceOuterClassDAO.CallInstanceInnerClassDAO(this);
}
} |
160112_1 | package main.java.game31.userinterface;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import main.java.game31.domain.gamecontrol.Spel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* This code was generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a
* for-profit company or business) then you should purchase
* a license - please visit www.cloudgarden.com for details.
*/
public class MainFrame extends javax.swing.JFrame {
private JMenuItem exitItem;
private JMenuItem nieuwspelItem;
private TheMainPanel theMainPanel;
private JLabel transparantVlak5_1;
private JLabel transparantVlak5;
private JLabel transparantVlak4_1;
private JLabel transparantVlak4;
private JLabel transparantVlak3;
private JLabel transparantVlak2;
private JLabel transparantVlak1;
private JMenu spelMenu;
private JMenuBar theMenuBar;
private JLabel bgPictureLabel;
private boolean gameStarted = false;
private int aantalFices;
public MainFrame(int i) {
initGUI();
this.setVisible(true);
SetupFrame sf = new SetupFrame(this);
}
public MainFrame() {
initGUI();
this.setVisible(true);
SetupFrame sf = new SetupFrame(this);
}
public void updateUI() {
theMainPanel.updateScherm();
}
public void newRound() {
theMainPanel.eersteBeurt();
}
public void nieuwSpel() {
SetupFrame sf = new SetupFrame(this);
}
public void loadSpelerSetup(int aantalSpelers, int aantalFices, boolean opEzeltje, boolean metStok) {
setupSpelers ss = new setupSpelers(aantalSpelers, this);
this.aantalFices = aantalFices;
}
public void startHetSpel(Vector computerSpelers, Vector menselijkeSpelers) {
Spel hetSpel = new Spel(computerSpelers, menselijkeSpelers, aantalFices, this);
theMainPanel.startSpel(hetSpel);
//Geef TheMainpanel het spel.
}
/**
* Initializes the GUI.
* Auto-generated code - any changes you make will disappear.
*/
public void initGUI(){
try {
preInitGUI();
theMainPanel = new TheMainPanel();
bgPictureLabel = new JLabel();
transparantVlak1 = new JLabel();
transparantVlak2 = new JLabel();
transparantVlak3 = new JLabel();
transparantVlak4 = new JLabel();
transparantVlak4_1 = new JLabel();
transparantVlak5 = new JLabel();
transparantVlak5_1 = new JLabel();
this.getContentPane().setLayout(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(true);
this.setTitle("31-en The Game");
this.setSize(new java.awt.Dimension(707,577));
theMainPanel.setVisible(true);
theMainPanel.setPreferredSize(new java.awt.Dimension(700,527));
theMainPanel.setBounds(new java.awt.Rectangle(0,0,700,527));
this.getContentPane().add(theMainPanel);
bgPictureLabel.setHorizontalAlignment(SwingConstants.LEFT);
bgPictureLabel.setHorizontalTextPosition(SwingConstants.LEFT);
bgPictureLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/mainFrameBackground.jpg")));
bgPictureLabel.setIconTextGap(0);
bgPictureLabel.setVerticalAlignment(SwingConstants.TOP);
bgPictureLabel.setVerticalTextPosition(SwingConstants.TOP);
bgPictureLabel.setVisible(true);
bgPictureLabel.setPreferredSize(new java.awt.Dimension(700,529));
bgPictureLabel.setOpaque(true);
bgPictureLabel.setRequestFocusEnabled(false);
bgPictureLabel.setVerifyInputWhenFocusTarget(true);
bgPictureLabel.setBounds(new java.awt.Rectangle(0,0,700,529));
bgPictureLabel.setFocusTraversalKeysEnabled(false);
bgPictureLabel.setFocusable(false);
bgPictureLabel.setIgnoreRepaint(true);
this.getContentPane().add(bgPictureLabel);
transparantVlak1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak1.setPreferredSize(new java.awt.Dimension(197,229));
transparantVlak1.setBounds(new java.awt.Rectangle(0,0,197,229));
bgPictureLabel.add(transparantVlak1);
transparantVlak2.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak2.setPreferredSize(new java.awt.Dimension(197,299));
transparantVlak2.setBounds(new java.awt.Rectangle(0,229,197,299));
bgPictureLabel.add(transparantVlak2);
transparantVlak3.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak3.setPreferredSize(new java.awt.Dimension(464,32));
transparantVlak3.setBounds(new java.awt.Rectangle(216,231,464,32));
bgPictureLabel.add(transparantVlak3);
transparantVlak4.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak4.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak4.setBounds(new java.awt.Rectangle(233,20,421,195));
bgPictureLabel.add(transparantVlak4);
transparantVlak4_1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak4_1.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak4_1.setBounds(new java.awt.Rectangle(233,20,421,195));
bgPictureLabel.add(transparantVlak4_1);
transparantVlak5.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak5.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak5.setBounds(new java.awt.Rectangle(239,296,421,195));
bgPictureLabel.add(transparantVlak5);
transparantVlak5_1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak5_1.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak5_1.setBounds(new java.awt.Rectangle(239,296,421,195));
bgPictureLabel.add(transparantVlak5_1);
theMenuBar = new JMenuBar();
spelMenu = new JMenu();
nieuwspelItem = new JMenuItem();
exitItem = new JMenuItem();
setJMenuBar(theMenuBar);
spelMenu.setText("Spel");
theMenuBar.add(spelMenu);
nieuwspelItem.setText("Nieuw Spel");
spelMenu.add(nieuwspelItem);
nieuwspelItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
nieuwspelItemActionPerformed(evt);
}
});
exitItem.setText("Afsluiten");
spelMenu.add(exitItem);
exitItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
postInitGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
/** Add your pre-init code in here */
public void preInitGUI(){
}
/** Add your post-init code in here */
public void postInitGUI(){
}
public static void main(String[] args){
showGUI();
}
/**
* This static method creates a new instance of this class and shows
* it inside a new JFrame, (unless it is already a JFrame).
*
* It is a convenience method for showing the GUI, but it can be
* copied and used as a basis for your own code. *
* It is auto-generated code - the body of this method will be
* re-generated after any changes are made to the GUI.
* However, if you delete this method it will not be re-created. */
public static void showGUI(){
try {
MainFrame inst = new MainFrame();
inst.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This is an auto-generated method which you can alter,
* e.g. to point to a different property file, to modify the key by
* by prefixing the name of this class, etc.
*
* By default, it expects a file called "messages.properties" to exist in the
* current package, and returns the value of the property defined
* in that file for the given key
*/
public String getExternalizedString(String key){
try {
return java.util.ResourceBundle.getBundle("game31/userInterface.MainFrameMessages").getString(key);
} catch (java.util.MissingResourceException e) {
return '!' + key + '!';
}
}
/** Auto-generated event handler method */
protected void exitItemActionPerformed(ActionEvent evt){
int sure = JOptionPane.showConfirmDialog(this, "Weet u zeker dat u wilt stoppen?", "Afsluiten?", JOptionPane.OK_CANCEL_OPTION);
if(sure == 0) {
System.exit(0);
}
}
/** Auto-generated event handler method */
protected void nieuwspelItemActionPerformed(ActionEvent evt){
new MainFrame(1);
this.dispose();
}
}
| HUSACCT/Maven-plugin | src/test/resources/game31-invallidarchitecture/Game31_Source_ArchRefactAss/src/main/java/game31/userinterface/MainFrame.java | 3,084 | //Geef TheMainpanel het spel. | line_comment | nl | package main.java.game31.userinterface;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import main.java.game31.domain.gamecontrol.Spel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* This code was generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a
* for-profit company or business) then you should purchase
* a license - please visit www.cloudgarden.com for details.
*/
public class MainFrame extends javax.swing.JFrame {
private JMenuItem exitItem;
private JMenuItem nieuwspelItem;
private TheMainPanel theMainPanel;
private JLabel transparantVlak5_1;
private JLabel transparantVlak5;
private JLabel transparantVlak4_1;
private JLabel transparantVlak4;
private JLabel transparantVlak3;
private JLabel transparantVlak2;
private JLabel transparantVlak1;
private JMenu spelMenu;
private JMenuBar theMenuBar;
private JLabel bgPictureLabel;
private boolean gameStarted = false;
private int aantalFices;
public MainFrame(int i) {
initGUI();
this.setVisible(true);
SetupFrame sf = new SetupFrame(this);
}
public MainFrame() {
initGUI();
this.setVisible(true);
SetupFrame sf = new SetupFrame(this);
}
public void updateUI() {
theMainPanel.updateScherm();
}
public void newRound() {
theMainPanel.eersteBeurt();
}
public void nieuwSpel() {
SetupFrame sf = new SetupFrame(this);
}
public void loadSpelerSetup(int aantalSpelers, int aantalFices, boolean opEzeltje, boolean metStok) {
setupSpelers ss = new setupSpelers(aantalSpelers, this);
this.aantalFices = aantalFices;
}
public void startHetSpel(Vector computerSpelers, Vector menselijkeSpelers) {
Spel hetSpel = new Spel(computerSpelers, menselijkeSpelers, aantalFices, this);
theMainPanel.startSpel(hetSpel);
//Geef TheMainpanel<SUF>
}
/**
* Initializes the GUI.
* Auto-generated code - any changes you make will disappear.
*/
public void initGUI(){
try {
preInitGUI();
theMainPanel = new TheMainPanel();
bgPictureLabel = new JLabel();
transparantVlak1 = new JLabel();
transparantVlak2 = new JLabel();
transparantVlak3 = new JLabel();
transparantVlak4 = new JLabel();
transparantVlak4_1 = new JLabel();
transparantVlak5 = new JLabel();
transparantVlak5_1 = new JLabel();
this.getContentPane().setLayout(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(true);
this.setTitle("31-en The Game");
this.setSize(new java.awt.Dimension(707,577));
theMainPanel.setVisible(true);
theMainPanel.setPreferredSize(new java.awt.Dimension(700,527));
theMainPanel.setBounds(new java.awt.Rectangle(0,0,700,527));
this.getContentPane().add(theMainPanel);
bgPictureLabel.setHorizontalAlignment(SwingConstants.LEFT);
bgPictureLabel.setHorizontalTextPosition(SwingConstants.LEFT);
bgPictureLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/mainFrameBackground.jpg")));
bgPictureLabel.setIconTextGap(0);
bgPictureLabel.setVerticalAlignment(SwingConstants.TOP);
bgPictureLabel.setVerticalTextPosition(SwingConstants.TOP);
bgPictureLabel.setVisible(true);
bgPictureLabel.setPreferredSize(new java.awt.Dimension(700,529));
bgPictureLabel.setOpaque(true);
bgPictureLabel.setRequestFocusEnabled(false);
bgPictureLabel.setVerifyInputWhenFocusTarget(true);
bgPictureLabel.setBounds(new java.awt.Rectangle(0,0,700,529));
bgPictureLabel.setFocusTraversalKeysEnabled(false);
bgPictureLabel.setFocusable(false);
bgPictureLabel.setIgnoreRepaint(true);
this.getContentPane().add(bgPictureLabel);
transparantVlak1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak1.setPreferredSize(new java.awt.Dimension(197,229));
transparantVlak1.setBounds(new java.awt.Rectangle(0,0,197,229));
bgPictureLabel.add(transparantVlak1);
transparantVlak2.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak2.setPreferredSize(new java.awt.Dimension(197,299));
transparantVlak2.setBounds(new java.awt.Rectangle(0,229,197,299));
bgPictureLabel.add(transparantVlak2);
transparantVlak3.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak3.setPreferredSize(new java.awt.Dimension(464,32));
transparantVlak3.setBounds(new java.awt.Rectangle(216,231,464,32));
bgPictureLabel.add(transparantVlak3);
transparantVlak4.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak4.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak4.setBounds(new java.awt.Rectangle(233,20,421,195));
bgPictureLabel.add(transparantVlak4);
transparantVlak4_1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak4_1.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak4_1.setBounds(new java.awt.Rectangle(233,20,421,195));
bgPictureLabel.add(transparantVlak4_1);
transparantVlak5.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak5.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak5.setBounds(new java.awt.Rectangle(239,296,421,195));
bgPictureLabel.add(transparantVlak5);
transparantVlak5_1.setIcon(new ImageIcon(getClass().getClassLoader().getResource("main/resources/images/transparant.png")));
transparantVlak5_1.setPreferredSize(new java.awt.Dimension(421,195));
transparantVlak5_1.setBounds(new java.awt.Rectangle(239,296,421,195));
bgPictureLabel.add(transparantVlak5_1);
theMenuBar = new JMenuBar();
spelMenu = new JMenu();
nieuwspelItem = new JMenuItem();
exitItem = new JMenuItem();
setJMenuBar(theMenuBar);
spelMenu.setText("Spel");
theMenuBar.add(spelMenu);
nieuwspelItem.setText("Nieuw Spel");
spelMenu.add(nieuwspelItem);
nieuwspelItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
nieuwspelItemActionPerformed(evt);
}
});
exitItem.setText("Afsluiten");
spelMenu.add(exitItem);
exitItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
postInitGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
/** Add your pre-init code in here */
public void preInitGUI(){
}
/** Add your post-init code in here */
public void postInitGUI(){
}
public static void main(String[] args){
showGUI();
}
/**
* This static method creates a new instance of this class and shows
* it inside a new JFrame, (unless it is already a JFrame).
*
* It is a convenience method for showing the GUI, but it can be
* copied and used as a basis for your own code. *
* It is auto-generated code - the body of this method will be
* re-generated after any changes are made to the GUI.
* However, if you delete this method it will not be re-created. */
public static void showGUI(){
try {
MainFrame inst = new MainFrame();
inst.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This is an auto-generated method which you can alter,
* e.g. to point to a different property file, to modify the key by
* by prefixing the name of this class, etc.
*
* By default, it expects a file called "messages.properties" to exist in the
* current package, and returns the value of the property defined
* in that file for the given key
*/
public String getExternalizedString(String key){
try {
return java.util.ResourceBundle.getBundle("game31/userInterface.MainFrameMessages").getString(key);
} catch (java.util.MissingResourceException e) {
return '!' + key + '!';
}
}
/** Auto-generated event handler method */
protected void exitItemActionPerformed(ActionEvent evt){
int sure = JOptionPane.showConfirmDialog(this, "Weet u zeker dat u wilt stoppen?", "Afsluiten?", JOptionPane.OK_CANCEL_OPTION);
if(sure == 0) {
System.exit(0);
}
}
/** Auto-generated event handler method */
protected void nieuwspelItemActionPerformed(ActionEvent evt){
new MainFrame(1);
this.dispose();
}
}
|
33864_2 | package main.java.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_Ant | src/main/java/game31/domein/ComputerSpeler.java | 2,864 | //kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
| line_comment | nl | package main.java.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,<SUF>
//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');
}
}
}
|
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');
}
}
}
|
102384_18 | package rstar;
/* Modified by Josephine Wong 23 Nov 1997
Improve User Interface of the program
*/
public class Constants
{
public static final boolean recordLeavesOnly = false;
/* These values are now set by the users - see UserInterface module.*/
// for experimental rects
public static final int MAXCOORD = 100;
public static final int MAXWIDTH = 60;
public static final int NUMRECTS = 200;
public static final int DIMENSION = 2;
public static final int BLOCKLENGTH = 1024;
public static final int CACHESIZE = 128;
// for queries
static final int RANGEQUERY = 0;
static final int POINTQUERY = 1;
static final int CIRCLEQUERY = 2;
static final int RINGQUERY = 3;
static final int CONSTQUERY = 4;
// for buffering
static final int SIZEOF_BOOLEAN = 1;
static final int SIZEOF_SHORT = 2;
static final int SIZEOF_CHAR = 1;
static final int SIZEOF_BYTE = 1;
static final int SIZEOF_FLOAT = 4;
static final int SIZEOF_INT = 4;
public final static int RTDataNode__dimension = 2;
public final static float MAXREAL = (float)9.99e20;
public final static int MAX_DIMENSION = 256;
// for comparisons
public final static float min(float a, float b) {return (a < b)? a : b;}
public final static int min(int a, int b) {return (a < b)? a : b;}
public final static float max(float a, float b) {return (a > b)? a : b;}
public final static int max(int a, int b) {return (a > b)? a : b;}
// for comparing mbrs
public final static int OVERLAP=0;
public final static int INSIDE=1;
public final static int S_NONE=2;
// for the insert algorithm
public final static int SPLIT=0;
public final static int REINSERT=1;
public final static int NONE=2;
// for header blocks
public final static int BFHEAD_LENGTH = SIZEOF_INT*2;
// sorting criteria
public final static int SORT_LOWER_MBR = 0; //for mbrs
public final static int SORT_UPPER_MBR = 1; //for mbrs
public final static int SORT_CENTER_MBR = 2; //for mbrs
public final static int SORT_MINDIST = 3; //for branchlists
public final static int BLK_SIZE=4096;
public final static int MAXLONGINT=32768;
public final static int NUM_TRIES=10;
// for errors
public static void error (String msg, boolean fatal)
{
System.out.println(msg);
if (fatal) System.exit(1);
}
// returns the d-dimension area of the mbr
public static float area(int dimension, float mbr[])
{
int i;
float sum;
sum = (float)1.0;
for (i = 0; i < dimension; i++)
sum *= mbr[2*i+1] - mbr[2*i];
return sum;
}
// returns the margin of the mbr. That is the sum of all projections
// to the axes
public static float margin(int dimension, float mbr[])
{
int i;
int ml, mu, m_last;
float sum;
sum = (float)0.0;
m_last = 2*dimension;
ml = 0;
mu = ml + 1;
while (mu < m_last)
{
sum += mbr[mu] - mbr[ml];
ml += 2;
mu += 2;
}
return sum;
}
// ist ein Skalar in einem Intervall ?
public static boolean inside(float p, float lb, float ub)
{
return (p >= lb && p <= ub);
}
// ist ein Vektor in einer Box ?
public static boolean inside(float v[], float mbr[], int dimension)
{
int i;
for (i = 0; i < dimension; i++)
if (!inside(v[i], mbr[2*i], mbr[2*i+1]))
return false;
return true;
}
// calcutales the overlapping area of r1 and r2
// calculate overlap in every dimension and multiplicate the values
public static float overlap(int dimension, float r1[], float r2[])
{
float sum;
int r1pos, r2pos, r1last;
float r1_lb, r1_ub, r2_lb, r2_ub;
sum = (float)1.0;
r1pos = 0; r2pos = 0;
r1last = 2 * dimension;
while (r1pos < r1last)
{
r1_lb = r1[r1pos++];
r1_ub = r1[r1pos++];
r2_lb = r2[r2pos++];
r2_ub = r2[r2pos++];
// calculate overlap in this dimension
if (inside(r1_ub, r2_lb, r2_ub))
// upper bound of r1 is inside r2
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r1_ub - r1_lb);
else
sum *= (r1_ub - r2_lb);
}
else
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r2_ub - r1_lb);
else
{
if (inside(r2_lb, r1_lb, r1_ub) && inside(r2_ub, r1_lb, r1_ub))
// r1 contains r2
sum *= (r2_ub - r2_lb);
else
// r1 and r2 do not overlap
sum = (float)0.0;
}
}
}
return sum;
}
// enlarge r in a way that it contains s
public static void enlarge(int dimension, float mbr[], float r1[], float r2[])
{
int i;
//mbr = new float[2*dimension];
for (i = 0; i < 2*dimension; i += 2)
{
mbr[i] = min(r1[i], r2[i]);
mbr[i+1] = max(r1[i+1], r2[i+1]);
}
/*System.out.println("Enlarge was called with parameters:");
System.out.println("r1 = " + r1[0] + " " + r1[1] + " " + r1[2] + " " + r1[3]);
System.out.println("r2 = " + r2[0] + " " + r2[1] + " " + r2[2] + " " + r2[3]);
System.out.println("r1 = " + mbr[0] + " " + mbr[1] + " " + mbr[2] + " " + mbr[3]);
*/
//#ifdef CHECK_MBR
// check_mbr(dimension,*mbr);
//#endif
}
/**
* returns true if the two mbrs intersect
*/
public static boolean section(int dimension, float mbr1[], float mbr2[])
{
int i;
for (i = 0; i < dimension; i++)
{
if (mbr1[2*i] > mbr2[2*i + 1] || mbr1[2*i + 1] < mbr2[2*i])
return false;
}
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_c(int dimension, float mbr1[], Object center, float radius)
{
float r2;
r2 = radius * radius;
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if ((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)
return false;
else
return true;
}
//new function
public static boolean section_c_2(int dimension, float mbr1[], Object center, float radius)
{
if (radius < MINDIST(center,mbr1))
return false;
else
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_ring(int dimension, float mbr1[], Object center, float radius1, float radius2)
{
float r_c1; //inner circle radius
float r_c2; //outer circle radius
if (radius1 < radius2)
{
r_c1 = radius1 * radius1;
r_c2 = radius2 * radius2;
}
else
{
r_c1 = radius2 * radius2;
r_c2 = radius1 * radius1;
}
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if (((r_c1 - MAXDIST(center,mbr1)) < (float)1.0e-8) &&
((MINDIST(center,mbr1) - r_c2) < (float)1.0e-8))
return true;
else
return false;
}
/** This is a generic version of C.A.R Hoare's Quick Sort
* algorithm. This will handle arrays that are already
* sorted, and arrays with duplicate keys.
*
* If you think of a one dimensional array as going from
* the lowest index on the left to the highest index on the right
* then the parameters to this function are lowest index or
* left and highest index or right. The first time you call
* this function it will be with the parameters 0, a.length - 1.
*
* @param a a Sortable array
* @param lo0 left boundary of array partition
* @param hi0 right boundary of array partition
*/
public static void quickSort(Sortable a[], int lo0, int hi0, int sortCriterion)
{
int lo = lo0;
int hi = hi0;
Sortable mid;
if (hi0 > lo0)
{
/* Arbitrarily establishing partition element as the midpoint of
* the array.
*/
mid = a[ ( lo0 + hi0 ) / 2 ];
// loop through the array until indices cross
while( lo <= hi )
{
/* find the first element that is greater than or equal to
* the partition element starting from the left Index.
*/
while( ( lo < hi0 ) && ( a[lo].lessThan(mid, sortCriterion) ))
++lo;
/* find an element that is smaller than or equal to
* the partition element starting from the right Index.
*/
while( ( hi > lo0 ) && ( a[hi].greaterThan(mid, sortCriterion)))
--hi;
// if the indexes have not crossed, swap
if( lo <= hi )
{
swap(a, lo, hi);
++lo;
--hi;
}
}
/* If the right index has not reached the left side of array
* must now sort the left partition.
*/
if( lo0 < hi )
quickSort( a, lo0, hi, sortCriterion );
/* If the left index has not reached the right side of array
* must now sort the right partition.
*/
if( lo < hi0 )
quickSort( a, lo, hi0, sortCriterion );
}
}
//Swaps two entries in an array of objects to be sorted.
//See Constants.quickSort()
public static void swap(Sortable a[], int i, int j)
{
Sortable T;
T = a[i];
a[i] = a[j];
a[j] = T;
}
/**
* computes the square of the Euclidean distance between 2 points
*/
public static float objectDIST(PPoint point1, PPoint point2)
{
//
// Berechnet das Quadrat der euklid'schen Metrik.
// (Der tatsaechliche Abstand ist uninteressant, weil
// die anderen Metriken (MINDIST und MINMAXDIST fuer
// die NearestNarborQuery nur relativ nie absolut
// gebraucht werden; nur Aussagen "<" oder ">" sind
// relevant.
//
float sum = (float)0;
int i;
for( i = 0; i < point1.dimension; i++)
sum += java.lang.Math.pow(point1.data[i] - point2.data[i], 2);
//return( sqrt(sum) );
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINDIST between 1 pt and 1 MBR (see [Rous95])
* the MINDIST ensures that the nearest neighbor from this pt to a
* rect in this MBR is at at least this distance
*/
public static float MINDIST(Object pt, float bounces[])
{
//
// Berechne die kuerzeste Entfernung zwischen einem Punkt Point
// und einem MBR bounces (Lotrecht!)
//
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float r;
int i;
for(i = 0; i < point.dimension; i++)
{
if (point.data[i] < bounces[2*i])
r = bounces[2*i];
else
{
if (point.data[i] > bounces[2*i+1])
r = bounces[2*i+1];
else
r = point.data[i];
}
sum += java.lang.Math.pow(point.data[i] - r , 2);
}
//return(sum);
return((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MAXDIST between 1 pt and 1 MBR. It is defined as the
* maximum distance of a MBR vertex against the specified point
* Used as an upper bound of the furthest rectangle inside an MBR from a specific
* point
*/
public static float MAXDIST(Object pt, float bounces[])
{
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float maxdiff;
int i;
for(i = 0; i < point.dimension; i++)
{
maxdiff = max(java.lang.Math.abs(point.data[i] - bounces[2*i]),
java.lang.Math.abs(point.data[i] - bounces[2*i+1]));
sum += java.lang.Math.pow(maxdiff, 2);
}
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINMAXDIST between 1 pt and 1 MBR (see [Rous95])
* the MINMAXDIST ensures that there is at least 1 object in the MBR
* that is at most MINMAXDIST far away of the point
*/
public static float MINMAXDIST(PPoint point, float bounces[])
{
// Berechne den kleinsten maximalen Abstand von einem Punkt Point
// zu einem MBR bounces.
// Wird benutzt zur Abschaetzung von Abstaenden bei NearestNarborQuery.
// Kann als Supremum fuer die aktuell kuerzeste Distanz:
// Alle Punkte mit einem Abstand > MINMAXDIST sind keine Kandidaten mehr
// fuer den NearestNarbor
// vgl. Literatur:
// Nearest Narbor Query v. Roussopoulos, Kelley und Vincent,
// University of Maryland
float sum = 0;
float minimum = (float)1.0e20;
float S = 0;
float rmk, rMi;
int k,i,j;
for( i = 0; i < point.dimension; i++)
{
rMi = (point.data[i] >= (bounces[2*i]+bounces[2*i+1])/2)
? bounces[2*i] : bounces[2*i+1];
S += java.lang.Math.pow( point.data[i] - rMi , 2 );
}
for( k = 0; k < point.dimension; k++)
{
rmk = ( point.data[k] <= (bounces[2*k]+bounces[2*k+1]) / 2 ) ?
bounces[2*k] : bounces[2*k+1];
sum = (float)java.lang.Math.pow(point.data[k] - rmk , 2 );
rMi = (point.data[k] >= (bounces[2*k]+bounces[2*k+1]) / 2 )
? bounces[2*k] : bounces[2*k+1];
sum += S - java.lang.Math.pow(point.data[k] - rMi , 2);
minimum = min(minimum,sum);
}
return(minimum);
//return ((float)java.lang.Math.sqrt(minimum));
}
/*
public static int sortmindist(Object element1, Object element2)
{
//
// Vergleichsfunktion fuer die Sortierung der BranchList bei der
// NearestNarborQuery (Sort, Branch and Prune)
//
BranchList e1,e2;
e1 = (BranchList ) element1;
e2 = (BranchList ) element2;
if (e1.mindist < e2.mindist)
return(-1);
else if (e1.mindist > e2.mindist)
return(1);
else
return(0);
}*/
public static int pruneBranchList(float nearest_distanz/*[]*/, Object activebranchList[], int n)
{
// Schneidet im Array BranchList alle Eintraege ab, deren Distanz groesser
// ist als die aktuell naeheste Distanz
//
BranchList bl[];
int i,j,k, aktlast;
bl = (BranchList[]) activebranchList;
// 1. Strategie:
//
// Ist MINDIST(P,M1) > MINMAXDIST(P,M2), so kann der
// NearestNeighbor auf keinen Fall mehr in M1 liegen!
//
aktlast = n;
for( i = 0; i < aktlast ; i++ )
{
if (bl[i].minmaxdist < bl[aktlast-1].mindist)
for(j = 0; (j < aktlast) ; j++ )
if ((i!=j) && (bl[j].mindist>bl[i].minmaxdist))
{
aktlast = j;
break;
}
}
// 2. Strategie:
//
// nearest_distanz > MINMAXDIST(P,M)
// -> nearest_distanz = MIMMAXDIST(P,M)
//
for( i = 0; i < aktlast; i++)
if (nearest_distanz/*[0]*/ > bl[i].minmaxdist)
nearest_distanz/*[0]*/ = bl[i].minmaxdist;
// 3. Strategie:
//
// nearest_distanz < MINDIST(P,M)
//
// in M kann der Nearest-Narbor sicher nicht mehr liegen.
//
for( i = 0; (i < aktlast) && (nearest_distanz/*[0]*/ >= bl[i].mindist) ; i++);
aktlast = i;
// printf("n: %d aktlast: %d \n",n,aktlast);
return (aktlast);
}
public static int testBranchList(Object abL[], Object sL[], int n, int last)
{
// Schneidet im Array BranchList alle Eintr"age ab, deren Distanz gr"o"ser
// ist als die aktuell naeheste Distanz
//
BranchList activebranchList[], sectionList[];
int i,number, aktlast;
activebranchList = (BranchList[]) abL;
sectionList = (BranchList[]) sL;
aktlast = last;
for(i = last; i < n ; i++)
{
number = activebranchList[i].entry_number;
if (sectionList[number].section)
{
// obwohl vom Abstand her dieser Eintrag gecanceld werden
// m"usste, wird hier der Eintrag in die ABL wieder
// aufgenommen, da evtl. ein Treffer der range-Query zu erwarten ist!
//
// An der letzten Stelle der Liste kommt der aktuelle Eintrag!
aktlast++;
activebranchList[aktlast].entry_number = activebranchList[i].entry_number;
activebranchList[aktlast].mindist = activebranchList[i].mindist;
activebranchList[aktlast].minmaxdist = activebranchList[i].minmaxdist; }
}
return (aktlast);
}
public static void check_mbr(int dimension, float mbr[])
{
}
public static rectangle toRectangle (float rect[])
{
rectangle r = new rectangle(0);
r.LX = (int) rect[0];
r.UX = (int) rect[1];
r.LY = (int) rect[2];
r.UY = (int) rect[3];
return r;
}
} | Haibo-Wang-ORG/Most-Popular-Route | src/rstar/Constants.java | 6,479 | // r1 and r2 do not overlap
| line_comment | nl | package rstar;
/* Modified by Josephine Wong 23 Nov 1997
Improve User Interface of the program
*/
public class Constants
{
public static final boolean recordLeavesOnly = false;
/* These values are now set by the users - see UserInterface module.*/
// for experimental rects
public static final int MAXCOORD = 100;
public static final int MAXWIDTH = 60;
public static final int NUMRECTS = 200;
public static final int DIMENSION = 2;
public static final int BLOCKLENGTH = 1024;
public static final int CACHESIZE = 128;
// for queries
static final int RANGEQUERY = 0;
static final int POINTQUERY = 1;
static final int CIRCLEQUERY = 2;
static final int RINGQUERY = 3;
static final int CONSTQUERY = 4;
// for buffering
static final int SIZEOF_BOOLEAN = 1;
static final int SIZEOF_SHORT = 2;
static final int SIZEOF_CHAR = 1;
static final int SIZEOF_BYTE = 1;
static final int SIZEOF_FLOAT = 4;
static final int SIZEOF_INT = 4;
public final static int RTDataNode__dimension = 2;
public final static float MAXREAL = (float)9.99e20;
public final static int MAX_DIMENSION = 256;
// for comparisons
public final static float min(float a, float b) {return (a < b)? a : b;}
public final static int min(int a, int b) {return (a < b)? a : b;}
public final static float max(float a, float b) {return (a > b)? a : b;}
public final static int max(int a, int b) {return (a > b)? a : b;}
// for comparing mbrs
public final static int OVERLAP=0;
public final static int INSIDE=1;
public final static int S_NONE=2;
// for the insert algorithm
public final static int SPLIT=0;
public final static int REINSERT=1;
public final static int NONE=2;
// for header blocks
public final static int BFHEAD_LENGTH = SIZEOF_INT*2;
// sorting criteria
public final static int SORT_LOWER_MBR = 0; //for mbrs
public final static int SORT_UPPER_MBR = 1; //for mbrs
public final static int SORT_CENTER_MBR = 2; //for mbrs
public final static int SORT_MINDIST = 3; //for branchlists
public final static int BLK_SIZE=4096;
public final static int MAXLONGINT=32768;
public final static int NUM_TRIES=10;
// for errors
public static void error (String msg, boolean fatal)
{
System.out.println(msg);
if (fatal) System.exit(1);
}
// returns the d-dimension area of the mbr
public static float area(int dimension, float mbr[])
{
int i;
float sum;
sum = (float)1.0;
for (i = 0; i < dimension; i++)
sum *= mbr[2*i+1] - mbr[2*i];
return sum;
}
// returns the margin of the mbr. That is the sum of all projections
// to the axes
public static float margin(int dimension, float mbr[])
{
int i;
int ml, mu, m_last;
float sum;
sum = (float)0.0;
m_last = 2*dimension;
ml = 0;
mu = ml + 1;
while (mu < m_last)
{
sum += mbr[mu] - mbr[ml];
ml += 2;
mu += 2;
}
return sum;
}
// ist ein Skalar in einem Intervall ?
public static boolean inside(float p, float lb, float ub)
{
return (p >= lb && p <= ub);
}
// ist ein Vektor in einer Box ?
public static boolean inside(float v[], float mbr[], int dimension)
{
int i;
for (i = 0; i < dimension; i++)
if (!inside(v[i], mbr[2*i], mbr[2*i+1]))
return false;
return true;
}
// calcutales the overlapping area of r1 and r2
// calculate overlap in every dimension and multiplicate the values
public static float overlap(int dimension, float r1[], float r2[])
{
float sum;
int r1pos, r2pos, r1last;
float r1_lb, r1_ub, r2_lb, r2_ub;
sum = (float)1.0;
r1pos = 0; r2pos = 0;
r1last = 2 * dimension;
while (r1pos < r1last)
{
r1_lb = r1[r1pos++];
r1_ub = r1[r1pos++];
r2_lb = r2[r2pos++];
r2_ub = r2[r2pos++];
// calculate overlap in this dimension
if (inside(r1_ub, r2_lb, r2_ub))
// upper bound of r1 is inside r2
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r1_ub - r1_lb);
else
sum *= (r1_ub - r2_lb);
}
else
{
if (inside(r1_lb, r2_lb, r2_ub))
// and lower bound of r1 is inside
sum *= (r2_ub - r1_lb);
else
{
if (inside(r2_lb, r1_lb, r1_ub) && inside(r2_ub, r1_lb, r1_ub))
// r1 contains r2
sum *= (r2_ub - r2_lb);
else
// r1 and<SUF>
sum = (float)0.0;
}
}
}
return sum;
}
// enlarge r in a way that it contains s
public static void enlarge(int dimension, float mbr[], float r1[], float r2[])
{
int i;
//mbr = new float[2*dimension];
for (i = 0; i < 2*dimension; i += 2)
{
mbr[i] = min(r1[i], r2[i]);
mbr[i+1] = max(r1[i+1], r2[i+1]);
}
/*System.out.println("Enlarge was called with parameters:");
System.out.println("r1 = " + r1[0] + " " + r1[1] + " " + r1[2] + " " + r1[3]);
System.out.println("r2 = " + r2[0] + " " + r2[1] + " " + r2[2] + " " + r2[3]);
System.out.println("r1 = " + mbr[0] + " " + mbr[1] + " " + mbr[2] + " " + mbr[3]);
*/
//#ifdef CHECK_MBR
// check_mbr(dimension,*mbr);
//#endif
}
/**
* returns true if the two mbrs intersect
*/
public static boolean section(int dimension, float mbr1[], float mbr2[])
{
int i;
for (i = 0; i < dimension; i++)
{
if (mbr1[2*i] > mbr2[2*i + 1] || mbr1[2*i + 1] < mbr2[2*i])
return false;
}
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_c(int dimension, float mbr1[], Object center, float radius)
{
float r2;
r2 = radius * radius;
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if ((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)
return false;
else
return true;
}
//new function
public static boolean section_c_2(int dimension, float mbr1[], Object center, float radius)
{
if (radius < MINDIST(center,mbr1))
return false;
else
return true;
}
/**
* returns true if the specified mbr intersects the specified circle
*/
public static boolean section_ring(int dimension, float mbr1[], Object center, float radius1, float radius2)
{
float r_c1; //inner circle radius
float r_c2; //outer circle radius
if (radius1 < radius2)
{
r_c1 = radius1 * radius1;
r_c2 = radius2 * radius2;
}
else
{
r_c1 = radius2 * radius2;
r_c2 = radius1 * radius1;
}
// if MBR contains circle center (MINDIST) return true
// if r2>MINDIST return true
//if ((MINDIST(center,mbr1) != 0) ||
// (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8)))
if (((r_c1 - MAXDIST(center,mbr1)) < (float)1.0e-8) &&
((MINDIST(center,mbr1) - r_c2) < (float)1.0e-8))
return true;
else
return false;
}
/** This is a generic version of C.A.R Hoare's Quick Sort
* algorithm. This will handle arrays that are already
* sorted, and arrays with duplicate keys.
*
* If you think of a one dimensional array as going from
* the lowest index on the left to the highest index on the right
* then the parameters to this function are lowest index or
* left and highest index or right. The first time you call
* this function it will be with the parameters 0, a.length - 1.
*
* @param a a Sortable array
* @param lo0 left boundary of array partition
* @param hi0 right boundary of array partition
*/
public static void quickSort(Sortable a[], int lo0, int hi0, int sortCriterion)
{
int lo = lo0;
int hi = hi0;
Sortable mid;
if (hi0 > lo0)
{
/* Arbitrarily establishing partition element as the midpoint of
* the array.
*/
mid = a[ ( lo0 + hi0 ) / 2 ];
// loop through the array until indices cross
while( lo <= hi )
{
/* find the first element that is greater than or equal to
* the partition element starting from the left Index.
*/
while( ( lo < hi0 ) && ( a[lo].lessThan(mid, sortCriterion) ))
++lo;
/* find an element that is smaller than or equal to
* the partition element starting from the right Index.
*/
while( ( hi > lo0 ) && ( a[hi].greaterThan(mid, sortCriterion)))
--hi;
// if the indexes have not crossed, swap
if( lo <= hi )
{
swap(a, lo, hi);
++lo;
--hi;
}
}
/* If the right index has not reached the left side of array
* must now sort the left partition.
*/
if( lo0 < hi )
quickSort( a, lo0, hi, sortCriterion );
/* If the left index has not reached the right side of array
* must now sort the right partition.
*/
if( lo < hi0 )
quickSort( a, lo, hi0, sortCriterion );
}
}
//Swaps two entries in an array of objects to be sorted.
//See Constants.quickSort()
public static void swap(Sortable a[], int i, int j)
{
Sortable T;
T = a[i];
a[i] = a[j];
a[j] = T;
}
/**
* computes the square of the Euclidean distance between 2 points
*/
public static float objectDIST(PPoint point1, PPoint point2)
{
//
// Berechnet das Quadrat der euklid'schen Metrik.
// (Der tatsaechliche Abstand ist uninteressant, weil
// die anderen Metriken (MINDIST und MINMAXDIST fuer
// die NearestNarborQuery nur relativ nie absolut
// gebraucht werden; nur Aussagen "<" oder ">" sind
// relevant.
//
float sum = (float)0;
int i;
for( i = 0; i < point1.dimension; i++)
sum += java.lang.Math.pow(point1.data[i] - point2.data[i], 2);
//return( sqrt(sum) );
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINDIST between 1 pt and 1 MBR (see [Rous95])
* the MINDIST ensures that the nearest neighbor from this pt to a
* rect in this MBR is at at least this distance
*/
public static float MINDIST(Object pt, float bounces[])
{
//
// Berechne die kuerzeste Entfernung zwischen einem Punkt Point
// und einem MBR bounces (Lotrecht!)
//
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float r;
int i;
for(i = 0; i < point.dimension; i++)
{
if (point.data[i] < bounces[2*i])
r = bounces[2*i];
else
{
if (point.data[i] > bounces[2*i+1])
r = bounces[2*i+1];
else
r = point.data[i];
}
sum += java.lang.Math.pow(point.data[i] - r , 2);
}
//return(sum);
return((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MAXDIST between 1 pt and 1 MBR. It is defined as the
* maximum distance of a MBR vertex against the specified point
* Used as an upper bound of the furthest rectangle inside an MBR from a specific
* point
*/
public static float MAXDIST(Object pt, float bounces[])
{
PPoint point = (PPoint)pt;
float sum = (float)0.0;
float maxdiff;
int i;
for(i = 0; i < point.dimension; i++)
{
maxdiff = max(java.lang.Math.abs(point.data[i] - bounces[2*i]),
java.lang.Math.abs(point.data[i] - bounces[2*i+1]));
sum += java.lang.Math.pow(maxdiff, 2);
}
//return(sum);
return ((float)java.lang.Math.sqrt(sum));
}
/**
* computes the MINMAXDIST between 1 pt and 1 MBR (see [Rous95])
* the MINMAXDIST ensures that there is at least 1 object in the MBR
* that is at most MINMAXDIST far away of the point
*/
public static float MINMAXDIST(PPoint point, float bounces[])
{
// Berechne den kleinsten maximalen Abstand von einem Punkt Point
// zu einem MBR bounces.
// Wird benutzt zur Abschaetzung von Abstaenden bei NearestNarborQuery.
// Kann als Supremum fuer die aktuell kuerzeste Distanz:
// Alle Punkte mit einem Abstand > MINMAXDIST sind keine Kandidaten mehr
// fuer den NearestNarbor
// vgl. Literatur:
// Nearest Narbor Query v. Roussopoulos, Kelley und Vincent,
// University of Maryland
float sum = 0;
float minimum = (float)1.0e20;
float S = 0;
float rmk, rMi;
int k,i,j;
for( i = 0; i < point.dimension; i++)
{
rMi = (point.data[i] >= (bounces[2*i]+bounces[2*i+1])/2)
? bounces[2*i] : bounces[2*i+1];
S += java.lang.Math.pow( point.data[i] - rMi , 2 );
}
for( k = 0; k < point.dimension; k++)
{
rmk = ( point.data[k] <= (bounces[2*k]+bounces[2*k+1]) / 2 ) ?
bounces[2*k] : bounces[2*k+1];
sum = (float)java.lang.Math.pow(point.data[k] - rmk , 2 );
rMi = (point.data[k] >= (bounces[2*k]+bounces[2*k+1]) / 2 )
? bounces[2*k] : bounces[2*k+1];
sum += S - java.lang.Math.pow(point.data[k] - rMi , 2);
minimum = min(minimum,sum);
}
return(minimum);
//return ((float)java.lang.Math.sqrt(minimum));
}
/*
public static int sortmindist(Object element1, Object element2)
{
//
// Vergleichsfunktion fuer die Sortierung der BranchList bei der
// NearestNarborQuery (Sort, Branch and Prune)
//
BranchList e1,e2;
e1 = (BranchList ) element1;
e2 = (BranchList ) element2;
if (e1.mindist < e2.mindist)
return(-1);
else if (e1.mindist > e2.mindist)
return(1);
else
return(0);
}*/
public static int pruneBranchList(float nearest_distanz/*[]*/, Object activebranchList[], int n)
{
// Schneidet im Array BranchList alle Eintraege ab, deren Distanz groesser
// ist als die aktuell naeheste Distanz
//
BranchList bl[];
int i,j,k, aktlast;
bl = (BranchList[]) activebranchList;
// 1. Strategie:
//
// Ist MINDIST(P,M1) > MINMAXDIST(P,M2), so kann der
// NearestNeighbor auf keinen Fall mehr in M1 liegen!
//
aktlast = n;
for( i = 0; i < aktlast ; i++ )
{
if (bl[i].minmaxdist < bl[aktlast-1].mindist)
for(j = 0; (j < aktlast) ; j++ )
if ((i!=j) && (bl[j].mindist>bl[i].minmaxdist))
{
aktlast = j;
break;
}
}
// 2. Strategie:
//
// nearest_distanz > MINMAXDIST(P,M)
// -> nearest_distanz = MIMMAXDIST(P,M)
//
for( i = 0; i < aktlast; i++)
if (nearest_distanz/*[0]*/ > bl[i].minmaxdist)
nearest_distanz/*[0]*/ = bl[i].minmaxdist;
// 3. Strategie:
//
// nearest_distanz < MINDIST(P,M)
//
// in M kann der Nearest-Narbor sicher nicht mehr liegen.
//
for( i = 0; (i < aktlast) && (nearest_distanz/*[0]*/ >= bl[i].mindist) ; i++);
aktlast = i;
// printf("n: %d aktlast: %d \n",n,aktlast);
return (aktlast);
}
public static int testBranchList(Object abL[], Object sL[], int n, int last)
{
// Schneidet im Array BranchList alle Eintr"age ab, deren Distanz gr"o"ser
// ist als die aktuell naeheste Distanz
//
BranchList activebranchList[], sectionList[];
int i,number, aktlast;
activebranchList = (BranchList[]) abL;
sectionList = (BranchList[]) sL;
aktlast = last;
for(i = last; i < n ; i++)
{
number = activebranchList[i].entry_number;
if (sectionList[number].section)
{
// obwohl vom Abstand her dieser Eintrag gecanceld werden
// m"usste, wird hier der Eintrag in die ABL wieder
// aufgenommen, da evtl. ein Treffer der range-Query zu erwarten ist!
//
// An der letzten Stelle der Liste kommt der aktuelle Eintrag!
aktlast++;
activebranchList[aktlast].entry_number = activebranchList[i].entry_number;
activebranchList[aktlast].mindist = activebranchList[i].mindist;
activebranchList[aktlast].minmaxdist = activebranchList[i].minmaxdist; }
}
return (aktlast);
}
public static void check_mbr(int dimension, float mbr[])
{
}
public static rectangle toRectangle (float rect[])
{
rectangle r = new rectangle(0);
r.LX = (int) rect[0];
r.UX = (int) rect[1];
r.LY = (int) rect[2];
r.UY = (int) rect[3];
return r;
}
} |
197785_3 | package net.fe.overworldStage;
import org.newdawn.slick.opengl.Texture;
import chu.engine.anim.Renderer;
import chu.engine.anim.Transform;
import net.fe.FEResources;
import net.fe.fightStage.FightStage;
import net.fe.unit.Unit;
// TODO: Auto-generated Javadoc
/**
* The Class TradeMenu.
*/
public class TradeMenu extends InventoryMenu {
/** The mug. */
private Texture mug;
/** The flip. */
private boolean flip;
/**
* Instantiates a new trade menu.
*
* @param u the u
* @param x the x
* @param y the y
* @param flip the flip
*/
public TradeMenu(Unit u, float x, float y, boolean flip) {
super(u,x,y);
mug = FEResources.getTexture(u.name.toLowerCase()+"_mugshot");
this.flip = flip;
}
/* (non-Javadoc)
* @see net.fe.overworldStage.Menu#render()
*/
public void render(){
int imageW = mug.getImageWidth();
int imageH = mug.getImageHeight();
int menuW = this.getWidth();
Transform t = new Transform();
if(flip)
t.flipHorizontal();
Renderer.render(mug, 0, 0, 1, 1,
x+menuW/2-imageW/2, y-imageH, x+menuW/2+imageW/2, y, renderDepth, t);
super.render();
}
}
| HamaIndustries/FEMultiPlayer-V2 | src/net/fe/overworldStage/TradeMenu.java | 448 | /* (non-Javadoc)
* @see net.fe.overworldStage.Menu#render()
*/ | block_comment | nl | package net.fe.overworldStage;
import org.newdawn.slick.opengl.Texture;
import chu.engine.anim.Renderer;
import chu.engine.anim.Transform;
import net.fe.FEResources;
import net.fe.fightStage.FightStage;
import net.fe.unit.Unit;
// TODO: Auto-generated Javadoc
/**
* The Class TradeMenu.
*/
public class TradeMenu extends InventoryMenu {
/** The mug. */
private Texture mug;
/** The flip. */
private boolean flip;
/**
* Instantiates a new trade menu.
*
* @param u the u
* @param x the x
* @param y the y
* @param flip the flip
*/
public TradeMenu(Unit u, float x, float y, boolean flip) {
super(u,x,y);
mug = FEResources.getTexture(u.name.toLowerCase()+"_mugshot");
this.flip = flip;
}
/* (non-Javadoc)
<SUF>*/
public void render(){
int imageW = mug.getImageWidth();
int imageH = mug.getImageHeight();
int menuW = this.getWidth();
Transform t = new Transform();
if(flip)
t.flipHorizontal();
Renderer.render(mug, 0, 0, 1, 1,
x+menuW/2-imageW/2, y-imageH, x+menuW/2+imageW/2, y, renderDepth, t);
super.render();
}
}
|
172098_6 | package analyze.computation;
import java.util.HashMap;
import analyze.labeling.LabelFactory;
import model.SequentialData;
import model.Record;
import model.UnsupportedFormatException;
import model.datafield.DataField;
import model.datafield.DataFieldInt;
/**
* This class represents an object that will do computations on the data.
* @author Elvan
*
*/
public class Computer {
/**
* This variable stores the values of the columns that are evaluated.
*/
private HashMap<String, DataField> columnValues;
/**
* This variable stores the sequential data that needs to be computed.
*/
private SequentialData userData;
/**
* This variable stores the name of the column the computation is called on.
*/
private String column;
/**
* Construct a computation that consists of a string.
* @param columname name of the column to do the computation on
* @param data the data to perform the computation on
*/
public Computer(String columname, SequentialData data) {
column = columname;
userData = data;
columnValues = new HashMap<String, DataField>();
}
/**
* This method should evaluate a condition with a given record.
* @param data user data to evaluate with
* @param name column/label name to perform computation on
*/
public void gatherColumnValues(SequentialData data, String name) {
columnValues.clear();
// zal later vervangen kunnen worden door String patient ID
int id = 0;
for (Record record : data) {
if (record.containsKey(name)) {
columnValues.put(Integer.toString(id), record.get(name));
id = columnValues.size();
} else if (record.containsLabel(LabelFactory.getInstance().getNewLabel(name).getNumber())) {
columnValues.put(Integer.toString(id), new DataFieldInt(1));
id = columnValues.size();
}
}
}
/**
* This method performs the computation on the sequential data.
* @param computation the computation that needs to be done
* @return result of the computation
* @throws UnsupportedFormatException format is not supported
*/
public DataField compute(String computation)
throws UnsupportedFormatException {
gatherColumnValues(userData, column);
DataField result;
switch (computation) {
case "AVERAGE":
result = AVG.run(columnValues);
break;
case "COUNT":
result = COUNT.run(columnValues);
break;
case "SUM":
result = SUM.run(columnValues);
break;
case "MAX":
result = MAX.run(columnValues);
break;
case "MIN":
result = MIN.run(columnValues);
break;
case "DEVIATION":
result = DEVIATION.run(columnValues);
break;
case "VAR":
result = VARIANCE.run(columnValues);
break;
case "SQUARED":
result = SQUARED.run(columnValues);
break;
default:
result = COUNT.run(columnValues);
break;
}
return result;
}
}
| HansSchouten/context_health_informatics | src/main/java/analyze/computation/Computer.java | 852 | // zal later vervangen kunnen worden door String patient ID | line_comment | nl | package analyze.computation;
import java.util.HashMap;
import analyze.labeling.LabelFactory;
import model.SequentialData;
import model.Record;
import model.UnsupportedFormatException;
import model.datafield.DataField;
import model.datafield.DataFieldInt;
/**
* This class represents an object that will do computations on the data.
* @author Elvan
*
*/
public class Computer {
/**
* This variable stores the values of the columns that are evaluated.
*/
private HashMap<String, DataField> columnValues;
/**
* This variable stores the sequential data that needs to be computed.
*/
private SequentialData userData;
/**
* This variable stores the name of the column the computation is called on.
*/
private String column;
/**
* Construct a computation that consists of a string.
* @param columname name of the column to do the computation on
* @param data the data to perform the computation on
*/
public Computer(String columname, SequentialData data) {
column = columname;
userData = data;
columnValues = new HashMap<String, DataField>();
}
/**
* This method should evaluate a condition with a given record.
* @param data user data to evaluate with
* @param name column/label name to perform computation on
*/
public void gatherColumnValues(SequentialData data, String name) {
columnValues.clear();
// zal later<SUF>
int id = 0;
for (Record record : data) {
if (record.containsKey(name)) {
columnValues.put(Integer.toString(id), record.get(name));
id = columnValues.size();
} else if (record.containsLabel(LabelFactory.getInstance().getNewLabel(name).getNumber())) {
columnValues.put(Integer.toString(id), new DataFieldInt(1));
id = columnValues.size();
}
}
}
/**
* This method performs the computation on the sequential data.
* @param computation the computation that needs to be done
* @return result of the computation
* @throws UnsupportedFormatException format is not supported
*/
public DataField compute(String computation)
throws UnsupportedFormatException {
gatherColumnValues(userData, column);
DataField result;
switch (computation) {
case "AVERAGE":
result = AVG.run(columnValues);
break;
case "COUNT":
result = COUNT.run(columnValues);
break;
case "SUM":
result = SUM.run(columnValues);
break;
case "MAX":
result = MAX.run(columnValues);
break;
case "MIN":
result = MIN.run(columnValues);
break;
case "DEVIATION":
result = DEVIATION.run(columnValues);
break;
case "VAR":
result = VARIANCE.run(columnValues);
break;
case "SQUARED":
result = SQUARED.run(columnValues);
break;
default:
result = COUNT.run(columnValues);
break;
}
return result;
}
}
|
7850_29 | package nl.hanze.itann.ttt;
// deze import hebben we nodig voor gebruikersinput – let daar maar niet op.
import java.util.Scanner;
/*
EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS;
Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een
systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij
je de positie van stukken weergeeft als bijvoorbeeld 'H3'.
Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren'
uitgeprogrammeerd. Dit heeft een bord als volgt:
+------+------+------+
| (0,0 | (1,0 | (2,0 |
+------+------+------+
| (0,1 | (1,1 | (2,1 |
+------+------+------+
| (0,2 | (1,2 | (2,2 |
+------+------+------+
Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2
(drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan
het data-type een twee-dimensionale array van char's is:
private char[3][3] board
^ ^
| |
X ----------- --------Y
Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het
programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ
ik 2,1 (zonder haakjes).
Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk
gaat door een verkeerde input kun je vast wel bedenken waarom.
Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is.
*/
public class BoterKaasEieren {
public static void main(String[] args) {
new BoterKaasEieren();
}
// Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt.
private char[][] board;
// De huidige speler. Dit is ofwel een 'X' of een 'O'
private char currentPlayerMark;
//constructor
public BoterKaasEieren() {
board = new char[3][3];
currentPlayerMark = 'X';
initializeBoard();
playGame();
}
// Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is
// of er een winnaar is.
private void playGame() {
//De regels hieronder is om user-input op te vangen. Maak je daar niet druk om.
//Van belang is dat de input wordt opgeslagen in de variable 'input'.
Scanner reader = new Scanner(System.in);
String input = "";
//De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false'
//teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode
//wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven.
while (gameNotFinished()) {
//we printen elke keer de nieuwe status van het speelbord even uit
printBoard();
changePlayer();
// Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen.
System.out.println("De beurt in aan "+currentPlayerMark);
System.out.println("Geef positie op (x,y): ");
//Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd.
//Hierom kunnen we deze loop laten blijven lopen zonder dat er continu
//dingen op het scherm verschijnen.
input = reader.next();
//We maken een array van Strings van de input – check de API van de string:
// https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
String[] coords = input.split(",");
placeMark(coords);
}
// Even het winnende bord afdrukken
printBoard();
//als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om
//die even expliciet te sluiten.
reader.close();
}
private boolean placeMark(String[] coords) {
//We gaan er even van uit dat er in de input twee getallen zijn gegeven.
int col = Integer.parseInt(coords[0]);
int row = Integer.parseInt(coords[1]);
//Let op hoe we opnieuw door een twee-dimensionale array lopen
if ((row >= 0) && (row < 3)) {
if ((col >= 0) && (col < 3)) {
if (board[row][col] == '-') {
board[row][col] = currentPlayerMark;
return true;
}
}
}
return false;
}
//Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig:
//voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat
//klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]).
private void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-'; // initieel is elk element een '-'
}
}
//Even voor het gemak de exacte coördinaten weergeven
printBoardCoords();
}
private void changePlayer() {
// hoe heet deze constructie?
currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X';
}
private boolean gameNotFinished() {
return !(isBoardFull() || checkForWin());
}
private void printBoard() {
System.out.println("+---+---+---+");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("+---+---+---+");
}
}
private void printBoardCoords() {
System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma.");
System.out.println("De coördinaten in het bord zijn als volgt:");
System.out.println("+-------+-------+-------+");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print("(" +j+","+i + ") | ");
}
System.out.println();
System.out.println("+-------+-------+-------+");
}
}
//Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te
//loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens
//een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet
//met een '-', in de methode initializeBoard)
private boolean isBoardFull() {
boolean isFull = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
isFull = false; //welke optimalisatie is hier nog mogelijk?
}
}
}
if (isFull) {
System.out.println("Het bord is vol; eind van het spel.");
return true;
}
return false;
}
// voor de rest: nevermind
private boolean checkForWin() {
if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) {
System.out.println("We hebben een winnaar: " +currentPlayerMark);
return true;
}
return false;
}
private boolean checkRowsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) {
return true;
}
}
return false;
}
private boolean checkColumnsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) {
return true;
}
}
return false;
}
private boolean checkDiagonalsForWin() {
return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true));
}
private boolean checkRowCol(char c1, char c2, char c3) {
return ((c1 != '-') && (c1 == c2) && (c2 == c3));
}
}
| Hanzehogeschool-hbo-ict/boterkaaseieren | BoterKaasEieren.java | 2,599 | //loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens | line_comment | nl | package nl.hanze.itann.ttt;
// deze import hebben we nodig voor gebruikersinput – let daar maar niet op.
import java.util.Scanner;
/*
EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS;
Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een
systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij
je de positie van stukken weergeeft als bijvoorbeeld 'H3'.
Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren'
uitgeprogrammeerd. Dit heeft een bord als volgt:
+------+------+------+
| (0,0 | (1,0 | (2,0 |
+------+------+------+
| (0,1 | (1,1 | (2,1 |
+------+------+------+
| (0,2 | (1,2 | (2,2 |
+------+------+------+
Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2
(drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan
het data-type een twee-dimensionale array van char's is:
private char[3][3] board
^ ^
| |
X ----------- --------Y
Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het
programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ
ik 2,1 (zonder haakjes).
Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk
gaat door een verkeerde input kun je vast wel bedenken waarom.
Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is.
*/
public class BoterKaasEieren {
public static void main(String[] args) {
new BoterKaasEieren();
}
// Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt.
private char[][] board;
// De huidige speler. Dit is ofwel een 'X' of een 'O'
private char currentPlayerMark;
//constructor
public BoterKaasEieren() {
board = new char[3][3];
currentPlayerMark = 'X';
initializeBoard();
playGame();
}
// Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is
// of er een winnaar is.
private void playGame() {
//De regels hieronder is om user-input op te vangen. Maak je daar niet druk om.
//Van belang is dat de input wordt opgeslagen in de variable 'input'.
Scanner reader = new Scanner(System.in);
String input = "";
//De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false'
//teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode
//wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven.
while (gameNotFinished()) {
//we printen elke keer de nieuwe status van het speelbord even uit
printBoard();
changePlayer();
// Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen.
System.out.println("De beurt in aan "+currentPlayerMark);
System.out.println("Geef positie op (x,y): ");
//Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd.
//Hierom kunnen we deze loop laten blijven lopen zonder dat er continu
//dingen op het scherm verschijnen.
input = reader.next();
//We maken een array van Strings van de input – check de API van de string:
// https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
String[] coords = input.split(",");
placeMark(coords);
}
// Even het winnende bord afdrukken
printBoard();
//als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om
//die even expliciet te sluiten.
reader.close();
}
private boolean placeMark(String[] coords) {
//We gaan er even van uit dat er in de input twee getallen zijn gegeven.
int col = Integer.parseInt(coords[0]);
int row = Integer.parseInt(coords[1]);
//Let op hoe we opnieuw door een twee-dimensionale array lopen
if ((row >= 0) && (row < 3)) {
if ((col >= 0) && (col < 3)) {
if (board[row][col] == '-') {
board[row][col] = currentPlayerMark;
return true;
}
}
}
return false;
}
//Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig:
//voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat
//klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]).
private void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-'; // initieel is elk element een '-'
}
}
//Even voor het gemak de exacte coördinaten weergeven
printBoardCoords();
}
private void changePlayer() {
// hoe heet deze constructie?
currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X';
}
private boolean gameNotFinished() {
return !(isBoardFull() || checkForWin());
}
private void printBoard() {
System.out.println("+---+---+---+");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("+---+---+---+");
}
}
private void printBoardCoords() {
System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma.");
System.out.println("De coördinaten in het bord zijn als volgt:");
System.out.println("+-------+-------+-------+");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print("(" +j+","+i + ") | ");
}
System.out.println();
System.out.println("+-------+-------+-------+");
}
}
//Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te
//loopen. We<SUF>
//een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet
//met een '-', in de methode initializeBoard)
private boolean isBoardFull() {
boolean isFull = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
isFull = false; //welke optimalisatie is hier nog mogelijk?
}
}
}
if (isFull) {
System.out.println("Het bord is vol; eind van het spel.");
return true;
}
return false;
}
// voor de rest: nevermind
private boolean checkForWin() {
if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) {
System.out.println("We hebben een winnaar: " +currentPlayerMark);
return true;
}
return false;
}
private boolean checkRowsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) {
return true;
}
}
return false;
}
private boolean checkColumnsForWin() {
for (int i = 0; i < 3; i++) {
if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) {
return true;
}
}
return false;
}
private boolean checkDiagonalsForWin() {
return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true));
}
private boolean checkRowCol(char c1, char c2, char c3) {
return ((c1 != '-') && (c1 == c2) && (c2 == c3));
}
}
|
33834_2 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package framework;
import framework.interfaces.Controller;
import framework.interfaces.Messagable;
import framework.interfaces.Networkable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.*;
import org.json.simple.*;
import org.json.simple.parser.*;
/**
* Get the lists for Players and Challenges. Give these to the View.
* Give the view to the ApplicationPane.
* @author Wouter
*/
public class LobbyController implements Networkable, Messagable, Controller{
@FXML
private ListView challenges;
@FXML
private ListView toChallenge;
@FXML
private Button subscribeButton;
@FXML
private Button refreshButton;
private ObservableList<ListObject> playersToChallenge = FXCollections.observableArrayList();
private ObservableList<ChallengeObject> incomingChallenges = FXCollections.observableArrayList();
private String game;
private String playerName = "";
private boolean tourny_mode = false;
public LobbyController(String game_to_play){
game = game_to_play;
}
public void init(){
toChallenge.setItems(playersToChallenge); // Hoeft maar 1 keer aangeroepen te worden
challenges.setItems(incomingChallenges);
MessageBus mb = MessageBus.getBus();
mb.call("NETWORK", "open", null);
mb.call("NETWORK", "login", null);
mb.call("NETWORK", "get name", new Object[] {this});
refreshPlayerList();
}
@Override
public void putData(ArrayList<String> messages) {
// Dit zijn messages die je krijgt van de server waar je naar vraagt.
for(String m: messages){
if(m.startsWith("SVR PLAYERLIST")){
// We received the playerlist we asked for.
makePlayerList(m.substring(15));
} else if (m.startsWith("name")) {
playerName = m.substring(5);
}
}
}
private void makePlayerList(String players){
try {
JSONParser parser = new JSONParser();
Object o = parser.parse(players);
JSONArray playerJSON = (JSONArray) o;
ArrayList<String> playerList = new ArrayList<>();
for (Object s : playerJSON) {
playerList.add((String) s);
}
playerList.remove(playerName);
// Filter duplicaten
Iterator<ListObject> it = playersToChallenge.iterator();
while (it.hasNext()) {
ListObject obj = it.next();
if (!playerList.contains(obj.getPlayerName())) {
it.remove();
} else {
playerList.remove(obj.getPlayerName());
}
}
// Voeg nieuwe toe
for (String player : playerList) {
playersToChallenge.add( new ListObject(player));
}
} catch (ParseException ex) {
Logger.getLogger(LobbyController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void handleSubscribe(ActionEvent event) {
MessageBus.getBus().call("GAME", "GAME SUBSCRIBE", null);
}
@FXML
private void handleRefresh(ActionEvent event) {
refreshPlayerList();
}
private void addChallenge(String challenger, String challengeNumber) {
Platform.runLater( () -> incomingChallenges.add(new ChallengeObject(challenger, challengeNumber)) );
}
private void acceptChallenge(ChallengeObject challenge) {
MessageBus.getBus().call("GAME", "GAME CHALLENGE ACCEPT", new String[] {challenge.getChallengeNumber()} );
}
private void removeChallenge(ChallengeObject challenge) {
// Negeer challenge
incomingChallenges.remove(challenge);
}
@Override
public void call(String message, Object[] args){
if (message.equals("CHALLENGE")) {
addChallenge((String) args[0], (String) args[1]);
}
}
@Override
public String getLocation() {
return "../framework/assets/LobbyView.fxml";
}
private void refreshPlayerList() {
Object[] args = new Object[1];
args[0] = this;
MessageBus.getBus().call("NETWORK", "get players", args);
}
/**
* Deze private class zorgt voor een nette afhandeling van iedere speler in de lijst
* (Moet mogelijk verplaatst worden naar LobbyView)
*/
private class ListObject extends GridPane {
private String playerName;
private Label playerLabel;
private Button playerButton;
private ListObject(String playerName) {
this.playerName = playerName;
playerLabel = new Label(playerName);
playerButton = createButton();
// De button kan gestyled worden met de .challengebutton class
playerButton.getStyleClass().add("challengebutton");
this.add(playerLabel, 0, 0);
this.add(playerButton, 1, 0);
setConstrains();
}
private String getPlayerName() {
return playerName;
}
private void setPlayerName(String playerName) {
this.playerName = playerName;
}
private Button createButton() {
Button btn = new Button("Challenge");
btn.setOnAction( event ->
MessageBus.getBus().call("NETWORK", "challenge \"" + this.playerName + "\" \"" + game +"\"", null)
);
return btn;
}
private void setConstrains() {
ColumnConstraints constraints = new ColumnConstraints();
constraints.setFillWidth(true);
constraints.setHgrow(Priority.ALWAYS);
this.getColumnConstraints().add(constraints);
}
}
/**
* Deze private class zorgt voor een nette vertoning en afhandeling van alle binnenkomende challenges.
* (Moet mogelijk verplaatst worden naar LobbyView)
*/
private class ChallengeObject extends GridPane {
private String playerName;
private String challengeNumber;
private Label nameLabel;
private Button acceptButton;
private Button declineButton;
private ChallengeObject(String playerName, String challengeNumber) {
this.playerName = playerName;
this.challengeNumber = challengeNumber;
nameLabel = new Label(playerName);
acceptButton = createAcceptButton();
declineButton = createDeclineButton();
this.add(nameLabel, 0, 0);
this.add(new HBox(acceptButton, declineButton), 1, 0);
setConstrains();
}
private Button createAcceptButton() {
Button btn = new Button("Accept");
btn.getStyleClass().add("acceptChallengeButton");
btn.setOnAction(event -> acceptChallenge(this));
return btn;
}
private Button createDeclineButton() {
Button btn = new Button("Decline");
btn.getStyleClass().add("declineChallengeButton");
btn.setOnAction(event -> removeChallenge(this));
return btn;
}
public String getPlayerName() {
return playerName;
}
public String getChallengeNumber() {
return challengeNumber;
}
private void setConstrains() {
ColumnConstraints cc1 = new ColumnConstraints();
cc1.setFillWidth(true);
cc1.setHgrow(Priority.ALWAYS);
this.getColumnConstraints().add(cc1);
}
}
}
| HanzehogeschoolSICT/GameClient | src/framework/LobbyController.java | 2,187 | // Hoeft maar 1 keer aangeroepen te worden | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package framework;
import framework.interfaces.Controller;
import framework.interfaces.Messagable;
import framework.interfaces.Networkable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.*;
import org.json.simple.*;
import org.json.simple.parser.*;
/**
* Get the lists for Players and Challenges. Give these to the View.
* Give the view to the ApplicationPane.
* @author Wouter
*/
public class LobbyController implements Networkable, Messagable, Controller{
@FXML
private ListView challenges;
@FXML
private ListView toChallenge;
@FXML
private Button subscribeButton;
@FXML
private Button refreshButton;
private ObservableList<ListObject> playersToChallenge = FXCollections.observableArrayList();
private ObservableList<ChallengeObject> incomingChallenges = FXCollections.observableArrayList();
private String game;
private String playerName = "";
private boolean tourny_mode = false;
public LobbyController(String game_to_play){
game = game_to_play;
}
public void init(){
toChallenge.setItems(playersToChallenge); // Hoeft maar<SUF>
challenges.setItems(incomingChallenges);
MessageBus mb = MessageBus.getBus();
mb.call("NETWORK", "open", null);
mb.call("NETWORK", "login", null);
mb.call("NETWORK", "get name", new Object[] {this});
refreshPlayerList();
}
@Override
public void putData(ArrayList<String> messages) {
// Dit zijn messages die je krijgt van de server waar je naar vraagt.
for(String m: messages){
if(m.startsWith("SVR PLAYERLIST")){
// We received the playerlist we asked for.
makePlayerList(m.substring(15));
} else if (m.startsWith("name")) {
playerName = m.substring(5);
}
}
}
private void makePlayerList(String players){
try {
JSONParser parser = new JSONParser();
Object o = parser.parse(players);
JSONArray playerJSON = (JSONArray) o;
ArrayList<String> playerList = new ArrayList<>();
for (Object s : playerJSON) {
playerList.add((String) s);
}
playerList.remove(playerName);
// Filter duplicaten
Iterator<ListObject> it = playersToChallenge.iterator();
while (it.hasNext()) {
ListObject obj = it.next();
if (!playerList.contains(obj.getPlayerName())) {
it.remove();
} else {
playerList.remove(obj.getPlayerName());
}
}
// Voeg nieuwe toe
for (String player : playerList) {
playersToChallenge.add( new ListObject(player));
}
} catch (ParseException ex) {
Logger.getLogger(LobbyController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void handleSubscribe(ActionEvent event) {
MessageBus.getBus().call("GAME", "GAME SUBSCRIBE", null);
}
@FXML
private void handleRefresh(ActionEvent event) {
refreshPlayerList();
}
private void addChallenge(String challenger, String challengeNumber) {
Platform.runLater( () -> incomingChallenges.add(new ChallengeObject(challenger, challengeNumber)) );
}
private void acceptChallenge(ChallengeObject challenge) {
MessageBus.getBus().call("GAME", "GAME CHALLENGE ACCEPT", new String[] {challenge.getChallengeNumber()} );
}
private void removeChallenge(ChallengeObject challenge) {
// Negeer challenge
incomingChallenges.remove(challenge);
}
@Override
public void call(String message, Object[] args){
if (message.equals("CHALLENGE")) {
addChallenge((String) args[0], (String) args[1]);
}
}
@Override
public String getLocation() {
return "../framework/assets/LobbyView.fxml";
}
private void refreshPlayerList() {
Object[] args = new Object[1];
args[0] = this;
MessageBus.getBus().call("NETWORK", "get players", args);
}
/**
* Deze private class zorgt voor een nette afhandeling van iedere speler in de lijst
* (Moet mogelijk verplaatst worden naar LobbyView)
*/
private class ListObject extends GridPane {
private String playerName;
private Label playerLabel;
private Button playerButton;
private ListObject(String playerName) {
this.playerName = playerName;
playerLabel = new Label(playerName);
playerButton = createButton();
// De button kan gestyled worden met de .challengebutton class
playerButton.getStyleClass().add("challengebutton");
this.add(playerLabel, 0, 0);
this.add(playerButton, 1, 0);
setConstrains();
}
private String getPlayerName() {
return playerName;
}
private void setPlayerName(String playerName) {
this.playerName = playerName;
}
private Button createButton() {
Button btn = new Button("Challenge");
btn.setOnAction( event ->
MessageBus.getBus().call("NETWORK", "challenge \"" + this.playerName + "\" \"" + game +"\"", null)
);
return btn;
}
private void setConstrains() {
ColumnConstraints constraints = new ColumnConstraints();
constraints.setFillWidth(true);
constraints.setHgrow(Priority.ALWAYS);
this.getColumnConstraints().add(constraints);
}
}
/**
* Deze private class zorgt voor een nette vertoning en afhandeling van alle binnenkomende challenges.
* (Moet mogelijk verplaatst worden naar LobbyView)
*/
private class ChallengeObject extends GridPane {
private String playerName;
private String challengeNumber;
private Label nameLabel;
private Button acceptButton;
private Button declineButton;
private ChallengeObject(String playerName, String challengeNumber) {
this.playerName = playerName;
this.challengeNumber = challengeNumber;
nameLabel = new Label(playerName);
acceptButton = createAcceptButton();
declineButton = createDeclineButton();
this.add(nameLabel, 0, 0);
this.add(new HBox(acceptButton, declineButton), 1, 0);
setConstrains();
}
private Button createAcceptButton() {
Button btn = new Button("Accept");
btn.getStyleClass().add("acceptChallengeButton");
btn.setOnAction(event -> acceptChallenge(this));
return btn;
}
private Button createDeclineButton() {
Button btn = new Button("Decline");
btn.getStyleClass().add("declineChallengeButton");
btn.setOnAction(event -> removeChallenge(this));
return btn;
}
public String getPlayerName() {
return playerName;
}
public String getChallengeNumber() {
return challengeNumber;
}
private void setConstrains() {
ColumnConstraints cc1 = new ColumnConstraints();
cc1.setFillWidth(true);
cc1.setHgrow(Priority.ALWAYS);
this.getColumnConstraints().add(cc1);
}
}
}
|
122759_15 | package model.io;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import java.io.*;
import java.lang.reflect.MalformedParametersException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Connection {
private Integer port;
private String address;
private Socket socket;
private String playerName;
private OutputServer outputServer;
private InputServer inputServer;
private Observer observer;
public Connection(String address, Integer port) {
if (!isAdressValid(address)) throw new MalformedParametersException("Malformed address: " + address);
if (port <= 0 || port > 65535) throw new MalformedParametersException("Malformed port: " + port);
this.address = address;
this.port = port;
}
/**
* Establishes a new connection to the game server with the given username.
* When the connection is not successful an IOException is thrown.
* @param playerName The username of the player that want to connect.
* @throws IOException Thrown when a connection to the server cannot be established.
*/
public void establish(String playerName) throws IOException {
this.outputServer = new OutputServer(this);
this.inputServer = new InputServer(this);
setObserver();
this.outputServer.start();
inputServer.start();
login(playerName);
}
/**
* Stops the connection to the server by closing the socket.
* This is turn stops the while loops and closes the threads.
* @throws IOException Thrown when the socket cannot be closed.
*/
public void stop() throws IOException {
this.logout();
this.socket.close();
}
private void setObserver() {
OutputHandler handler = new OutputHandler(observer);
this.outputServer.setObserver(new OutputServer.Observer() {
@Override
public void onNewLine(String line) {
handler.handle(line);
}
/**
* Returns the IP of the connected game server.
* @return The IP of the connected game server.
*/
@Override
public void onEndOfLine() {
System.out.println("===============================");
}
});
}
public static boolean isAdressValid(String address) {
Pattern pattern = Pattern.compile("" +
"^" + //Starts with...
"(" +
"(" +
"[01]?\\d\\d?" + //If starts with 0 or 1, one or 2 digits, if three; it must start with 0 or 1
"|" +
"2[0-4]\\d" + //If starts with 2, can be followed by 0-4 and/or any digit.
"|" +
"25[0-5]" + //If starts with 25, can be followed by any number in the range 0-5
")" +
"\\." + //Ends with a "."
"){3}" + //Repeat 3 times. eg: "255.255.255."
"(" +
"[01]?\\d\\d?" +
"|" +
"2[0-4]\\d" +
"|" +
"25[0-5]" +
")" +
"$");
return pattern.matcher(address).find();
}
/**
* Sends a login request to the outputServer to login the player with the given playerName.
* <pre>
* {@code
* Inloggen:
* C: login <speler>
* S: OK
* ->Nu ingelogd met spelernaam <speler>.
* }
* </pre>
* @param playerName The name to register. (cannot be null)
*/
public void login(@NotNull String playerName) {
this.playerName = playerName;
this.inputServer.submit("login " + playerName);
}
/**
* Sends a logout request to the outputServer to logout the current player.
* Returns nothing when successful, else it returns a {@code Connection.ServerMessage.ERR} with the reason of failure.
* <pre>
* {@code
* Uitloggen/Verbinding verbreken:
* C: logout | exit | quit | disconnect | bye
* S: -
* ->Verbinding is verbroken.
* }
* </pre>
*/
public void logout(){
this.inputServer.submit("logout");
}
/**
* Sends a request to the outputServer in order to retrieve a list of available games on the outputServer.
* <pre>
* {@code
* Lijst opvragen met ondersteunde spellen:
* C: get gamelist
* S: OK
* S: SVR GAMELIST ["<speltype>", ...]
* ->Lijst met spellen ontvangen.
* }
* </pre>
*/
public void getGameList(){
this.inputServer.submit("get gamelist");
}
/**
* Sends a request to the outputServer in order to retrieve a list of logged-in players on the outputServer.
* <pre>
* {@code
* Lijst opvragen met verbonden spelers:
* C: get playerlist
* S: OK
* S: SVR PLAYERLIST ["<speler>", ...]
* ->Lijst met spelers ontvangen.
* }
* </pre>
*/
public void getPlayerList(){
this.inputServer.submit("get playerlist");
}
/**
* Sends a request to the outputServer in order to subscribe to a gametype on the outputServer.
* <pre>
* {@code
* Lijst opvragen met verbonden spelers:
* C: get playerlist
* S: OK
* S: SVR PLAYERLIST ["<speler>", ...]
* ->Lijst met spelers ontvangen.
* }
* </pre>
* @param gameType The gametype to subscribe to.
*/
public void subscribe(@NotNull String gameType){
this.inputServer.submit("subscribe " + gameType);
}
/**
* Sends a request to the outputServer to do a move.
* <pre>
* {@code
* Een zet doen na het toegewezen krijgen van een beurt:
* C: move <zet>
* S: OK
* ->De zet is geaccepteerd door de outputServer, gevolg voor spel zal volgen
* }
* </pre>
* @param move The move to do.
*/
public void move(@NotNull Integer move){
this.inputServer.submit("move " + move);
}
/**
* Sends a request to the outputServer in order to forfeit and tell the other player you give up.
* <pre>
* {@code
* Een match opgeven:
* C: forfeit
* S: OK
* ->De speler heeft het spel opgegeven, de outputServer zal het resultaat van de match doorgeven.
* }
* </pre>
*/
public void forfeit(){
this.inputServer.submit("forfeit");
}
/**
* Send a request to the outputServer in order to challenge another player to a game using the players name and what game to play.
* <pre>
* {@code
* Een speler uitdagen voor een spel:
* C: challenge "<speler>" "<speltype>"
* S: OK
* ->De speler is nu uitgedaagd voor een spel. Eerder gemaakte uitdagingen zijn komen te vervallen.
* }
* </pre>
* @param opponentName The name of the opponent to challenge.
* @param gameType The type of game to play.
*/
public void challenge(String opponentName, String gameType){
this.inputServer.submit("challenge \"" + opponentName + "\" \"" + gameType + "\"");
}
/**
* Sends a request to the outputServer in order to accept a pending challenge invite from another player.
* <pre>
* {@code
* Een uitdaging accepteren:
* C: challenge accept <uitdaging nummer>
* S: OK
* ->De uitdaging is geaccepteerd. De match wordt gestart, bericht volgt.
* }
* </pre>
* @param challengeNumber The challenge number of the challenge to be accepted.
*/
public void accept_challenge(Integer challengeNumber){
this.inputServer.submit("challenge accept " + challengeNumber);
}
/**
* Send a request to the outputServer in order to view the help page of either a command or the full page.
* <pre>
* {@code
* Help opvragen:
* C: help
* S: OK
* ->De client heeft nu help informatie opgevraagd, de outputServer zal antwoorden met help informatie.
*
* Help opvragen van een commando:
* C: help <commando>
* S: OK
* ->De client heeft nu help informatie opgevraagd voor een commando, de outputServer zal antwoorden met help informatie.
* }
* </pre>
* @param command The command to view the help page of, if null, the full help page is shown.
*/
@Deprecated
public void help(@Nullable String command){
this.inputServer.submit("help " + (command != null ? command : "")); //Add the command if it isn't null.
}
public interface Observer {
void onMove(String player, String details, int move);
void onYourTurn(String comment);
void onGameMatch(String playerMove, String gameType, String Opponent);
void onGameEnd(int statusCode, String comment);
void onChallenge(String opponentName, int challengeNumber, String gameType);
void onChallengeCancelled(int challengeNumber, String comment);
void onGameList(ArrayList<String> games);
void onPlayerList(ArrayList<String> players);
void onError(String comment);
}
//<editor-fold desc="Getters and Setters">
public Integer getPort() {
return port;
}
public String getAddress() {
return address;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public Socket getSocket() {
return socket;
}
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getServerIpAddress(){
return this.address;
}
public String getPlayerName(){
return this.playerName;
}
//</editor-fold>
}
| HanzehogeschoolSICT/ITV2E2-Project | src/model/io/Connection.java | 2,924 | /**
* Send a request to the outputServer in order to challenge another player to a game using the players name and what game to play.
* <pre>
* {@code
* Een speler uitdagen voor een spel:
* C: challenge "<speler>" "<speltype>"
* S: OK
* ->De speler is nu uitgedaagd voor een spel. Eerder gemaakte uitdagingen zijn komen te vervallen.
* }
* </pre>
* @param opponentName The name of the opponent to challenge.
* @param gameType The type of game to play.
*/ | block_comment | nl | package model.io;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import java.io.*;
import java.lang.reflect.MalformedParametersException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Connection {
private Integer port;
private String address;
private Socket socket;
private String playerName;
private OutputServer outputServer;
private InputServer inputServer;
private Observer observer;
public Connection(String address, Integer port) {
if (!isAdressValid(address)) throw new MalformedParametersException("Malformed address: " + address);
if (port <= 0 || port > 65535) throw new MalformedParametersException("Malformed port: " + port);
this.address = address;
this.port = port;
}
/**
* Establishes a new connection to the game server with the given username.
* When the connection is not successful an IOException is thrown.
* @param playerName The username of the player that want to connect.
* @throws IOException Thrown when a connection to the server cannot be established.
*/
public void establish(String playerName) throws IOException {
this.outputServer = new OutputServer(this);
this.inputServer = new InputServer(this);
setObserver();
this.outputServer.start();
inputServer.start();
login(playerName);
}
/**
* Stops the connection to the server by closing the socket.
* This is turn stops the while loops and closes the threads.
* @throws IOException Thrown when the socket cannot be closed.
*/
public void stop() throws IOException {
this.logout();
this.socket.close();
}
private void setObserver() {
OutputHandler handler = new OutputHandler(observer);
this.outputServer.setObserver(new OutputServer.Observer() {
@Override
public void onNewLine(String line) {
handler.handle(line);
}
/**
* Returns the IP of the connected game server.
* @return The IP of the connected game server.
*/
@Override
public void onEndOfLine() {
System.out.println("===============================");
}
});
}
public static boolean isAdressValid(String address) {
Pattern pattern = Pattern.compile("" +
"^" + //Starts with...
"(" +
"(" +
"[01]?\\d\\d?" + //If starts with 0 or 1, one or 2 digits, if three; it must start with 0 or 1
"|" +
"2[0-4]\\d" + //If starts with 2, can be followed by 0-4 and/or any digit.
"|" +
"25[0-5]" + //If starts with 25, can be followed by any number in the range 0-5
")" +
"\\." + //Ends with a "."
"){3}" + //Repeat 3 times. eg: "255.255.255."
"(" +
"[01]?\\d\\d?" +
"|" +
"2[0-4]\\d" +
"|" +
"25[0-5]" +
")" +
"$");
return pattern.matcher(address).find();
}
/**
* Sends a login request to the outputServer to login the player with the given playerName.
* <pre>
* {@code
* Inloggen:
* C: login <speler>
* S: OK
* ->Nu ingelogd met spelernaam <speler>.
* }
* </pre>
* @param playerName The name to register. (cannot be null)
*/
public void login(@NotNull String playerName) {
this.playerName = playerName;
this.inputServer.submit("login " + playerName);
}
/**
* Sends a logout request to the outputServer to logout the current player.
* Returns nothing when successful, else it returns a {@code Connection.ServerMessage.ERR} with the reason of failure.
* <pre>
* {@code
* Uitloggen/Verbinding verbreken:
* C: logout | exit | quit | disconnect | bye
* S: -
* ->Verbinding is verbroken.
* }
* </pre>
*/
public void logout(){
this.inputServer.submit("logout");
}
/**
* Sends a request to the outputServer in order to retrieve a list of available games on the outputServer.
* <pre>
* {@code
* Lijst opvragen met ondersteunde spellen:
* C: get gamelist
* S: OK
* S: SVR GAMELIST ["<speltype>", ...]
* ->Lijst met spellen ontvangen.
* }
* </pre>
*/
public void getGameList(){
this.inputServer.submit("get gamelist");
}
/**
* Sends a request to the outputServer in order to retrieve a list of logged-in players on the outputServer.
* <pre>
* {@code
* Lijst opvragen met verbonden spelers:
* C: get playerlist
* S: OK
* S: SVR PLAYERLIST ["<speler>", ...]
* ->Lijst met spelers ontvangen.
* }
* </pre>
*/
public void getPlayerList(){
this.inputServer.submit("get playerlist");
}
/**
* Sends a request to the outputServer in order to subscribe to a gametype on the outputServer.
* <pre>
* {@code
* Lijst opvragen met verbonden spelers:
* C: get playerlist
* S: OK
* S: SVR PLAYERLIST ["<speler>", ...]
* ->Lijst met spelers ontvangen.
* }
* </pre>
* @param gameType The gametype to subscribe to.
*/
public void subscribe(@NotNull String gameType){
this.inputServer.submit("subscribe " + gameType);
}
/**
* Sends a request to the outputServer to do a move.
* <pre>
* {@code
* Een zet doen na het toegewezen krijgen van een beurt:
* C: move <zet>
* S: OK
* ->De zet is geaccepteerd door de outputServer, gevolg voor spel zal volgen
* }
* </pre>
* @param move The move to do.
*/
public void move(@NotNull Integer move){
this.inputServer.submit("move " + move);
}
/**
* Sends a request to the outputServer in order to forfeit and tell the other player you give up.
* <pre>
* {@code
* Een match opgeven:
* C: forfeit
* S: OK
* ->De speler heeft het spel opgegeven, de outputServer zal het resultaat van de match doorgeven.
* }
* </pre>
*/
public void forfeit(){
this.inputServer.submit("forfeit");
}
/**
* Send a request<SUF>*/
public void challenge(String opponentName, String gameType){
this.inputServer.submit("challenge \"" + opponentName + "\" \"" + gameType + "\"");
}
/**
* Sends a request to the outputServer in order to accept a pending challenge invite from another player.
* <pre>
* {@code
* Een uitdaging accepteren:
* C: challenge accept <uitdaging nummer>
* S: OK
* ->De uitdaging is geaccepteerd. De match wordt gestart, bericht volgt.
* }
* </pre>
* @param challengeNumber The challenge number of the challenge to be accepted.
*/
public void accept_challenge(Integer challengeNumber){
this.inputServer.submit("challenge accept " + challengeNumber);
}
/**
* Send a request to the outputServer in order to view the help page of either a command or the full page.
* <pre>
* {@code
* Help opvragen:
* C: help
* S: OK
* ->De client heeft nu help informatie opgevraagd, de outputServer zal antwoorden met help informatie.
*
* Help opvragen van een commando:
* C: help <commando>
* S: OK
* ->De client heeft nu help informatie opgevraagd voor een commando, de outputServer zal antwoorden met help informatie.
* }
* </pre>
* @param command The command to view the help page of, if null, the full help page is shown.
*/
@Deprecated
public void help(@Nullable String command){
this.inputServer.submit("help " + (command != null ? command : "")); //Add the command if it isn't null.
}
public interface Observer {
void onMove(String player, String details, int move);
void onYourTurn(String comment);
void onGameMatch(String playerMove, String gameType, String Opponent);
void onGameEnd(int statusCode, String comment);
void onChallenge(String opponentName, int challengeNumber, String gameType);
void onChallengeCancelled(int challengeNumber, String comment);
void onGameList(ArrayList<String> games);
void onPlayerList(ArrayList<String> players);
void onError(String comment);
}
//<editor-fold desc="Getters and Setters">
public Integer getPort() {
return port;
}
public String getAddress() {
return address;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public Socket getSocket() {
return socket;
}
public void setObserver(Observer observer) {
this.observer = observer;
}
public String getServerIpAddress(){
return this.address;
}
public String getPlayerName(){
return this.playerName;
}
//</editor-fold>
}
|
33673_0 | package controller;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.io.IOException;
/**
* View gemaakt met Gluon Scenebuilder
*/
public class Main extends Application{
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/view/layout.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
Platform.exit();
System.exit(0);
}
});
}
} | HanzehogeschoolSICT/InleverOpdracht1-Vincent-Luder-Niek-Beukema-ITV2E | src/controller/Main.java | 271 | /**
* View gemaakt met Gluon Scenebuilder
*/ | block_comment | nl | package controller;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.io.IOException;
/**
* View gemaakt met<SUF>*/
public class Main extends Application{
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/view/layout.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
Platform.exit();
System.exit(0);
}
});
}
} |
23103_0 | package main;
import model.Board;
import model.GetSolutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
//Het enige dat niet werkt is het overslaan van letter die al zijn geweest.
public static void main(String[] args) {
List<String> alreadyBeenHere = new ArrayList<>();
Board board = new Board(alreadyBeenHere);
board.printBoard();
System.out.println("\n" + "---- Solutions ----");
GetSolutions getSolutions = new GetSolutions(alreadyBeenHere, board);
getSolutions.total();
System.out.println(getSolutions.getHits());
}
} | HanzehogeschoolSICT/InleverOpdracht2_JoeriJorisITV2E | src/main/Main.java | 187 | //Het enige dat niet werkt is het overslaan van letter die al zijn geweest. | line_comment | nl | package main;
import model.Board;
import model.GetSolutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
//Het enige<SUF>
public static void main(String[] args) {
List<String> alreadyBeenHere = new ArrayList<>();
Board board = new Board(alreadyBeenHere);
board.printBoard();
System.out.println("\n" + "---- Solutions ----");
GetSolutions getSolutions = new GetSolutions(alreadyBeenHere, board);
getSolutions.total();
System.out.println(getSolutions.getHits());
}
} |
36779_0 | package model;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* Gemaakt door Vincent & Niek
* Met hulp van Ronan
* Bronnen: http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java
* http://stackoverflow.com/questions/23075689/how-to-do-a-recursive-search-for-a-word-in-the-boggle-game-board
*/
public class Solver {
private boolean[][] isVisited;
private ArrayList<String> woordenLijst = new ArrayList<>();
private Set<String> foundWords = new HashSet<String>();
public Set<String> solve(String[][] board){
loadWordList();
isVisited = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
searchWord(board, i, j, "");
clearVisited(board.length,board[0].length);
}
}
return foundWords;
}
private void loadWordList(){
try {
URL url = getClass().getResource("dict.txt");
BufferedReader br = new BufferedReader(new FileReader(url.getPath()));
String line;
while ((line = br.readLine()) != null) {
woordenLijst.add(line);
}
} catch (IOException ex){
ex.printStackTrace();
}
}
private void clearVisited(int xSize, int ySize){
for(int i = 0; i <xSize; i++) {
for(int j = 0; j <ySize; j++) {
isVisited[i][j] = false;
}
}
}
private void searchWord(String[][] board, int xPos, int yPos, String word){
word += board[xPos][yPos];
if (isVisited[xPos][yPos]) {return;}
isVisited[xPos][yPos] = true;
for(String checkWord: woordenLijst){
if (checkWord.equals(word)){
foundWords.add(word);
}
if(checkWord.startsWith(word) && xPos>0 && yPos>0 && xPos<board.length-1 && yPos<board.length-1 ){
searchWord(board,xPos+1, yPos, word); // positie naar rechts
searchWord(board,xPos, yPos+1, word); // positie omhoog
searchWord(board,xPos-1, yPos, word); // positie naar links
searchWord(board,xPos, yPos-1, word); // positie naar beneden
searchWord(board,xPos+1, yPos+1, word); //topright
searchWord(board,xPos-1, yPos-1, word);//bottomleft
searchWord(board,xPos-1, yPos+1, word);//topleft
searchWord(board,xPos+1, yPos-1, word);//bottomright
break;
}
}
}
}
| HanzehogeschoolSICT/Inleveropdracht2-VincentLuder-NiekBeukema-ITV2E | src/model/Solver.java | 875 | /**
* Gemaakt door Vincent & Niek
* Met hulp van Ronan
* Bronnen: http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java
* http://stackoverflow.com/questions/23075689/how-to-do-a-recursive-search-for-a-word-in-the-boggle-game-board
*/ | block_comment | nl | package model;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* Gemaakt door Vincent<SUF>*/
public class Solver {
private boolean[][] isVisited;
private ArrayList<String> woordenLijst = new ArrayList<>();
private Set<String> foundWords = new HashSet<String>();
public Set<String> solve(String[][] board){
loadWordList();
isVisited = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
searchWord(board, i, j, "");
clearVisited(board.length,board[0].length);
}
}
return foundWords;
}
private void loadWordList(){
try {
URL url = getClass().getResource("dict.txt");
BufferedReader br = new BufferedReader(new FileReader(url.getPath()));
String line;
while ((line = br.readLine()) != null) {
woordenLijst.add(line);
}
} catch (IOException ex){
ex.printStackTrace();
}
}
private void clearVisited(int xSize, int ySize){
for(int i = 0; i <xSize; i++) {
for(int j = 0; j <ySize; j++) {
isVisited[i][j] = false;
}
}
}
private void searchWord(String[][] board, int xPos, int yPos, String word){
word += board[xPos][yPos];
if (isVisited[xPos][yPos]) {return;}
isVisited[xPos][yPos] = true;
for(String checkWord: woordenLijst){
if (checkWord.equals(word)){
foundWords.add(word);
}
if(checkWord.startsWith(word) && xPos>0 && yPos>0 && xPos<board.length-1 && yPos<board.length-1 ){
searchWord(board,xPos+1, yPos, word); // positie naar rechts
searchWord(board,xPos, yPos+1, word); // positie omhoog
searchWord(board,xPos-1, yPos, word); // positie naar links
searchWord(board,xPos, yPos-1, word); // positie naar beneden
searchWord(board,xPos+1, yPos+1, word); //topright
searchWord(board,xPos-1, yPos-1, word);//bottomleft
searchWord(board,xPos-1, yPos+1, word);//topleft
searchWord(board,xPos+1, yPos-1, word);//bottomright
break;
}
}
}
}
|
5522_9 | import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.util.*;
import static javafx.scene.chart.XYChart.Data;
import static javafx.scene.chart.XYChart.Series;
public class Sort extends Application {
private Slider slider = new Slider();
public static void main(String[] args) {
launch(args);
}
private static final int
BAR_COUNT = 14,
MAX_BAR_HEIGHT = 50;
private static final String
COLOR_INITIAL = "-fx-bar-fill: #888";
private int pointer = 1;
private int notSwapped = 0;
private int finished = 0;
private ObservableList<Data<String, Number>> bars;
private BarChart<String, Number> chart;
private FlowPane inputs;
//Quicksort Dingen van jesse
private boolean firstLoop = false;
private HashMap<String, Integer> myMap;
private HashMap<String, Integer> emptyMap;
private boolean checkEmpty = false;
@Override
public void start(Stage stage) {
stage.setTitle("Sorting Animations");
stage.setWidth(1024);
stage.setHeight(576);
final BorderPane pane = new BorderPane();
pane.setPadding(new Insets(10));
makeChart(pane);
makeButtons(pane);
stage.setScene(new Scene(pane));
stage.show();
randomizeAll(pane);
}
private void makeChart(BorderPane pane) {
chart = new BarChart<>(new CategoryAxis(), new NumberAxis(0, MAX_BAR_HEIGHT, 0));
chart.setLegendVisible(false);
chart.getYAxis().setTickLabelsVisible(false);
chart.getYAxis().setOpacity(0);
chart.getXAxis().setTickLabelsVisible(false);
chart.getXAxis().setOpacity(0);
chart.setHorizontalGridLinesVisible(false);
chart.setVerticalGridLinesVisible(false);
bars = FXCollections.observableArrayList();
chart.getData().add(new Series<>(bars));
for (int i = 0; i < BAR_COUNT; i++) {
Data<String, Number> dataObject = new Data<>(Integer.toString(i + 1), 1);
bars.add(dataObject); // node will be present after this
addPainting(dataObject.getNode(), COLOR_INITIAL); // do this after bars.add
}
pane.setCenter(chart);
}
private void makeButtons(BorderPane pane) {
inputs = new FlowPane();
inputs.setHgap(5);
inputs.setVgap(5);
createButton("Nieuwe Chart", () -> randomizeAll(pane));
createButton("Bubblesort start", () -> bubbleSort(pane));
createButton("Bubblesort per stap", () -> oneStepBubble(pane));
createButton("Insertionsort start", () -> insertionsort(pane));
createButton("Insertionsort per stap", () -> oneStepInsertion(pane));
createButton("Quicksort start", () -> quicksort(pane));
createButton("Quicksort per stap", () -> oneStepQuick(pane));
makeSlider(50, 500, 250);
pane.setBottom(inputs);
}
private void makeSlider(int min, int max, int standaard) {
slider.setMin(min);
slider.setMax(max);
slider.setValue(standaard);
slider.setMajorTickUnit(standaard-min);
slider.setBlockIncrement(max/10);
slider.setShowTickMarks(true);
slider.setShowTickLabels(true);
inputs.getChildren().add(slider);
}
private void addPainting(Node newNode, String colorInitial) {
if (newNode != null) {
newNode.setStyle(colorInitial);
}
}
private void createButton(String label, Runnable method) {
final Button test = new Button(label);
test.setOnAction(event -> method.run());
inputs.getChildren().add(test);
}
private void randomizeAll(BorderPane pane) {
finished = 0;
pointer = 1;
Random random = new Random();
for (Data<String, Number> bar : bars) {
bar.setYValue(random.nextInt(MAX_BAR_HEIGHT) + 1);
}
}
/**
* Bubble Sort algorithm
*/
private void bubbleSort(BorderPane pane){
List<Data<String, Number>> list = bars;
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
oneStepBubble(pane);
}
}, 0, 550 - (int) slider.getValue());
}
private double getValue(List<Data<String, Number>> list, int index) {
return list.get(index).getYValue().doubleValue();
}
/**
* Bubble Sort one step algorithm
*/
private void oneStepBubble(BorderPane pane) {
if (finished != 1) {
List<Data<String, Number>> list = bars;
double temp;
if (getValue(list, pointer - 1) > getValue(list, pointer)) {
temp = getValue(list, pointer - 1);
list.get(pointer - 1).setYValue(list.get(pointer).getYValue());
list.get(pointer).setYValue(temp);
} else {
notSwapped += 1;
}
if (pointer >= 13) {
pointer = 1;
if (notSwapped >= 13) {
finished = 1;
}
else {
notSwapped = 0;
}
} else {
pointer += 1;
}
}
}
private void insertionsort(BorderPane pane) {
List<Data<String, Number>> list = bars;
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
oneStepInsertion(pane);
}
}, 0, 550 - (int) slider.getValue());
}
private void oneStepInsertion(BorderPane pane) {
if(finished != 1) {
List<Data<String, Number>> list = bars;
int j = pointer;
int temp = (int) getValue(list, pointer);
int newValue = temp;
while (j > 0 && getValue(list, j - 1) > newValue) {
list.get(j).setYValue(getValue(list, j - 1));
j--;
}
list.get(j).setYValue(newValue);
if (pointer >= 13) {
finished = 1;
}
else {
pointer++;
}
}
}
private void quicksort(BorderPane pane) {
List<Data<String, Number>> list = bars;
int a = 0;
int b = list.size() -1;
quickSort(list, a, b);
}
private void oneStepQuick(BorderPane pane) {
List<Data<String, Number>> list = bars;
if (firstLoop == false) {
int a = 0;
int b = list.size() -1;
quickSort(list, a, b, true);
firstLoop = true;
} else {
int a = myMap.get("A");
int b = myMap.get("B");
int wallIndex = myMap.get("Wallindex");
quickSort(list, a, wallIndex-1, true);
quickSort(list, wallIndex+1, b, true);
}
}
public void quickSort(List<Data<String, Number>> list, int a, int b) {
/**
* Kijk of A groter of gelijk is aan B. A begint op 0 (laagste index) en B begint op de hoogste index
* Zie hiervoor ook list.size()-1
*/
if (a >= b) {
return;
}
/** Bepaal de Pivot voor de quicksort */
int pivotValue = (int) getValue(list, b);
int wallIndex = a;
/**
* Is er een waarde groter dan de Pivot? Switch!
* Wanneer een waarde niet groter is dan de pivot, wordt de wall +1 gedaan.
* */
for (int i = a; i < b; i++) {
if(getValue(list, i) < pivotValue) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(i).getYValue());
list.get(i).setYValue(temp);
wallIndex++;
}
}
/** Zorg dat de Pivot ook geswitched wordt met de "muur" die
* gemaakt is in de functie hierbijven (zie wallIndex) */
if (wallIndex != b) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(b).getYValue());
list.get(b).setYValue(temp);
}
/** Alle getallen in de Array moeten bij langs zijn gegaan.
* Pas als als A in beide gevallen hieronder groter is dan B, is hij klaar.
*/
quickSort(list, a, wallIndex-1);
quickSort(list, wallIndex+1, b);
}
public void quickSort(List<Data<String, Number>> list, int a, int b, boolean perStapDoen) {
if (a >= b) {
checkEmpty = true;
return;
}
int pivotValue = (int) getValue(list, b);
int wallIndex = a;
for (int i = a; i < b; i++) {
if(getValue(list, i) < pivotValue) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(i).getYValue());
list.get(i).setYValue(temp);
wallIndex++;
}
}
if (wallIndex != b) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(b).getYValue());
list.get(b).setYValue(temp);
}
System.out.println("A is eerst " + a + ", B is eerst " + b + ", En wallindex is eerst: " + wallIndex);
/**
* De HashMap waar A en B worden opgeslagen om de recursie te "simuleren"
*/
myMap = new HashMap<String, Integer>();
myMap.put("A", a);
myMap.put("B", b);
myMap.put("Wallindex", wallIndex);
}
} | HanzehogeschoolSICT/OOP3-JesseTijsma-MarkDissel | Sort.java | 3,249 | /** Alle getallen in de Array moeten bij langs zijn gegaan.
* Pas als als A in beide gevallen hieronder groter is dan B, is hij klaar.
*/ | block_comment | nl | import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.util.*;
import static javafx.scene.chart.XYChart.Data;
import static javafx.scene.chart.XYChart.Series;
public class Sort extends Application {
private Slider slider = new Slider();
public static void main(String[] args) {
launch(args);
}
private static final int
BAR_COUNT = 14,
MAX_BAR_HEIGHT = 50;
private static final String
COLOR_INITIAL = "-fx-bar-fill: #888";
private int pointer = 1;
private int notSwapped = 0;
private int finished = 0;
private ObservableList<Data<String, Number>> bars;
private BarChart<String, Number> chart;
private FlowPane inputs;
//Quicksort Dingen van jesse
private boolean firstLoop = false;
private HashMap<String, Integer> myMap;
private HashMap<String, Integer> emptyMap;
private boolean checkEmpty = false;
@Override
public void start(Stage stage) {
stage.setTitle("Sorting Animations");
stage.setWidth(1024);
stage.setHeight(576);
final BorderPane pane = new BorderPane();
pane.setPadding(new Insets(10));
makeChart(pane);
makeButtons(pane);
stage.setScene(new Scene(pane));
stage.show();
randomizeAll(pane);
}
private void makeChart(BorderPane pane) {
chart = new BarChart<>(new CategoryAxis(), new NumberAxis(0, MAX_BAR_HEIGHT, 0));
chart.setLegendVisible(false);
chart.getYAxis().setTickLabelsVisible(false);
chart.getYAxis().setOpacity(0);
chart.getXAxis().setTickLabelsVisible(false);
chart.getXAxis().setOpacity(0);
chart.setHorizontalGridLinesVisible(false);
chart.setVerticalGridLinesVisible(false);
bars = FXCollections.observableArrayList();
chart.getData().add(new Series<>(bars));
for (int i = 0; i < BAR_COUNT; i++) {
Data<String, Number> dataObject = new Data<>(Integer.toString(i + 1), 1);
bars.add(dataObject); // node will be present after this
addPainting(dataObject.getNode(), COLOR_INITIAL); // do this after bars.add
}
pane.setCenter(chart);
}
private void makeButtons(BorderPane pane) {
inputs = new FlowPane();
inputs.setHgap(5);
inputs.setVgap(5);
createButton("Nieuwe Chart", () -> randomizeAll(pane));
createButton("Bubblesort start", () -> bubbleSort(pane));
createButton("Bubblesort per stap", () -> oneStepBubble(pane));
createButton("Insertionsort start", () -> insertionsort(pane));
createButton("Insertionsort per stap", () -> oneStepInsertion(pane));
createButton("Quicksort start", () -> quicksort(pane));
createButton("Quicksort per stap", () -> oneStepQuick(pane));
makeSlider(50, 500, 250);
pane.setBottom(inputs);
}
private void makeSlider(int min, int max, int standaard) {
slider.setMin(min);
slider.setMax(max);
slider.setValue(standaard);
slider.setMajorTickUnit(standaard-min);
slider.setBlockIncrement(max/10);
slider.setShowTickMarks(true);
slider.setShowTickLabels(true);
inputs.getChildren().add(slider);
}
private void addPainting(Node newNode, String colorInitial) {
if (newNode != null) {
newNode.setStyle(colorInitial);
}
}
private void createButton(String label, Runnable method) {
final Button test = new Button(label);
test.setOnAction(event -> method.run());
inputs.getChildren().add(test);
}
private void randomizeAll(BorderPane pane) {
finished = 0;
pointer = 1;
Random random = new Random();
for (Data<String, Number> bar : bars) {
bar.setYValue(random.nextInt(MAX_BAR_HEIGHT) + 1);
}
}
/**
* Bubble Sort algorithm
*/
private void bubbleSort(BorderPane pane){
List<Data<String, Number>> list = bars;
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
oneStepBubble(pane);
}
}, 0, 550 - (int) slider.getValue());
}
private double getValue(List<Data<String, Number>> list, int index) {
return list.get(index).getYValue().doubleValue();
}
/**
* Bubble Sort one step algorithm
*/
private void oneStepBubble(BorderPane pane) {
if (finished != 1) {
List<Data<String, Number>> list = bars;
double temp;
if (getValue(list, pointer - 1) > getValue(list, pointer)) {
temp = getValue(list, pointer - 1);
list.get(pointer - 1).setYValue(list.get(pointer).getYValue());
list.get(pointer).setYValue(temp);
} else {
notSwapped += 1;
}
if (pointer >= 13) {
pointer = 1;
if (notSwapped >= 13) {
finished = 1;
}
else {
notSwapped = 0;
}
} else {
pointer += 1;
}
}
}
private void insertionsort(BorderPane pane) {
List<Data<String, Number>> list = bars;
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
oneStepInsertion(pane);
}
}, 0, 550 - (int) slider.getValue());
}
private void oneStepInsertion(BorderPane pane) {
if(finished != 1) {
List<Data<String, Number>> list = bars;
int j = pointer;
int temp = (int) getValue(list, pointer);
int newValue = temp;
while (j > 0 && getValue(list, j - 1) > newValue) {
list.get(j).setYValue(getValue(list, j - 1));
j--;
}
list.get(j).setYValue(newValue);
if (pointer >= 13) {
finished = 1;
}
else {
pointer++;
}
}
}
private void quicksort(BorderPane pane) {
List<Data<String, Number>> list = bars;
int a = 0;
int b = list.size() -1;
quickSort(list, a, b);
}
private void oneStepQuick(BorderPane pane) {
List<Data<String, Number>> list = bars;
if (firstLoop == false) {
int a = 0;
int b = list.size() -1;
quickSort(list, a, b, true);
firstLoop = true;
} else {
int a = myMap.get("A");
int b = myMap.get("B");
int wallIndex = myMap.get("Wallindex");
quickSort(list, a, wallIndex-1, true);
quickSort(list, wallIndex+1, b, true);
}
}
public void quickSort(List<Data<String, Number>> list, int a, int b) {
/**
* Kijk of A groter of gelijk is aan B. A begint op 0 (laagste index) en B begint op de hoogste index
* Zie hiervoor ook list.size()-1
*/
if (a >= b) {
return;
}
/** Bepaal de Pivot voor de quicksort */
int pivotValue = (int) getValue(list, b);
int wallIndex = a;
/**
* Is er een waarde groter dan de Pivot? Switch!
* Wanneer een waarde niet groter is dan de pivot, wordt de wall +1 gedaan.
* */
for (int i = a; i < b; i++) {
if(getValue(list, i) < pivotValue) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(i).getYValue());
list.get(i).setYValue(temp);
wallIndex++;
}
}
/** Zorg dat de Pivot ook geswitched wordt met de "muur" die
* gemaakt is in de functie hierbijven (zie wallIndex) */
if (wallIndex != b) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(b).getYValue());
list.get(b).setYValue(temp);
}
/** Alle getallen in<SUF>*/
quickSort(list, a, wallIndex-1);
quickSort(list, wallIndex+1, b);
}
public void quickSort(List<Data<String, Number>> list, int a, int b, boolean perStapDoen) {
if (a >= b) {
checkEmpty = true;
return;
}
int pivotValue = (int) getValue(list, b);
int wallIndex = a;
for (int i = a; i < b; i++) {
if(getValue(list, i) < pivotValue) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(i).getYValue());
list.get(i).setYValue(temp);
wallIndex++;
}
}
if (wallIndex != b) {
int temp = (int) getValue(list, wallIndex);
list.get(wallIndex).setYValue(list.get(b).getYValue());
list.get(b).setYValue(temp);
}
System.out.println("A is eerst " + a + ", B is eerst " + b + ", En wallindex is eerst: " + wallIndex);
/**
* De HashMap waar A en B worden opgeslagen om de recursie te "simuleren"
*/
myMap = new HashMap<String, Integer>();
myMap.put("A", a);
myMap.put("B", b);
myMap.put("Wallindex", wallIndex);
}
} |
24298_5 | import java.util.Stack;
public class QuickSort implements Sorter {
private int[] list;
private int startRange;
private int endRange;
private Stack<Integer> rightRangesStart = new Stack<>();
private Stack<Integer> rightRangesEnd = new Stack<>();
public void setList(int[] list) {
this.list = list;
this.startRange = 0;
this.endRange = list.length-1;
}
private int pivot;
private int dir;
private int index = -1;
private int indexLeft;
private int indexRight;
public boolean startCycle() {
if (index != -1) {
if (index - startRange <= 1) { // Switch naar rechts
if (!rightRangesStart.empty()) {
startRange = rightRangesStart.pop();
endRange = rightRangesEnd.pop();
} else {
return true; // Stop
}
} else { // Switch of blijf links
endRange = index - 1;
}
}
pivot = list[startRange];
dir = -1;
indexLeft = startRange;
indexRight = endRange;
return false; // Doorgaan
}
public boolean runCycle() {
if (indexLeft==indexRight) {
index = indexLeft;
list[index] = pivot;
if (endRange - (index + 1) >= 1) {
rightRangesStart.push(index + 1);
rightRangesEnd.push(endRange);
}
return false;
}
if (dir == 1) { // Van links naar rechts, empty index rechts
if (list[indexLeft] > pivot) {
list[indexRight] = list[indexLeft]; // Value groter dan pivot, verplaatsen naar empty index rechts
indexRight--;
dir = -1;
} else {
indexLeft++;
}
} else { // Van rechts naar links, empty index links
if (list[indexRight] <= pivot) {
list[indexLeft] = list[indexRight]; // Value kleiner dan of gelijk aan pivot, verplaatsen naar empty index links
indexLeft++;
dir = 1;
} else {
indexRight--;
}
}
return true; // Doorgaan
}
public int[] getList() {
return list;
}
}
| HanzehogeschoolSICT/Opdracht1-Sort_ITV2D_Kishan-de-Mul_Elwin-Tamminga | QuickSort.java | 625 | // Value kleiner dan of gelijk aan pivot, verplaatsen naar empty index links | line_comment | nl | import java.util.Stack;
public class QuickSort implements Sorter {
private int[] list;
private int startRange;
private int endRange;
private Stack<Integer> rightRangesStart = new Stack<>();
private Stack<Integer> rightRangesEnd = new Stack<>();
public void setList(int[] list) {
this.list = list;
this.startRange = 0;
this.endRange = list.length-1;
}
private int pivot;
private int dir;
private int index = -1;
private int indexLeft;
private int indexRight;
public boolean startCycle() {
if (index != -1) {
if (index - startRange <= 1) { // Switch naar rechts
if (!rightRangesStart.empty()) {
startRange = rightRangesStart.pop();
endRange = rightRangesEnd.pop();
} else {
return true; // Stop
}
} else { // Switch of blijf links
endRange = index - 1;
}
}
pivot = list[startRange];
dir = -1;
indexLeft = startRange;
indexRight = endRange;
return false; // Doorgaan
}
public boolean runCycle() {
if (indexLeft==indexRight) {
index = indexLeft;
list[index] = pivot;
if (endRange - (index + 1) >= 1) {
rightRangesStart.push(index + 1);
rightRangesEnd.push(endRange);
}
return false;
}
if (dir == 1) { // Van links naar rechts, empty index rechts
if (list[indexLeft] > pivot) {
list[indexRight] = list[indexLeft]; // Value groter dan pivot, verplaatsen naar empty index rechts
indexRight--;
dir = -1;
} else {
indexLeft++;
}
} else { // Van rechts naar links, empty index links
if (list[indexRight] <= pivot) {
list[indexLeft] = list[indexRight]; // Value kleiner<SUF>
indexLeft++;
dir = 1;
} else {
indexRight--;
}
}
return true; // Doorgaan
}
public int[] getList() {
return list;
}
}
|
211664_11 | package model;
import java.util.ArrayList;
public class OthelloBoard implements Cloneable{
ArrayList<OthelloCoordinate> board = new ArrayList<OthelloCoordinate>();
private ArrayList<Integer> possibleMoves = new ArrayList<Integer>();
char ownToken;
public OthelloBoard(char c){
ownToken = c;
reset();
}
OthelloBoard(ArrayList<OthelloCoordinate> board, ArrayList<Integer> possibleMoves, char ownToken) {
this.board = board;
this.possibleMoves = possibleMoves;
this.ownToken = ownToken;
}
@Override
public Object clone() throws CloneNotSupportedException {
ArrayList<OthelloCoordinate> boardclone = new ArrayList<>();
ArrayList<Integer> possibleMovesClone = (ArrayList<Integer>) possibleMoves.clone();
for (OthelloCoordinate coord: board) {
boardclone.add((OthelloCoordinate) coord.clone());
}
return new OthelloBoard(boardclone, possibleMovesClone, ownToken);
}
/**
* Gets the current count of tiles on the board of a specific token
* @param token to count the score of
* @return amount of disks on the board.
*/
public int getCurrentScore(char token){
int count = 0;
for (OthelloCoordinate coord : board) {
if (coord.getToken() == token) {
count++;
}
}
return count;
}
/**
* voegt een coordinaat toe an het bord. Als het coordinaat al in het bord zit,
* dan verandert het het token naar het token van het nieuwe coordinaat.
* Werkt met x en y coordinaten
* @param x X coordinaat van het coordinaat (0-7)
* @param y Y coordinaat van het coordinaat (0-7)
* @param c De kleur van het coordinaat ('W' of 'B')
*/
public void addCoordinate(int x, int y, char c){
if(x >= 0 && x < 8 && y >= 0 && y < 8){ OthelloCoordinate coord = new OthelloCoordinate(x,y);
coord.setToken(c);
if(!board.contains(coord)){
board.add(coord);
} else {
OthelloCoordinate coord2 = getCoordinate(x, y);
coord2.setToken(c);
}
}
}
/**
* voegt een coordinaat toe an het bord. Als het coordinaat al in het bord zit,
* dan verandert het het token naar het token van het nieuwe coordinaat.
* Werkt met index
* @param index Index van het coordinaat (0-63)
* @param c De kleur van het coordinaat ('W' of 'B')
*/
public void addCoordinate(int index, char c){
if(index >= 0 && index <64){
OthelloCoordinate coord = new OthelloCoordinate(index);
coord.setToken(c);
if(!hasCoord(coord)){
board.add(coord);
}else {
OthelloCoordinate coord2 = getCoordinate(index % 8, index / 8);
coord2.setToken(c);
}
}
}
/**
* Returnt een coordinaat op een bepaald punt in het bord.
* @param x X coordinaat van het coordinaat (0-7)
* @param y Y coordinaat van het coordinaat (0-7)
* @return coord het coordinaat (return null als hij niet in het bord zit)
*/
public OthelloCoordinate getCoordinate(int x, int y){
for (OthelloCoordinate coord : board){
if(coord.getX() == x && coord.getY() == y){
return coord;
}
}
return null;
}
/**
* Returnt het bord
* @return board Het bord
*/
public ArrayList<OthelloCoordinate> getBoard(){
return board;
}
/**
* print het bord in een 2 dimensionale overzichtelijke manier
*/
public void printBoard(){
//System.out.println(board);
for(int x = 0; x < 8; x++) {
String line = "";
for(int y = 0; y < 8; y++) {
OthelloCoordinate coord = getCoordinate(x, y);
if(coord == null) {
line+="#";
} else {
line+=coord.getToken();
}
}
System.out.println(line);
}
}
/**
* Reset het bord, voegt de standaard start steentjes toe
*/
public void reset() {
board.clear();
addCoordinate(3,3,'W');
addCoordinate(4,4,'W');
addCoordinate(3,4,'B');
addCoordinate(4,3,'B');
}
/**
* Geeft alle mogelijke moves voor een bepaalde kleur.
* @param token De kleur die de zet gaat maken
* @return possibleMoves Een lijst met mogelijke moves die de kleur token kan maken
*/
public synchronized ArrayList<Integer> findPossibleMoves(char token){
possibleMoves.clear();
for (OthelloCoordinate coord : board){
searchSurroundingCorners(coord, token);
}
return possibleMoves;
}
/**
* Zoekt door alle plekken om een bepaald punt heen om te kijken of het een mogelijke move is.
* voegt alle mogelijke moves die geen duplicates zijn toe aan possibleMoves.
* @param coord Het coordinaat uit het bord waar we recursief omheen gaan zoeken.
* @param token De kleur die de zet gaat maken.
*/
private void searchSurroundingCorners(OthelloCoordinate coord, char token) {
int x = coord.getX();
int y = coord.getY();
OthelloCoordinate newCoord;
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
newCoord = new OthelloCoordinate(x+i,y+j);
if(hasCoord(newCoord)){
newCoord.setToken(getCoordinate(x+i,y+j).getToken());
}
if(isValid(newCoord, token) && !(possibleMoves.contains(newCoord.getIndex()))){
possibleMoves.add(newCoord.getIndex());
}
}
}
}
}
/**
* Geeft aan of een bepaalde move een een toegestane move is. Hiervoor moet het
* coordinaat binnen het bord zitten, nog niet gevuld zijn en een mogelijk pad hebben.
* @param coord Het coordinaat waarvan we kijken of hij toegestaan is
* @param token De kleur die de zet gaat maken.
* @return boolean true als de move toegestaan is, false als de move niet toegestaan is.
*/
public boolean isValid(OthelloCoordinate coord, char token) {
if(!isInBoard(coord)){
return false;
}
if(hasCoord(coord)){
return false;
}
return hasPossiblePath(coord, token);
}
/**
* Kijkt voor een bepaald coordinaat of er een legaal pad is naar andere steentjes.
* @param coord Het coordinaat waarvan we kijken of hij een pad heeft
* @param token De kleur die de zet gaat maken.
* @return boolean true als er minstens ��n pad gevonden is, false als er geen pad te vinden is.
*/
private boolean hasPossiblePath(OthelloCoordinate coord, char token) {
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
if(checkDirection(i,j,coord, 0, token) != -1){
return true;
}
}
}
}
return false;
}
/**
* Kijkt voor een bepaald coordinaat in een bepaalde richting of een pad te vinden is
* @param i De x richting waarheen we gaan zoeken.
* @param j De y richting waarheen we gaan zoeken.
* @param coord Het coordinaat die we nu bekijken
* @param depth De diepte van de recursie. Dit geeft aan hoe ver we al aan het zoeken zijn in een richting.
* @param token De kleur die de zet gaat maken.
* @return depth de diepte van de recursie, dit geeft aan hoe ver we al aan het zoeken zijn in een richting.
* Dit is nuttig om een path te flippen op het bord. Het geeft dus tegelijkertijd aan of de directie toegestaan is en hoe ver het pad uiteindelijk is.
*/
private int checkDirection(int i, int j, OthelloCoordinate coord, int depth, char token) {
OthelloCoordinate newCoord = getCoordinate(coord.getX()+i,coord.getY()+j);
if(newCoord == null){
return -1;
}
if(newCoord.getToken() == token && depth == 0){
return -1;
}
if(newCoord.getToken() == token && depth > 0){
return depth;
}
return checkDirection(i, j, newCoord, depth+1, token);
}
/**
* Kijkt of een bepaald coordinaat in het bord gevuld is.
* @param coordIn Het coordinaat.
* @return boolean true als het coordinaat gevuld is, false als het coordinaat niet gevuld is.
*/
private boolean hasCoord(OthelloCoordinate coordIn) {
return getCoordinate(coordIn.getX(),coordIn.getY()) != null;
}
/**
* Kijkt of een bepaald coordinaat binnen het bord zit.
* @param coord Het coordinaat.
* @return boolean true als het coordinaat binnen het bord zit, fals als het niet binnen het bord zit.
*/
private boolean isInBoard(OthelloCoordinate coord){
int x = coord.getX();
int y = coord.getY();
return ((x>=0 && x < 8) && (y>=0 && y < 8));
}
/**
* Krijgt een move en kleur als input, en gaat dan alle mogelijke paden flippen.
* Dit is het verwerken van een move in het bord.
* @param input De move die verwerkt moet worden
* @param token De kleur van de move die gezet wordt
*/
public void flipPaths(int input, char token) {
int depth;
OthelloCoordinate coord = new OthelloCoordinate(input);
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
depth = getCorrectPathDepth(i,j,coord,token);
if(depth > 0){
flipFoundPath(coord, i,j,depth,token);
}
}
}
}
}
/**
* Er is een pad gevonden en die wordt hier geflipt.
* @param coord het coordinaat die nu geflipt wordt
* @param i De x richting waarheen we bewegen.
* @param j De y richting waarheen we bewegen.
* @param depth de diepte van de recursie van getCorrectPathDepth. Dit is de lengte van het pad
* @param token De kleur van de move die gezet wordt
*/
private void flipFoundPath(OthelloCoordinate coord, int i, int j, int depth, char token) {
OthelloCoordinate newCoord = coord;
for(int n=0; n<=depth;n++){
addCoordinate(newCoord.getIndex(), token);
newCoord = new OthelloCoordinate(newCoord.getX()+i,newCoord.getY()+j);
newCoord.setToken(token);
}
}
/**
* Maakt gebruik van checkdirection om de lengte van het pad te vinden.
* De depth die daar gereturnt wordt geeft aan dat het pad toegestaan is als hij groter dan 0 is.
* Ook geeft het de lengte van het pad aan.
* @param i De x richting waarheen we bewegen.
* @param j De y richting waarheen we bewegen.
* @param coord het coordinaat van de move die gezet wordt
* @param token De kleur van de move die gezet wordt
* @return depth de diepte van het pad (en dus de lengte)
*/
private int getCorrectPathDepth(int i, int j, OthelloCoordinate coord, char token) {
return checkDirection(i,j,coord,0, token);
}
}
| HanzehogeschoolSICT/Project-Othello | src/model/OthelloBoard.java | 3,623 | /**
* Kijkt voor een bepaald coordinaat in een bepaalde richting of een pad te vinden is
* @param i De x richting waarheen we gaan zoeken.
* @param j De y richting waarheen we gaan zoeken.
* @param coord Het coordinaat die we nu bekijken
* @param depth De diepte van de recursie. Dit geeft aan hoe ver we al aan het zoeken zijn in een richting.
* @param token De kleur die de zet gaat maken.
* @return depth de diepte van de recursie, dit geeft aan hoe ver we al aan het zoeken zijn in een richting.
* Dit is nuttig om een path te flippen op het bord. Het geeft dus tegelijkertijd aan of de directie toegestaan is en hoe ver het pad uiteindelijk is.
*/ | block_comment | nl | package model;
import java.util.ArrayList;
public class OthelloBoard implements Cloneable{
ArrayList<OthelloCoordinate> board = new ArrayList<OthelloCoordinate>();
private ArrayList<Integer> possibleMoves = new ArrayList<Integer>();
char ownToken;
public OthelloBoard(char c){
ownToken = c;
reset();
}
OthelloBoard(ArrayList<OthelloCoordinate> board, ArrayList<Integer> possibleMoves, char ownToken) {
this.board = board;
this.possibleMoves = possibleMoves;
this.ownToken = ownToken;
}
@Override
public Object clone() throws CloneNotSupportedException {
ArrayList<OthelloCoordinate> boardclone = new ArrayList<>();
ArrayList<Integer> possibleMovesClone = (ArrayList<Integer>) possibleMoves.clone();
for (OthelloCoordinate coord: board) {
boardclone.add((OthelloCoordinate) coord.clone());
}
return new OthelloBoard(boardclone, possibleMovesClone, ownToken);
}
/**
* Gets the current count of tiles on the board of a specific token
* @param token to count the score of
* @return amount of disks on the board.
*/
public int getCurrentScore(char token){
int count = 0;
for (OthelloCoordinate coord : board) {
if (coord.getToken() == token) {
count++;
}
}
return count;
}
/**
* voegt een coordinaat toe an het bord. Als het coordinaat al in het bord zit,
* dan verandert het het token naar het token van het nieuwe coordinaat.
* Werkt met x en y coordinaten
* @param x X coordinaat van het coordinaat (0-7)
* @param y Y coordinaat van het coordinaat (0-7)
* @param c De kleur van het coordinaat ('W' of 'B')
*/
public void addCoordinate(int x, int y, char c){
if(x >= 0 && x < 8 && y >= 0 && y < 8){ OthelloCoordinate coord = new OthelloCoordinate(x,y);
coord.setToken(c);
if(!board.contains(coord)){
board.add(coord);
} else {
OthelloCoordinate coord2 = getCoordinate(x, y);
coord2.setToken(c);
}
}
}
/**
* voegt een coordinaat toe an het bord. Als het coordinaat al in het bord zit,
* dan verandert het het token naar het token van het nieuwe coordinaat.
* Werkt met index
* @param index Index van het coordinaat (0-63)
* @param c De kleur van het coordinaat ('W' of 'B')
*/
public void addCoordinate(int index, char c){
if(index >= 0 && index <64){
OthelloCoordinate coord = new OthelloCoordinate(index);
coord.setToken(c);
if(!hasCoord(coord)){
board.add(coord);
}else {
OthelloCoordinate coord2 = getCoordinate(index % 8, index / 8);
coord2.setToken(c);
}
}
}
/**
* Returnt een coordinaat op een bepaald punt in het bord.
* @param x X coordinaat van het coordinaat (0-7)
* @param y Y coordinaat van het coordinaat (0-7)
* @return coord het coordinaat (return null als hij niet in het bord zit)
*/
public OthelloCoordinate getCoordinate(int x, int y){
for (OthelloCoordinate coord : board){
if(coord.getX() == x && coord.getY() == y){
return coord;
}
}
return null;
}
/**
* Returnt het bord
* @return board Het bord
*/
public ArrayList<OthelloCoordinate> getBoard(){
return board;
}
/**
* print het bord in een 2 dimensionale overzichtelijke manier
*/
public void printBoard(){
//System.out.println(board);
for(int x = 0; x < 8; x++) {
String line = "";
for(int y = 0; y < 8; y++) {
OthelloCoordinate coord = getCoordinate(x, y);
if(coord == null) {
line+="#";
} else {
line+=coord.getToken();
}
}
System.out.println(line);
}
}
/**
* Reset het bord, voegt de standaard start steentjes toe
*/
public void reset() {
board.clear();
addCoordinate(3,3,'W');
addCoordinate(4,4,'W');
addCoordinate(3,4,'B');
addCoordinate(4,3,'B');
}
/**
* Geeft alle mogelijke moves voor een bepaalde kleur.
* @param token De kleur die de zet gaat maken
* @return possibleMoves Een lijst met mogelijke moves die de kleur token kan maken
*/
public synchronized ArrayList<Integer> findPossibleMoves(char token){
possibleMoves.clear();
for (OthelloCoordinate coord : board){
searchSurroundingCorners(coord, token);
}
return possibleMoves;
}
/**
* Zoekt door alle plekken om een bepaald punt heen om te kijken of het een mogelijke move is.
* voegt alle mogelijke moves die geen duplicates zijn toe aan possibleMoves.
* @param coord Het coordinaat uit het bord waar we recursief omheen gaan zoeken.
* @param token De kleur die de zet gaat maken.
*/
private void searchSurroundingCorners(OthelloCoordinate coord, char token) {
int x = coord.getX();
int y = coord.getY();
OthelloCoordinate newCoord;
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
newCoord = new OthelloCoordinate(x+i,y+j);
if(hasCoord(newCoord)){
newCoord.setToken(getCoordinate(x+i,y+j).getToken());
}
if(isValid(newCoord, token) && !(possibleMoves.contains(newCoord.getIndex()))){
possibleMoves.add(newCoord.getIndex());
}
}
}
}
}
/**
* Geeft aan of een bepaalde move een een toegestane move is. Hiervoor moet het
* coordinaat binnen het bord zitten, nog niet gevuld zijn en een mogelijk pad hebben.
* @param coord Het coordinaat waarvan we kijken of hij toegestaan is
* @param token De kleur die de zet gaat maken.
* @return boolean true als de move toegestaan is, false als de move niet toegestaan is.
*/
public boolean isValid(OthelloCoordinate coord, char token) {
if(!isInBoard(coord)){
return false;
}
if(hasCoord(coord)){
return false;
}
return hasPossiblePath(coord, token);
}
/**
* Kijkt voor een bepaald coordinaat of er een legaal pad is naar andere steentjes.
* @param coord Het coordinaat waarvan we kijken of hij een pad heeft
* @param token De kleur die de zet gaat maken.
* @return boolean true als er minstens ��n pad gevonden is, false als er geen pad te vinden is.
*/
private boolean hasPossiblePath(OthelloCoordinate coord, char token) {
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
if(checkDirection(i,j,coord, 0, token) != -1){
return true;
}
}
}
}
return false;
}
/**
* Kijkt voor een<SUF>*/
private int checkDirection(int i, int j, OthelloCoordinate coord, int depth, char token) {
OthelloCoordinate newCoord = getCoordinate(coord.getX()+i,coord.getY()+j);
if(newCoord == null){
return -1;
}
if(newCoord.getToken() == token && depth == 0){
return -1;
}
if(newCoord.getToken() == token && depth > 0){
return depth;
}
return checkDirection(i, j, newCoord, depth+1, token);
}
/**
* Kijkt of een bepaald coordinaat in het bord gevuld is.
* @param coordIn Het coordinaat.
* @return boolean true als het coordinaat gevuld is, false als het coordinaat niet gevuld is.
*/
private boolean hasCoord(OthelloCoordinate coordIn) {
return getCoordinate(coordIn.getX(),coordIn.getY()) != null;
}
/**
* Kijkt of een bepaald coordinaat binnen het bord zit.
* @param coord Het coordinaat.
* @return boolean true als het coordinaat binnen het bord zit, fals als het niet binnen het bord zit.
*/
private boolean isInBoard(OthelloCoordinate coord){
int x = coord.getX();
int y = coord.getY();
return ((x>=0 && x < 8) && (y>=0 && y < 8));
}
/**
* Krijgt een move en kleur als input, en gaat dan alle mogelijke paden flippen.
* Dit is het verwerken van een move in het bord.
* @param input De move die verwerkt moet worden
* @param token De kleur van de move die gezet wordt
*/
public void flipPaths(int input, char token) {
int depth;
OthelloCoordinate coord = new OthelloCoordinate(input);
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
if(!((i==0) && (j==0))){
depth = getCorrectPathDepth(i,j,coord,token);
if(depth > 0){
flipFoundPath(coord, i,j,depth,token);
}
}
}
}
}
/**
* Er is een pad gevonden en die wordt hier geflipt.
* @param coord het coordinaat die nu geflipt wordt
* @param i De x richting waarheen we bewegen.
* @param j De y richting waarheen we bewegen.
* @param depth de diepte van de recursie van getCorrectPathDepth. Dit is de lengte van het pad
* @param token De kleur van de move die gezet wordt
*/
private void flipFoundPath(OthelloCoordinate coord, int i, int j, int depth, char token) {
OthelloCoordinate newCoord = coord;
for(int n=0; n<=depth;n++){
addCoordinate(newCoord.getIndex(), token);
newCoord = new OthelloCoordinate(newCoord.getX()+i,newCoord.getY()+j);
newCoord.setToken(token);
}
}
/**
* Maakt gebruik van checkdirection om de lengte van het pad te vinden.
* De depth die daar gereturnt wordt geeft aan dat het pad toegestaan is als hij groter dan 0 is.
* Ook geeft het de lengte van het pad aan.
* @param i De x richting waarheen we bewegen.
* @param j De y richting waarheen we bewegen.
* @param coord het coordinaat van de move die gezet wordt
* @param token De kleur van de move die gezet wordt
* @return depth de diepte van het pad (en dus de lengte)
*/
private int getCorrectPathDepth(int i, int j, OthelloCoordinate coord, char token) {
return checkDirection(i,j,coord,0, token);
}
}
|
67402_0 | package hanze.nl.infobord;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class ListenerStarter implements Runnable, ExceptionListener {
//TODO Implementeer de starter voor de messagelistener:
// Zet de verbinding op met de messagebroker en start de listener met
// de juiste selector.
} | HanzehogeschoolSICT/SoftwareQuality | src/hanze/nl/infobord/ListenerStarter.java | 167 | //TODO Implementeer de starter voor de messagelistener: | line_comment | nl | package hanze.nl.infobord;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class ListenerStarter implements Runnable, ExceptionListener {
//TODO Implementeer<SUF>
// Zet de verbinding op met de messagebroker en start de listener met
// de juiste selector.
} |
35126_0 | package main.java.model;
import main.java.util.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BoggleModel extends Model implements ModelController {
private Board board;
private Trie trie;
private WorkerManager workerManager = new WorkerManager();
private Word previousWord;
private Word currentWord;
private ObservableList<Word> wordList = FXCollections.observableArrayList();
public BoggleModel() {
board = new Board(4);
}
public void loadTrie() throws IOException {
trie = new WordlistReader("res/woordenlijst.txt", 3).read();
findWords();
}
public ObservableList<Word> getWordList() {
return wordList;
}
public void setSize(int size) {
if (size > 1) {
board = new Board(size);
findWords();
this.hasChanged = true;
this.updateViews();
}
}
public void setLetters(String letters) {
Board temp = Board.boardFromString(letters);
if (temp != null) {
board = temp;
findWords();
this.hasChanged = true;
this.updateViews();
}
}
private void findWords() {
wordList.clear();
wordList.addAll(workerManager.executeBoard(board));
System.out.println("wordList = " + wordList);
}
public void stopThreads() {
workerManager.stop();
workerManager.awaitTermination();
}
public void updateWord(Word newWord) {
previousWord = currentWord;
currentWord = newWord;
this.updateViews();
}
public Word getPreviousWord() {
return previousWord;
}
public Word getCurrentWord() {
return currentWord;
}
@Override
public char charAt(int x, int y) {
return board.get(x, y).getValue();
}
@Override
public int getSize() {
return board.getSize();
}
/**
* Deze private class is verantwoordelijk voor het parallel zoeken naar woorden.
*/
private class WorkerManager {
private ExecutorService executorService;
private WorkerManager() {
executorService = Executors.newCachedThreadPool();
}
private ArrayList<Word> executeBoard(Board board) {
ArrayList<Callable<ArrayList<Word>>> callables = new ArrayList<>(board.getSize() * board.getSize());
board.getNodes().forEach(bn -> {
if (trie.hasChild(bn.getValue()))
callables.add(() -> new TrieWalker(trie.getChild(bn.getValue()), bn).getWords());
});
ArrayList<Word> returnList = new ArrayList<>();
try {
executorService.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.forEach(returnList::addAll);
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnList;
}
private void stop() {
executorService.shutdownNow();
}
private void awaitTermination() {
try {
executorService.awaitTermination(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| HanzehogeschoolSICT/rutsj-Boggle | src/main/java/model/BoggleModel.java | 1,026 | /**
* Deze private class is verantwoordelijk voor het parallel zoeken naar woorden.
*/ | block_comment | nl | package main.java.model;
import main.java.util.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BoggleModel extends Model implements ModelController {
private Board board;
private Trie trie;
private WorkerManager workerManager = new WorkerManager();
private Word previousWord;
private Word currentWord;
private ObservableList<Word> wordList = FXCollections.observableArrayList();
public BoggleModel() {
board = new Board(4);
}
public void loadTrie() throws IOException {
trie = new WordlistReader("res/woordenlijst.txt", 3).read();
findWords();
}
public ObservableList<Word> getWordList() {
return wordList;
}
public void setSize(int size) {
if (size > 1) {
board = new Board(size);
findWords();
this.hasChanged = true;
this.updateViews();
}
}
public void setLetters(String letters) {
Board temp = Board.boardFromString(letters);
if (temp != null) {
board = temp;
findWords();
this.hasChanged = true;
this.updateViews();
}
}
private void findWords() {
wordList.clear();
wordList.addAll(workerManager.executeBoard(board));
System.out.println("wordList = " + wordList);
}
public void stopThreads() {
workerManager.stop();
workerManager.awaitTermination();
}
public void updateWord(Word newWord) {
previousWord = currentWord;
currentWord = newWord;
this.updateViews();
}
public Word getPreviousWord() {
return previousWord;
}
public Word getCurrentWord() {
return currentWord;
}
@Override
public char charAt(int x, int y) {
return board.get(x, y).getValue();
}
@Override
public int getSize() {
return board.getSize();
}
/**
* Deze private class<SUF>*/
private class WorkerManager {
private ExecutorService executorService;
private WorkerManager() {
executorService = Executors.newCachedThreadPool();
}
private ArrayList<Word> executeBoard(Board board) {
ArrayList<Callable<ArrayList<Word>>> callables = new ArrayList<>(board.getSize() * board.getSize());
board.getNodes().forEach(bn -> {
if (trie.hasChild(bn.getValue()))
callables.add(() -> new TrieWalker(trie.getChild(bn.getValue()), bn).getWords());
});
ArrayList<Word> returnList = new ArrayList<>();
try {
executorService.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.forEach(returnList::addAll);
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnList;
}
private void stop() {
executorService.shutdownNow();
}
private void awaitTermination() {
try {
executorService.awaitTermination(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
97282_19 | package com.destillegast;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.*;
public class Fix extends JavaPlugin implements Listener {
private final HashMap<String, Date> delaymap = new HashMap<>();
private String prefix = ChatColor.DARK_GRAY + "[" + ChatColor.AQUA + "Fix" + ChatColor.DARK_GRAY + "] " + ChatColor.WHITE;
private final NamespacedKey antiRepairKey = new NamespacedKey(this, "denyRepair");
@Override
public void onEnable() {
getConfig().options().copyDefaults(true);
saveDefaultConfig();
getServer().getPluginManager().registerEvents(this, this);
prefix = col(getConfig().getString("prefix", prefix));
getCommand("fix").setExecutor((sender, command, label, args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
if (player.hasPermission("fix.hand")) {
ItemStack item = player.getInventory().getItemInMainHand();
if (item.getType() == Material.AIR) return false;
if (canItemBeRepaired(item)) {
if (item.getItemMeta() instanceof Damageable) {
if (delaymap.containsKey(player.getName())) {
Date d = delaymap.get(player.getName());
long differenceInMillis = Calendar.getInstance().getTime().getTime() - d.getTime();
long differenceInMin = differenceInMillis / 1000L / 60L;
boolean hasUpgrade = player.hasPermission("fix.hand.quicker");
long waitTime = hasUpgrade ? getConfig().getLong("Wait time fast", 30) : getConfig().getLong("Wait time", 60);
if (differenceInMin < waitTime) {
int time = (int) (waitTime - differenceInMin);
player.sendMessage(col(prefix + getConfig().getString("wait").replace("{time}", time + "")));
} else {
delaymap.remove(player.getName());
ItemMeta meta = item.getItemMeta();
((Damageable) meta).setDamage(0);
item.setItemMeta(meta);
player.sendMessage(col(prefix + getConfig().getString("fixed")));
delaymap.put(player.getName(), Calendar.getInstance().getTime());
}
} else {
ItemMeta meta = item.getItemMeta();
((Damageable) meta).setDamage(0);
item.setItemMeta(meta);
player.sendMessage(col(prefix + getConfig().getString("fixed")));
delaymap.put(player.getName(), Calendar.getInstance().getTime());
}
} else {
player.sendMessage(col(prefix + getConfig().getString("mag niet repareren")));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("mag niet repareren")));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
}
} else {
sender.sendMessage("Ingame command only");
}
return true;
});
getCommand("makeunrepairable").setExecutor((sender, command, label, args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
if (player.hasPermission("fix.create")) {
ItemStack item = player.getInventory().getItemInMainHand();
if(item.getItemMeta() != null){
ItemMeta im = item.getItemMeta();
if(im.getPersistentDataContainer().has(antiRepairKey, PersistentDataType.BYTE)){
player.sendMessage(col(prefix + "Item has already been set as unrepairable"));
return true;
}
im.getPersistentDataContainer().set(antiRepairKey, PersistentDataType.BYTE, (byte)1);
if(im instanceof Repairable){
((Repairable) im).setRepairCost(Integer.MAX_VALUE);
}
List<String> currentLore = im.getLore();
if(currentLore == null) currentLore = new ArrayList<>();
currentLore.add(ChatColor.DARK_RED + "Unfixable");
im.setLore(currentLore);
item.setItemMeta(im);
player.sendMessage(col(prefix + "Item has been set as unrepairable"));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
}
} else {
sender.sendMessage("Ingame command only");
}
return false;
});
}
public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("fix")) {
}
// if (cmd.getName().equalsIgnoreCase("setlore")) {
// if (player.getInventory().getItemInMainHand().getType() == Material.AIR) return false;
// if (!player.isOp()) {
// player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
// return false;
// }
//
// if (args.length > 0) {
// String lore = ChatColor.translateAlternateColorCodes('&', args[0]);
// String[] lores = lore.split(",");
// List<String> loresl = new ArrayList<>(Arrays.asList(lores));
// ItemMeta m = player.getInventory().getItemInMainHand().getItemMeta();
// m.setLore(loresl);
// player.getInventory().getItemInMainHand().setItemMeta(m);
// player.sendMessage(col(prefix + "Lore succesful set to '" + lore + "'"));
// } else {
// player.sendMessage(col(prefix + "Voer een lore in"));
// }
// }
}
return false;
}
// @EventHandler
// public void onInventoryClick(InventoryClickEvent event) {
// if (event.getWhoClicked() instanceof Player) {
// if (event.getInventory().getType().equals(InventoryType.ANVIL)) {
// try {
// ItemStack item = event.getCurrentItem();
// if (item != null && item.hasItemMeta()) {
// if (checkLore(item.getItemMeta().getLore())) {
// event.setCancelled(true);
// }
// }
// } catch (Exception ignored) {
//
// }
// }
// }
// }
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player) {
if (event.getInventory().getType().equals(InventoryType.ANVIL)) {
try {
ItemStack item = event.getCurrentItem();
if (!canItemBeRepaired(item)) {
event.setCancelled(true);
}
} catch (Exception ignored) {
}
}
}
}
//heeft het illegale lore ?
private boolean checkLore(List<String> lores) {
if (lores == null) {
return false;
}
for (String lore : lores) {
for (String nolore : getConfig().getStringList("disabled_lores")) {
nolore = col(nolore);
//lore = ChatColor.translateAlternateColorCodes('&', lore);
//lore = ChatColor.stripColor(lore);//ChatColor.translateAlternateColorCodes('&', nolore);
//System.out.pintln(nolore);
if (lore.toLowerCase().contains(nolore.toLowerCase())) {
//System.out.println("found");
return true;
}
}
}
return false;
}
private boolean canItemBeRepaired(ItemStack itemStack) {
if (itemStack == null || itemStack.getItemMeta() == null) return true;
ItemMeta im = itemStack.getItemMeta();
return !im.getPersistentDataContainer().has(antiRepairKey, PersistentDataType.BYTE);
}
private String col(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
} | HappyMine-NL/HappyFix | src/java/com/destillegast/Fix.java | 2,526 | //heeft het illegale lore ? | line_comment | nl | package com.destillegast;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.*;
public class Fix extends JavaPlugin implements Listener {
private final HashMap<String, Date> delaymap = new HashMap<>();
private String prefix = ChatColor.DARK_GRAY + "[" + ChatColor.AQUA + "Fix" + ChatColor.DARK_GRAY + "] " + ChatColor.WHITE;
private final NamespacedKey antiRepairKey = new NamespacedKey(this, "denyRepair");
@Override
public void onEnable() {
getConfig().options().copyDefaults(true);
saveDefaultConfig();
getServer().getPluginManager().registerEvents(this, this);
prefix = col(getConfig().getString("prefix", prefix));
getCommand("fix").setExecutor((sender, command, label, args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
if (player.hasPermission("fix.hand")) {
ItemStack item = player.getInventory().getItemInMainHand();
if (item.getType() == Material.AIR) return false;
if (canItemBeRepaired(item)) {
if (item.getItemMeta() instanceof Damageable) {
if (delaymap.containsKey(player.getName())) {
Date d = delaymap.get(player.getName());
long differenceInMillis = Calendar.getInstance().getTime().getTime() - d.getTime();
long differenceInMin = differenceInMillis / 1000L / 60L;
boolean hasUpgrade = player.hasPermission("fix.hand.quicker");
long waitTime = hasUpgrade ? getConfig().getLong("Wait time fast", 30) : getConfig().getLong("Wait time", 60);
if (differenceInMin < waitTime) {
int time = (int) (waitTime - differenceInMin);
player.sendMessage(col(prefix + getConfig().getString("wait").replace("{time}", time + "")));
} else {
delaymap.remove(player.getName());
ItemMeta meta = item.getItemMeta();
((Damageable) meta).setDamage(0);
item.setItemMeta(meta);
player.sendMessage(col(prefix + getConfig().getString("fixed")));
delaymap.put(player.getName(), Calendar.getInstance().getTime());
}
} else {
ItemMeta meta = item.getItemMeta();
((Damageable) meta).setDamage(0);
item.setItemMeta(meta);
player.sendMessage(col(prefix + getConfig().getString("fixed")));
delaymap.put(player.getName(), Calendar.getInstance().getTime());
}
} else {
player.sendMessage(col(prefix + getConfig().getString("mag niet repareren")));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("mag niet repareren")));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
}
} else {
sender.sendMessage("Ingame command only");
}
return true;
});
getCommand("makeunrepairable").setExecutor((sender, command, label, args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
if (player.hasPermission("fix.create")) {
ItemStack item = player.getInventory().getItemInMainHand();
if(item.getItemMeta() != null){
ItemMeta im = item.getItemMeta();
if(im.getPersistentDataContainer().has(antiRepairKey, PersistentDataType.BYTE)){
player.sendMessage(col(prefix + "Item has already been set as unrepairable"));
return true;
}
im.getPersistentDataContainer().set(antiRepairKey, PersistentDataType.BYTE, (byte)1);
if(im instanceof Repairable){
((Repairable) im).setRepairCost(Integer.MAX_VALUE);
}
List<String> currentLore = im.getLore();
if(currentLore == null) currentLore = new ArrayList<>();
currentLore.add(ChatColor.DARK_RED + "Unfixable");
im.setLore(currentLore);
item.setItemMeta(im);
player.sendMessage(col(prefix + "Item has been set as unrepairable"));
}
} else {
player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
}
} else {
sender.sendMessage("Ingame command only");
}
return false;
});
}
public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("fix")) {
}
// if (cmd.getName().equalsIgnoreCase("setlore")) {
// if (player.getInventory().getItemInMainHand().getType() == Material.AIR) return false;
// if (!player.isOp()) {
// player.sendMessage(col(prefix + getConfig().getString("geen permissie")));
// return false;
// }
//
// if (args.length > 0) {
// String lore = ChatColor.translateAlternateColorCodes('&', args[0]);
// String[] lores = lore.split(",");
// List<String> loresl = new ArrayList<>(Arrays.asList(lores));
// ItemMeta m = player.getInventory().getItemInMainHand().getItemMeta();
// m.setLore(loresl);
// player.getInventory().getItemInMainHand().setItemMeta(m);
// player.sendMessage(col(prefix + "Lore succesful set to '" + lore + "'"));
// } else {
// player.sendMessage(col(prefix + "Voer een lore in"));
// }
// }
}
return false;
}
// @EventHandler
// public void onInventoryClick(InventoryClickEvent event) {
// if (event.getWhoClicked() instanceof Player) {
// if (event.getInventory().getType().equals(InventoryType.ANVIL)) {
// try {
// ItemStack item = event.getCurrentItem();
// if (item != null && item.hasItemMeta()) {
// if (checkLore(item.getItemMeta().getLore())) {
// event.setCancelled(true);
// }
// }
// } catch (Exception ignored) {
//
// }
// }
// }
// }
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player) {
if (event.getInventory().getType().equals(InventoryType.ANVIL)) {
try {
ItemStack item = event.getCurrentItem();
if (!canItemBeRepaired(item)) {
event.setCancelled(true);
}
} catch (Exception ignored) {
}
}
}
}
//heeft het<SUF>
private boolean checkLore(List<String> lores) {
if (lores == null) {
return false;
}
for (String lore : lores) {
for (String nolore : getConfig().getStringList("disabled_lores")) {
nolore = col(nolore);
//lore = ChatColor.translateAlternateColorCodes('&', lore);
//lore = ChatColor.stripColor(lore);//ChatColor.translateAlternateColorCodes('&', nolore);
//System.out.pintln(nolore);
if (lore.toLowerCase().contains(nolore.toLowerCase())) {
//System.out.println("found");
return true;
}
}
}
return false;
}
private boolean canItemBeRepaired(ItemStack itemStack) {
if (itemStack == null || itemStack.getItemMeta() == null) return true;
ItemMeta im = itemStack.getItemMeta();
return !im.getPersistentDataContainer().has(antiRepairKey, PersistentDataType.BYTE);
}
private String col(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
} |
104250_38 | package com.DeStilleGast.Minecraft.HappyMine.VoteShop;
import com.DeStilleGast.Minecraft.HappyMine.VoteShop.sign.CurrencySign;
import com.DeStilleGast.Minecraft.HappyMine.VoteShop.sign.SignShop;
import com.DeStilleGast.Minecraft.HappyMine.database.MySQLConnector;
import com.google.common.base.Joiner;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import xyz.destillegast.dsgutils.DSGUtils;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.stream.Collectors;
/**
* Created by DeStilleGast on 13-11-2016.
*/
public class ShopCore extends JavaPlugin implements Listener, CommandExecutor {
/*
* - ui overhaul (votepoints weergeven in items)
- group/category system
- config uitbreiden per item
│ - feedback (true/false)
│ - showIfPermission (string array)
│ - removeIfPermissions (string array)
└ - group/category
- command om votepoints bij te stellen (add/remove/set)
- placeholder api support (optionele support, niet verplichten)
*/
protected ArrayList<ShopItem> shopItems = new ArrayList<>();
private HashMap<Player, Integer> creator = new HashMap<Player, Integer>();
private HashMap<Player, ArrayList<String>> commandLines = new HashMap<Player, ArrayList<String>>();
private File shopFolder;
private String prefixCreator;
public String prefix;
public String boughtMessage;
protected String poorMessage;
private String noItemMessage;
private String aliasCommand;
private MySQLConnector database;
// public static final String antiTamper = ChatColor.RESET + "-=[VoteShop item]=-";
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("voteshop").setExecutor(this);
if (!this.getDataFolder().exists()) this.getDataFolder().mkdir();
File configFile = new File(this.getDataFolder(), "config.yml");
if (!configFile.exists()) {
saveResource("config.yml", false);
}
try {
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
prefix = ChatColor.translateAlternateColorCodes('&', config.getString("prefix", "&8[&bVote&8]&r")).trim();
prefixCreator = ChatColor.translateAlternateColorCodes('&', config.getString("createPrefix", "&8[&bVote creator&8]&r")).trim();
boughtMessage = ChatColor.translateAlternateColorCodes('&', config.getString("boughtMessage", "You bought {item}&r for &e{price}&r VotePoints!")).trim();
poorMessage = ChatColor.translateAlternateColorCodes('&', config.getString("poorMessage", "You are to poor to buy this item, you have &e{coins}&r VotePoints!")).trim();
noItemMessage = ChatColor.translateAlternateColorCodes('&', config.getString("noItemMessage", "This server doesn't have any items in the VoteShop!")).trim();
aliasCommand = config.getString("aliasCommand", "spawn");
} catch (Exception ex) {
ex.printStackTrace();
}
/* Database */
File databaseConfigFile = new File(this.getDataFolder(), "database.yml");
YamlConfiguration cf;
if (databaseConfigFile.exists()) {
cf = YamlConfiguration.loadConfiguration(databaseConfigFile);
} else {
cf = new YamlConfiguration();
cf.set("host", "");
cf.set("database", "Voteshop");
cf.set("Username", "root");
cf.set("Password", "toor");
try {
cf.save(databaseConfigFile);
} catch (IOException e) {
e.printStackTrace();
}
getLogger().info("Config file created");
}
String mysqlHost = cf.getString("host");
String mysqlDatabase = cf.getString("database", "Voteshop");
String mysqlUser = cf.getString("Username", "root");
String mysqlPass = cf.getString("Password", "toor");
this.database = new MySQLConnector(mysqlHost, mysqlDatabase, mysqlUser, mysqlPass);
if (!this.database.hasConnection()) getLogger().info("No DATABASE");
shopFolder = new File(this.getDataFolder(), "shops");
if (!shopFolder.exists()) shopFolder.mkdirs();
loadShopItems();
Plugin utilPlugin = Bukkit.getPluginManager().getPlugin("DSGUtils");
if(utilPlugin != null){
((DSGUtils)utilPlugin).getSignManager().registerHandler("VoteShop", new SignShop(this));
((DSGUtils)utilPlugin).getSignManager().registerHandler("VotePoints", new CurrencySign(this));
getLogger().info("DSGUtilties has been used");
}
}
public void loadShopItems() {
shopItems.clear();
for (File f : shopFolder.listFiles()) {
this.getLogger().info("Shop item found: " + f.getName());
YamlConfiguration cf = YamlConfiguration.loadConfiguration(f);
//addPerk(cf.getItemStack("Item"), cf.getInt("refillTime", 5));
ItemStack item = cf.getItemStack("Item");
if (item == null) continue;
// shopItems.add(new ShopItem(item, commands, cf.getInt("price", 100000)));
shopItems.add(new ShopItem(item, cf, f.getName()));
this.getLogger().info("Shop item added: " + f.getName());
}
Bukkit.getOnlinePlayers().forEach(p -> {
if(p.getOpenInventory().getTopInventory().getHolder() instanceof ShopUI){
p.closeInventory();
}
});
}
// @EventHandler
// public void onInventoryClick(InventoryClickEvent e) {
// if (e.getInventory().getHolder() != this) return;
//
// Player p = (Player) e.getWhoClicked();
// ItemStack itemStack = e.getCurrentItem();
//
// if (itemStack == null) {
// return;
// }
//
//
// for (ShopItem si : shopItems) {
// ItemStack shopItm = si.getItemStack();
//
// if (itemStack.isSimilar(shopItm)) {
// int myPoints = getCurrency(p);
// if (myPoints >= si.getPrice()) {
// pay(p, si.getPrice());
//
// for (String cmd : si.getCommands()) {
// cmd = cmd.replace("{player}", p.getName());
// getServer().dispatchCommand(getServer().getConsoleSender(), cmd);
// }
//
// String itemName = "no name";
// if (itemStack.hasItemMeta() & itemStack.getItemMeta() != null /* to get rid of annoying build warnings */) {
// if (itemStack.getItemMeta().hasDisplayName()) {
// itemName = itemStack.getItemMeta().getDisplayName();
// } else if (itemStack.getItemMeta().hasLocalizedName()) {
// itemName = itemStack.getItemMeta().getLocalizedName();
// }
// }
//
// p.sendMessage(String.format("%s %s", prefix, boughtMessage.replace("{item}", itemName).replace("{price}", si.getPrice() + "")));
// this.getLogger().info(String.format("%s player %s has bought '%s'", prefix, p.getName(), itemName));
// } else {
// p.sendMessage(prefix + " " + poorMessage.replace("{coins}", myPoints + ""));
// }
// }
// }
// e.setCancelled(true);
// }
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player p = (Player) sender;
if (args.length == 0) {
if (shopItems.size() == 0) {
sender.sendMessage(prefix + " " + noItemMessage);
return true;
} else {
p.performCommand(aliasCommand);
// sender.sendMessage(prefix + " shop command is gesloten, bezoek ons via de fysieke shop");
// Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
// Inventory shopInventory = openShop(p);
//
// Bukkit.getScheduler().runTask(this, () -> p.openInventory(shopInventory));
// });
}
} else if (args[0].equalsIgnoreCase("create") && sender.isOp()) {
sender.sendMessage(prefixCreator + label + " addcommand <command>");
sender.sendMessage(prefixCreator + label + " setname <new name>");
sender.sendMessage(prefixCreator + label + " setlore <command>");
sender.sendMessage(prefixCreator + label + " setprice <price>");
sender.sendMessage(prefixCreator + label + " done");
commandLines.put(p, new ArrayList<String>());
} else if (args[0].equalsIgnoreCase("done") && sender.isOp()) {
try {
File shopFolder = new File(this.getDataFolder(), "shops");
YamlConfiguration test = YamlConfiguration.loadConfiguration(new File(shopFolder, args[1] + ".yml"));
ItemStack newPerk = p.getInventory().getItemInMainHand();
test.set("Item", newPerk);
test.set("price", creator.getOrDefault(p, 10));
test.set("runCommands", commandLines.get(p));
// test.set("showIfAllPermission", new ArrayList<String>());
// test.set("hideIfAnyPermission", new ArrayList<String>());
test.set("enabled", true);
test.save(new File(shopFolder, args[1] + ".yml"));
if (commandLines.containsKey(p)) {
commandLines.remove(p);
}
sender.sendMessage(prefixCreator + " You will need to update the config of " + args[1] + " and after that run '/voteshop reload'");
} catch (IOException e) {
sender.sendMessage(prefixCreator + " Enter name of config");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("setname") && sender.isOp()) {
try {
ItemStack it = p.getInventory().getItemInMainHand();
ItemMeta im = it.getItemMeta();
im.setDisplayName(ChatColor.translateAlternateColorCodes('&', Joiner.on(' ').join(getAllArgs(1, args))));
it.setItemMeta(im);
sender.sendMessage(prefixCreator + "name set to " + it.getItemMeta().getDisplayName());
} catch (Exception e) {
sender.sendMessage(prefixCreator + label + " setname <new name>");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("addcommand") && sender.isOp()) {
try {
if (commandLines.containsKey(p)) {
ArrayList<String> cmds = commandLines.get(p);
cmds.add(Joiner.on(" ").join(getAllArgs(1, args)));
commandLines.put(p, cmds);
for (String s : cmds) {
p.sendMessage(s);
}
}
} catch (Exception e) {
sender.sendMessage(prefixCreator + label + " addcommand <new command>");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("setprice") && sender.isOp()) {
try {
creator.put(p, Integer.parseInt(args[1]));
sender.sendMessage(prefixCreator + "price set to " + creator.get(p));
} catch (Exception ex) {
sender.sendMessage(prefixCreator + label + " setprice <price>");
ex.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("reload") && sender.isOp()) {
this.loadShopItems();
sender.sendMessage(prefixCreator + "reloaded :D");
} else if (args[0].equalsIgnoreCase("take") && sender.hasPermission("voteshop.take")) {
try {
String playerName = args[1];
int amount = Integer.parseInt(args[2]);
Player player = null;
for (Player i : Bukkit.getOnlinePlayers()) {
if (i.getName().equalsIgnoreCase(playerName)) {
player = i;
break;
}
}
if (player == null) {
sender.sendMessage(prefixCreator + " player " + playerName + " doesn't exist!");
return true;
}
if (getCurrency(p) >= amount) {
pay(player, amount);
sender.sendMessage(prefixCreator + " successfully took " + amount + " votepoints from " + playerName);
} else {
sender.sendMessage(prefixCreator + "Player " + amount + " doesn't have enough votepoints!");
}
} catch (Exception ex) {
sender.sendMessage(prefixCreator + " take <player> <amount>");
ex.printStackTrace();
}
}
} else {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
this.loadShopItems();
sender.sendMessage(prefixCreator + "reloaded :D");
} else {
sender.sendMessage(prefixCreator + "onbekende commando");
}
} else {
sender.sendMessage(prefixCreator + " Sadly servers don't have any interfaces to interact with inventories");
}
}
return true;
}
private Inventory openShop(Player p) {
ShopUI newShop = new ShopUI(this, shopItems.stream().filter(ShopItem::isEnabled).map(ShopItem::getItemStack).sorted(Comparator.comparing(ItemStack::getType)).collect(Collectors.toList()), p);
Bukkit.getPluginManager().registerEvents(newShop, this);
return newShop.getInventory();
}
//easy for sub modules too !
public static String[] getAllArgs(Integer offset, String[] arg) {
String[] args = new String[arg.length - offset];
for (Integer i = offset; i < arg.length; i++) {
args[i - offset] = arg[i];
}
return args;
}
public int getCurrency(Player p) {
try {
database.open();
PreparedStatement ps = database.prepareStatement("SELECT `VotePoints` FROM `VoteCurrency` WHERE `UUID`=?");
ps.setString(1, p.getUniqueId().toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt("VotePoints");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (database.hasConnection())
database.close();
}
return 0;
}
public void pay(Player p, int amount) {
try {
database.open();
PreparedStatement ps = database.prepareStatement("UPDATE `VoteCurrency` SET VotePoints=VotePoints-" + amount + " WHERE `UUID`=?");
ps.setString(1, p.getUniqueId().toString());
ps.execute();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (database.hasConnection())
database.close();
}
}
public ArrayList<ShopItem> getShopItems() {
return shopItems;
}
//
// @Override
// public Inventory getInventory() {
// //"[" + this.shopItems.size() + "] Vote shop: ");// + getCurrency(p) + " VotePoints");
//
// return shopInventory;
// }
// @EventHandler(priority = EventPriority.HIGHEST)
// public void onItemGrab(InventoryClickEvent e){
// if(e.getCurrentItem() != null && e.getCurrentItem().hasItemMeta()){
// ItemMeta im = e.getCurrentItem().getItemMeta();
// if(!e.isCancelled()){
// if(im.getLore().contains(antiTamper)){
// e.setCancelled(true);
// }
// }
// }
// }
}
| HappyMine-NL/HappyVoteshop | src/Main/com/DeStilleGast/Minecraft/HappyMine/VoteShop/ShopCore.java | 4,774 | // if(e.getCurrentItem() != null && e.getCurrentItem().hasItemMeta()){ | line_comment | nl | package com.DeStilleGast.Minecraft.HappyMine.VoteShop;
import com.DeStilleGast.Minecraft.HappyMine.VoteShop.sign.CurrencySign;
import com.DeStilleGast.Minecraft.HappyMine.VoteShop.sign.SignShop;
import com.DeStilleGast.Minecraft.HappyMine.database.MySQLConnector;
import com.google.common.base.Joiner;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import xyz.destillegast.dsgutils.DSGUtils;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.stream.Collectors;
/**
* Created by DeStilleGast on 13-11-2016.
*/
public class ShopCore extends JavaPlugin implements Listener, CommandExecutor {
/*
* - ui overhaul (votepoints weergeven in items)
- group/category system
- config uitbreiden per item
│ - feedback (true/false)
│ - showIfPermission (string array)
│ - removeIfPermissions (string array)
└ - group/category
- command om votepoints bij te stellen (add/remove/set)
- placeholder api support (optionele support, niet verplichten)
*/
protected ArrayList<ShopItem> shopItems = new ArrayList<>();
private HashMap<Player, Integer> creator = new HashMap<Player, Integer>();
private HashMap<Player, ArrayList<String>> commandLines = new HashMap<Player, ArrayList<String>>();
private File shopFolder;
private String prefixCreator;
public String prefix;
public String boughtMessage;
protected String poorMessage;
private String noItemMessage;
private String aliasCommand;
private MySQLConnector database;
// public static final String antiTamper = ChatColor.RESET + "-=[VoteShop item]=-";
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("voteshop").setExecutor(this);
if (!this.getDataFolder().exists()) this.getDataFolder().mkdir();
File configFile = new File(this.getDataFolder(), "config.yml");
if (!configFile.exists()) {
saveResource("config.yml", false);
}
try {
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
prefix = ChatColor.translateAlternateColorCodes('&', config.getString("prefix", "&8[&bVote&8]&r")).trim();
prefixCreator = ChatColor.translateAlternateColorCodes('&', config.getString("createPrefix", "&8[&bVote creator&8]&r")).trim();
boughtMessage = ChatColor.translateAlternateColorCodes('&', config.getString("boughtMessage", "You bought {item}&r for &e{price}&r VotePoints!")).trim();
poorMessage = ChatColor.translateAlternateColorCodes('&', config.getString("poorMessage", "You are to poor to buy this item, you have &e{coins}&r VotePoints!")).trim();
noItemMessage = ChatColor.translateAlternateColorCodes('&', config.getString("noItemMessage", "This server doesn't have any items in the VoteShop!")).trim();
aliasCommand = config.getString("aliasCommand", "spawn");
} catch (Exception ex) {
ex.printStackTrace();
}
/* Database */
File databaseConfigFile = new File(this.getDataFolder(), "database.yml");
YamlConfiguration cf;
if (databaseConfigFile.exists()) {
cf = YamlConfiguration.loadConfiguration(databaseConfigFile);
} else {
cf = new YamlConfiguration();
cf.set("host", "");
cf.set("database", "Voteshop");
cf.set("Username", "root");
cf.set("Password", "toor");
try {
cf.save(databaseConfigFile);
} catch (IOException e) {
e.printStackTrace();
}
getLogger().info("Config file created");
}
String mysqlHost = cf.getString("host");
String mysqlDatabase = cf.getString("database", "Voteshop");
String mysqlUser = cf.getString("Username", "root");
String mysqlPass = cf.getString("Password", "toor");
this.database = new MySQLConnector(mysqlHost, mysqlDatabase, mysqlUser, mysqlPass);
if (!this.database.hasConnection()) getLogger().info("No DATABASE");
shopFolder = new File(this.getDataFolder(), "shops");
if (!shopFolder.exists()) shopFolder.mkdirs();
loadShopItems();
Plugin utilPlugin = Bukkit.getPluginManager().getPlugin("DSGUtils");
if(utilPlugin != null){
((DSGUtils)utilPlugin).getSignManager().registerHandler("VoteShop", new SignShop(this));
((DSGUtils)utilPlugin).getSignManager().registerHandler("VotePoints", new CurrencySign(this));
getLogger().info("DSGUtilties has been used");
}
}
public void loadShopItems() {
shopItems.clear();
for (File f : shopFolder.listFiles()) {
this.getLogger().info("Shop item found: " + f.getName());
YamlConfiguration cf = YamlConfiguration.loadConfiguration(f);
//addPerk(cf.getItemStack("Item"), cf.getInt("refillTime", 5));
ItemStack item = cf.getItemStack("Item");
if (item == null) continue;
// shopItems.add(new ShopItem(item, commands, cf.getInt("price", 100000)));
shopItems.add(new ShopItem(item, cf, f.getName()));
this.getLogger().info("Shop item added: " + f.getName());
}
Bukkit.getOnlinePlayers().forEach(p -> {
if(p.getOpenInventory().getTopInventory().getHolder() instanceof ShopUI){
p.closeInventory();
}
});
}
// @EventHandler
// public void onInventoryClick(InventoryClickEvent e) {
// if (e.getInventory().getHolder() != this) return;
//
// Player p = (Player) e.getWhoClicked();
// ItemStack itemStack = e.getCurrentItem();
//
// if (itemStack == null) {
// return;
// }
//
//
// for (ShopItem si : shopItems) {
// ItemStack shopItm = si.getItemStack();
//
// if (itemStack.isSimilar(shopItm)) {
// int myPoints = getCurrency(p);
// if (myPoints >= si.getPrice()) {
// pay(p, si.getPrice());
//
// for (String cmd : si.getCommands()) {
// cmd = cmd.replace("{player}", p.getName());
// getServer().dispatchCommand(getServer().getConsoleSender(), cmd);
// }
//
// String itemName = "no name";
// if (itemStack.hasItemMeta() & itemStack.getItemMeta() != null /* to get rid of annoying build warnings */) {
// if (itemStack.getItemMeta().hasDisplayName()) {
// itemName = itemStack.getItemMeta().getDisplayName();
// } else if (itemStack.getItemMeta().hasLocalizedName()) {
// itemName = itemStack.getItemMeta().getLocalizedName();
// }
// }
//
// p.sendMessage(String.format("%s %s", prefix, boughtMessage.replace("{item}", itemName).replace("{price}", si.getPrice() + "")));
// this.getLogger().info(String.format("%s player %s has bought '%s'", prefix, p.getName(), itemName));
// } else {
// p.sendMessage(prefix + " " + poorMessage.replace("{coins}", myPoints + ""));
// }
// }
// }
// e.setCancelled(true);
// }
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player p = (Player) sender;
if (args.length == 0) {
if (shopItems.size() == 0) {
sender.sendMessage(prefix + " " + noItemMessage);
return true;
} else {
p.performCommand(aliasCommand);
// sender.sendMessage(prefix + " shop command is gesloten, bezoek ons via de fysieke shop");
// Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
// Inventory shopInventory = openShop(p);
//
// Bukkit.getScheduler().runTask(this, () -> p.openInventory(shopInventory));
// });
}
} else if (args[0].equalsIgnoreCase("create") && sender.isOp()) {
sender.sendMessage(prefixCreator + label + " addcommand <command>");
sender.sendMessage(prefixCreator + label + " setname <new name>");
sender.sendMessage(prefixCreator + label + " setlore <command>");
sender.sendMessage(prefixCreator + label + " setprice <price>");
sender.sendMessage(prefixCreator + label + " done");
commandLines.put(p, new ArrayList<String>());
} else if (args[0].equalsIgnoreCase("done") && sender.isOp()) {
try {
File shopFolder = new File(this.getDataFolder(), "shops");
YamlConfiguration test = YamlConfiguration.loadConfiguration(new File(shopFolder, args[1] + ".yml"));
ItemStack newPerk = p.getInventory().getItemInMainHand();
test.set("Item", newPerk);
test.set("price", creator.getOrDefault(p, 10));
test.set("runCommands", commandLines.get(p));
// test.set("showIfAllPermission", new ArrayList<String>());
// test.set("hideIfAnyPermission", new ArrayList<String>());
test.set("enabled", true);
test.save(new File(shopFolder, args[1] + ".yml"));
if (commandLines.containsKey(p)) {
commandLines.remove(p);
}
sender.sendMessage(prefixCreator + " You will need to update the config of " + args[1] + " and after that run '/voteshop reload'");
} catch (IOException e) {
sender.sendMessage(prefixCreator + " Enter name of config");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("setname") && sender.isOp()) {
try {
ItemStack it = p.getInventory().getItemInMainHand();
ItemMeta im = it.getItemMeta();
im.setDisplayName(ChatColor.translateAlternateColorCodes('&', Joiner.on(' ').join(getAllArgs(1, args))));
it.setItemMeta(im);
sender.sendMessage(prefixCreator + "name set to " + it.getItemMeta().getDisplayName());
} catch (Exception e) {
sender.sendMessage(prefixCreator + label + " setname <new name>");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("addcommand") && sender.isOp()) {
try {
if (commandLines.containsKey(p)) {
ArrayList<String> cmds = commandLines.get(p);
cmds.add(Joiner.on(" ").join(getAllArgs(1, args)));
commandLines.put(p, cmds);
for (String s : cmds) {
p.sendMessage(s);
}
}
} catch (Exception e) {
sender.sendMessage(prefixCreator + label + " addcommand <new command>");
e.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("setprice") && sender.isOp()) {
try {
creator.put(p, Integer.parseInt(args[1]));
sender.sendMessage(prefixCreator + "price set to " + creator.get(p));
} catch (Exception ex) {
sender.sendMessage(prefixCreator + label + " setprice <price>");
ex.printStackTrace();
}
} else if (args[0].equalsIgnoreCase("reload") && sender.isOp()) {
this.loadShopItems();
sender.sendMessage(prefixCreator + "reloaded :D");
} else if (args[0].equalsIgnoreCase("take") && sender.hasPermission("voteshop.take")) {
try {
String playerName = args[1];
int amount = Integer.parseInt(args[2]);
Player player = null;
for (Player i : Bukkit.getOnlinePlayers()) {
if (i.getName().equalsIgnoreCase(playerName)) {
player = i;
break;
}
}
if (player == null) {
sender.sendMessage(prefixCreator + " player " + playerName + " doesn't exist!");
return true;
}
if (getCurrency(p) >= amount) {
pay(player, amount);
sender.sendMessage(prefixCreator + " successfully took " + amount + " votepoints from " + playerName);
} else {
sender.sendMessage(prefixCreator + "Player " + amount + " doesn't have enough votepoints!");
}
} catch (Exception ex) {
sender.sendMessage(prefixCreator + " take <player> <amount>");
ex.printStackTrace();
}
}
} else {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
this.loadShopItems();
sender.sendMessage(prefixCreator + "reloaded :D");
} else {
sender.sendMessage(prefixCreator + "onbekende commando");
}
} else {
sender.sendMessage(prefixCreator + " Sadly servers don't have any interfaces to interact with inventories");
}
}
return true;
}
private Inventory openShop(Player p) {
ShopUI newShop = new ShopUI(this, shopItems.stream().filter(ShopItem::isEnabled).map(ShopItem::getItemStack).sorted(Comparator.comparing(ItemStack::getType)).collect(Collectors.toList()), p);
Bukkit.getPluginManager().registerEvents(newShop, this);
return newShop.getInventory();
}
//easy for sub modules too !
public static String[] getAllArgs(Integer offset, String[] arg) {
String[] args = new String[arg.length - offset];
for (Integer i = offset; i < arg.length; i++) {
args[i - offset] = arg[i];
}
return args;
}
public int getCurrency(Player p) {
try {
database.open();
PreparedStatement ps = database.prepareStatement("SELECT `VotePoints` FROM `VoteCurrency` WHERE `UUID`=?");
ps.setString(1, p.getUniqueId().toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt("VotePoints");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (database.hasConnection())
database.close();
}
return 0;
}
public void pay(Player p, int amount) {
try {
database.open();
PreparedStatement ps = database.prepareStatement("UPDATE `VoteCurrency` SET VotePoints=VotePoints-" + amount + " WHERE `UUID`=?");
ps.setString(1, p.getUniqueId().toString());
ps.execute();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (database.hasConnection())
database.close();
}
}
public ArrayList<ShopItem> getShopItems() {
return shopItems;
}
//
// @Override
// public Inventory getInventory() {
// //"[" + this.shopItems.size() + "] Vote shop: ");// + getCurrency(p) + " VotePoints");
//
// return shopInventory;
// }
// @EventHandler(priority = EventPriority.HIGHEST)
// public void onItemGrab(InventoryClickEvent e){
// if(e.getCurrentItem() !=<SUF>
// ItemMeta im = e.getCurrentItem().getItemMeta();
// if(!e.isCancelled()){
// if(im.getLore().contains(antiTamper)){
// e.setCancelled(true);
// }
// }
// }
// }
}
|
122922_7 | package nl.happymine;
import java.sql.*;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by DeStilleGast on 11-9-2016.
*/
public class Connector {
private Logger logger;
private final String host, database, user, password;
private Connection con;
public Connector(Logger logger, String host, String database, String user, String password) {
this.logger = logger;
this.host = host;
this.database = database;
this.user = user;
this.password = password;
}
public void open() {
try {
// logger.info("Atempting to login to database");
con = DriverManager.getConnection("jdbc:mysql://" + host + ":3306/" + database + "?autoReconnect=true&serverTimezone=" + TimeZone.getDefault().getID(),
user, password);
// System.out.println(ZoneId.systemDefault().toString());
// logger.log(Level.INFO, "[MySQL] The connection to MySQL is made!");
} catch (SQLException e) {
logger.log(Level.INFO, "[MySQL] The connection to MySQL couldn't be made! reason: " + e.getMessage() + ", Caused by " + e.getCause().getMessage());
}
}
public void close() {
try {
if (con != null) {
con.close();
// logger.log(Level.INFO, "[MySQL] The connection to MySQL is ended successfully!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Request a prepare statement with the given query
*
* @param qry Query
* @return PreparedStatedment with given query
*/
public PreparedStatement prepareStatement(String qry) throws SQLException {
return con.prepareStatement(qry);
}
/**
* Execute a update/insert statement
*
* @param statement PrepareStatement with Update/Insert statement
*/
public int update(PreparedStatement statement) throws SQLException {
try {
return statement.executeUpdate();
} catch (SQLException e) {
open();
e.printStackTrace();
throw e; // ook al wordt het hier opgevangen, het dingetje is, we kunnen anders niet zien of het gelukt of gefaald heeft
} finally {
statement.close();
}
}
/**
* Check if there is a connection to the MySQL server
*
* @return true if there is a connection
*/
public boolean hasConnection() {
return con != null;
}
/**
* Execute SELECT statement
*
* @param statement PrepareStatement with SELECT query
* @return ResultSet from given PrepareStatement/query
*/
public ResultSet query(PreparedStatement statement) throws SQLException {
return statement.executeQuery();
}
public void createTable(String tb) {
try {
open();
update(prepareStatement("CREATE TABLE IF NOT EXISTS " + tb));
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
close();
}
}
}
| HappyMine-NL/TogglePvP | src/main/java/nl/happymine/Connector.java | 864 | // ook al wordt het hier opgevangen, het dingetje is, we kunnen anders niet zien of het gelukt of gefaald heeft | line_comment | nl | package nl.happymine;
import java.sql.*;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by DeStilleGast on 11-9-2016.
*/
public class Connector {
private Logger logger;
private final String host, database, user, password;
private Connection con;
public Connector(Logger logger, String host, String database, String user, String password) {
this.logger = logger;
this.host = host;
this.database = database;
this.user = user;
this.password = password;
}
public void open() {
try {
// logger.info("Atempting to login to database");
con = DriverManager.getConnection("jdbc:mysql://" + host + ":3306/" + database + "?autoReconnect=true&serverTimezone=" + TimeZone.getDefault().getID(),
user, password);
// System.out.println(ZoneId.systemDefault().toString());
// logger.log(Level.INFO, "[MySQL] The connection to MySQL is made!");
} catch (SQLException e) {
logger.log(Level.INFO, "[MySQL] The connection to MySQL couldn't be made! reason: " + e.getMessage() + ", Caused by " + e.getCause().getMessage());
}
}
public void close() {
try {
if (con != null) {
con.close();
// logger.log(Level.INFO, "[MySQL] The connection to MySQL is ended successfully!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Request a prepare statement with the given query
*
* @param qry Query
* @return PreparedStatedment with given query
*/
public PreparedStatement prepareStatement(String qry) throws SQLException {
return con.prepareStatement(qry);
}
/**
* Execute a update/insert statement
*
* @param statement PrepareStatement with Update/Insert statement
*/
public int update(PreparedStatement statement) throws SQLException {
try {
return statement.executeUpdate();
} catch (SQLException e) {
open();
e.printStackTrace();
throw e; // ook al<SUF>
} finally {
statement.close();
}
}
/**
* Check if there is a connection to the MySQL server
*
* @return true if there is a connection
*/
public boolean hasConnection() {
return con != null;
}
/**
* Execute SELECT statement
*
* @param statement PrepareStatement with SELECT query
* @return ResultSet from given PrepareStatement/query
*/
public ResultSet query(PreparedStatement statement) throws SQLException {
return statement.executeQuery();
}
public void createTable(String tb) {
try {
open();
update(prepareStatement("CREATE TABLE IF NOT EXISTS " + tb));
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
close();
}
}
}
|
23328_2 | package Enigma_machine;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class TDD {
private Enigma_Machine enigma;
@Before
public void set_up_machine(){ // vanaf test_1
enigma = new Enigma_Machine();
enigma.setup_rotor_blok("123", "MCK");
}
@Test
public void test_0(){ // Eerst maar eens een rotor laten draaien
Rotor rotor = new Rotor();
assertEquals(rotor.get_window_position(),0);
rotor.rotate_rotor();
assertEquals(rotor.get_window_position(),1);
for (int i = 2; i<26; i++){ // Een rondje draaien
rotor.rotate_rotor();
assertEquals(rotor.get_window_position(),i);
}
rotor.rotate_rotor(); // Helemaal rond
assertEquals(rotor.get_window_position(),0);
}
@Test
public void test_1() { // Drie rotoren in een doosje plaatsen en met elkaar laten draaien
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// Ga uit van de setup I-II-III en codering MCK
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),10);
enigma.rotor_blok[2].rotate_rotor();; // Alleen rotor 2 draait
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),11);
for (int i = 12; i < 22; i++){ // Rotor 2 tot aan het rollover punt draaien
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),i);
}
enigma.rotor_blok[2].rotate_rotor(); // Rollover op rotor 1
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),3);
assertEquals(enigma.rotor_blok[2].get_window_position(),22);
for (int i = 23; i < 27; i++) // rotor 2 tot aan de laatste positie + 1 draaien
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),3);
assertEquals(enigma.rotor_blok[2].get_window_position(),0);
for (int i = 0; i < 52; i++) // rollover op rotor 0 (en dus twee keer op rotor 1)
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),13);
assertEquals(enigma.rotor_blok[1].get_window_position(),5);
assertEquals(enigma.rotor_blok[2].get_window_position(),0);
}
@Test
public void test_2(){ // Een rotor laten coderen, maak gebruik van rotor_III met de 'K' in het window
assertEquals(enigma.rotor_blok[2].encode_right_left(5),20); // positie 5 rechts is 'E', 'E' in de linkerkolom staat op pos 20
assertEquals(enigma.rotor_blok[2].encode_left_right(14),4); // positie 14 links is 'Y', rechts staat die op de positie 4
enigma.rotor_blok[2].rotate_rotor(); // Draai de rotor een slag, 'L' staat nu in het window (=positie 0)
assertEquals(enigma.rotor_blok[2].encode_right_left(5),23); // positie 5 rechts is nu 'I', 'I' in de linkerkolom staat nu op pos 23
assertEquals(enigma.rotor_blok[2].encode_left_right(14),1); // positie 14 links is 'Z', rechts staat die op de positie 1
}
@Test
public void test_3() { // Een reflector maken
Reflector reflector = new Reflector();
assertEquals(reflector.reflector_result(4),16);
assertEquals(reflector.reflector_result(16),4);
}
@Test
public void test_4() { // Volledige codering van een letter
assertEquals(enigma.encode('E'),'Q'); // Controleer de output
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// en de rotor zetting
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),11);
assertEquals(enigma.encode('N'),'M'); // Volgende letter
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// Rotor moet weer gedraaid zijn
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),12);
}
@Test
public void test_5(){ // Een string coderen
assertEquals(enigma.string_encode("ENIGMA REVEALED"),"QMJIDO MZWZJFJR");
}
}
| HaraldRietdijk/Enigma | Enigma/src/Enigma_machine/TDD.java | 1,674 | // Drie rotoren in een doosje plaatsen en met elkaar laten draaien
| line_comment | nl | package Enigma_machine;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class TDD {
private Enigma_Machine enigma;
@Before
public void set_up_machine(){ // vanaf test_1
enigma = new Enigma_Machine();
enigma.setup_rotor_blok("123", "MCK");
}
@Test
public void test_0(){ // Eerst maar eens een rotor laten draaien
Rotor rotor = new Rotor();
assertEquals(rotor.get_window_position(),0);
rotor.rotate_rotor();
assertEquals(rotor.get_window_position(),1);
for (int i = 2; i<26; i++){ // Een rondje draaien
rotor.rotate_rotor();
assertEquals(rotor.get_window_position(),i);
}
rotor.rotate_rotor(); // Helemaal rond
assertEquals(rotor.get_window_position(),0);
}
@Test
public void test_1() { // Drie rotoren<SUF>
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// Ga uit van de setup I-II-III en codering MCK
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),10);
enigma.rotor_blok[2].rotate_rotor();; // Alleen rotor 2 draait
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),11);
for (int i = 12; i < 22; i++){ // Rotor 2 tot aan het rollover punt draaien
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),i);
}
enigma.rotor_blok[2].rotate_rotor(); // Rollover op rotor 1
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),3);
assertEquals(enigma.rotor_blok[2].get_window_position(),22);
for (int i = 23; i < 27; i++) // rotor 2 tot aan de laatste positie + 1 draaien
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),12);
assertEquals(enigma.rotor_blok[1].get_window_position(),3);
assertEquals(enigma.rotor_blok[2].get_window_position(),0);
for (int i = 0; i < 52; i++) // rollover op rotor 0 (en dus twee keer op rotor 1)
enigma.rotor_blok[2].rotate_rotor();
assertEquals(enigma.rotor_blok[0].get_window_position(),13);
assertEquals(enigma.rotor_blok[1].get_window_position(),5);
assertEquals(enigma.rotor_blok[2].get_window_position(),0);
}
@Test
public void test_2(){ // Een rotor laten coderen, maak gebruik van rotor_III met de 'K' in het window
assertEquals(enigma.rotor_blok[2].encode_right_left(5),20); // positie 5 rechts is 'E', 'E' in de linkerkolom staat op pos 20
assertEquals(enigma.rotor_blok[2].encode_left_right(14),4); // positie 14 links is 'Y', rechts staat die op de positie 4
enigma.rotor_blok[2].rotate_rotor(); // Draai de rotor een slag, 'L' staat nu in het window (=positie 0)
assertEquals(enigma.rotor_blok[2].encode_right_left(5),23); // positie 5 rechts is nu 'I', 'I' in de linkerkolom staat nu op pos 23
assertEquals(enigma.rotor_blok[2].encode_left_right(14),1); // positie 14 links is 'Z', rechts staat die op de positie 1
}
@Test
public void test_3() { // Een reflector maken
Reflector reflector = new Reflector();
assertEquals(reflector.reflector_result(4),16);
assertEquals(reflector.reflector_result(16),4);
}
@Test
public void test_4() { // Volledige codering van een letter
assertEquals(enigma.encode('E'),'Q'); // Controleer de output
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// en de rotor zetting
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),11);
assertEquals(enigma.encode('N'),'M'); // Volgende letter
assertEquals(enigma.rotor_blok[0].get_window_position(),12);// Rotor moet weer gedraaid zijn
assertEquals(enigma.rotor_blok[1].get_window_position(),2);
assertEquals(enigma.rotor_blok[2].get_window_position(),12);
}
@Test
public void test_5(){ // Een string coderen
assertEquals(enigma.string_encode("ENIGMA REVEALED"),"QMJIDO MZWZJFJR");
}
}
|
78570_9 | package com.jagrosh.jmusicbot.MongoDB;
import com.jagrosh.jmusicbot.JMusicBot;
import com.jagrosh.jmusicbot.utils.TemperatureInstance;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoTemperatureInstance extends Mongo {
private final List<TemperatureInstance> temperatureInstrances;
public MongoTemperatureInstance() {
temperatureInstrances = new ArrayList<TemperatureInstance>();
connect();
load();
}
// connect database
private void connect() {
// Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over
if (JMusicBot.getNosqlHost().equals("")) {
System.out.println("The connection string is null!!!!");
return;
}
// Verbind alleen als er nog geen actieve verbinding is.
if (this.mongoClient == null) {
try {
// Open pijpleiding
this.mongoClient = MongoClients.create(JMusicBot.getNosqlHost());
// Selecteer de juiste database
this.mongoDatabase = mongoClient.getDatabase(JMusicBot.getNosqlDatabase());
} catch (MongoException e) {
e.printStackTrace();
}
}
}
public void load() {
// Als je geen NoSQL server hebt opgegeven gaat de methode niet verder anders zou je een nullpointer krijgen
if (JMusicBot.getNosqlHost().equals(""))
return;
// Selecteer de juiste collecton in de NoSQL server
this.selectedCollection("weatherInstance");
// Haal alles op uit deze collection en loop er 1 voor 1 doorheen
MongoCursor<Document> cursor = collection.find().iterator();
try {
// Zolang er data is
while (cursor.hasNext()) {
// warning Java is case sensitive
// Haal alle velden per record
Document tempReiziger = cursor.next();
String location = (String) tempReiziger.get("location");
String time = (String) tempReiziger.get("time");
double temperature = Double.valueOf(tempReiziger.get("temperature").toString());
String winddirection = (String) tempReiziger.get("winddirection");
String alarmtext = (String) tempReiziger.get("alarmtext");
String expectedWeather = (String) tempReiziger.get("alarmtext");
String kindOfWeather = (String) tempReiziger.get("kindOfWeather");
// Maak een nieuw object en voeg deze toe aan de arraylist
temperatureInstrances.add(new TemperatureInstance(location,time,temperature,winddirection,alarmtext,expectedWeather, kindOfWeather));
}
} finally {
// Sluit de stream
cursor.close();
}
}
public void add(Object object) {
try {
if (object instanceof TemperatureInstance){
Document document = new Document("location", ((TemperatureInstance) object).getLocation()).append("time", ((TemperatureInstance) object).getTime())
.append("temperature", ((TemperatureInstance) object).getTemperature()).append("winddirection", ((TemperatureInstance) object).getWinddirection()).append("alarmtext", ((TemperatureInstance) object).getAlarmtext())
.append("expectedWeather", ((TemperatureInstance) object).getExpectedWeather()).append("kindOfWeather", ((TemperatureInstance) object).getKindOfWeather());
collection.insertOne(document);
}
}
catch (Exception e){
System.out.println("Shit, that conversion didn't go as planned. " + e);
}
}
}
| HarisSgouridis/FabBot | src/main/java/com/jagrosh/jmusicbot/MongoDB/MongoTemperatureInstance.java | 1,038 | // Maak een nieuw object en voeg deze toe aan de arraylist | line_comment | nl | package com.jagrosh.jmusicbot.MongoDB;
import com.jagrosh.jmusicbot.JMusicBot;
import com.jagrosh.jmusicbot.utils.TemperatureInstance;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoTemperatureInstance extends Mongo {
private final List<TemperatureInstance> temperatureInstrances;
public MongoTemperatureInstance() {
temperatureInstrances = new ArrayList<TemperatureInstance>();
connect();
load();
}
// connect database
private void connect() {
// Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over
if (JMusicBot.getNosqlHost().equals("")) {
System.out.println("The connection string is null!!!!");
return;
}
// Verbind alleen als er nog geen actieve verbinding is.
if (this.mongoClient == null) {
try {
// Open pijpleiding
this.mongoClient = MongoClients.create(JMusicBot.getNosqlHost());
// Selecteer de juiste database
this.mongoDatabase = mongoClient.getDatabase(JMusicBot.getNosqlDatabase());
} catch (MongoException e) {
e.printStackTrace();
}
}
}
public void load() {
// Als je geen NoSQL server hebt opgegeven gaat de methode niet verder anders zou je een nullpointer krijgen
if (JMusicBot.getNosqlHost().equals(""))
return;
// Selecteer de juiste collecton in de NoSQL server
this.selectedCollection("weatherInstance");
// Haal alles op uit deze collection en loop er 1 voor 1 doorheen
MongoCursor<Document> cursor = collection.find().iterator();
try {
// Zolang er data is
while (cursor.hasNext()) {
// warning Java is case sensitive
// Haal alle velden per record
Document tempReiziger = cursor.next();
String location = (String) tempReiziger.get("location");
String time = (String) tempReiziger.get("time");
double temperature = Double.valueOf(tempReiziger.get("temperature").toString());
String winddirection = (String) tempReiziger.get("winddirection");
String alarmtext = (String) tempReiziger.get("alarmtext");
String expectedWeather = (String) tempReiziger.get("alarmtext");
String kindOfWeather = (String) tempReiziger.get("kindOfWeather");
// Maak een<SUF>
temperatureInstrances.add(new TemperatureInstance(location,time,temperature,winddirection,alarmtext,expectedWeather, kindOfWeather));
}
} finally {
// Sluit de stream
cursor.close();
}
}
public void add(Object object) {
try {
if (object instanceof TemperatureInstance){
Document document = new Document("location", ((TemperatureInstance) object).getLocation()).append("time", ((TemperatureInstance) object).getTime())
.append("temperature", ((TemperatureInstance) object).getTemperature()).append("winddirection", ((TemperatureInstance) object).getWinddirection()).append("alarmtext", ((TemperatureInstance) object).getAlarmtext())
.append("expectedWeather", ((TemperatureInstance) object).getExpectedWeather()).append("kindOfWeather", ((TemperatureInstance) object).getKindOfWeather());
collection.insertOne(document);
}
}
catch (Exception e){
System.out.println("Shit, that conversion didn't go as planned. " + e);
}
}
}
|
131181_0 | /*********************************
* H.R. Oosterhuis - 10196129
* Kunstmatige Intelligentie
* Datastructuren 2012-2013
* Project Opdracht
*********************************/
public abstract class PuzzleSolver {
/*
* if set to true, information about search tree and hash table
* used to solve the puzzle will be displayed
*/
public static boolean hashInfo = false ;
/* solves the puzzle using A*
* the algorithm is hardwired to discarded any boards
* it has reached before with a lower cost
*
* returns a stack containing the solution moves in order
*/
public static MoveStack solve( Board board ){
//NodeQueue is a priority queue it orders the nodes on expected cost
// queue is set to ascending meaning the lowest expected cost
// is returned first
NodeQueue newNodes, queue = new NodeQueue(500, true);
Node node = new Node(board);
BoardHashTable table = new BoardHashTable(1000);
//nodes considered holds the total of new nodes created
int nodesConsidered = 0;
// the first node is added to the table and queue
table.put(board, 0);
queue.push(node);
nodesConsidered++;
while(!queue.isEmpty() && !queue.peek().board().won()){
// since the queue is ordered on expected cost
// the popped node has the smallest expected cost
node = queue.pop();
newNodes = node.expandNode();
while(!newNodes.isEmpty()){
nodesConsidered++;
node = newNodes.pop();
//the node is only added to the open nodes
//if it is the first node containing that board
//or it has a lower cost than the last time the board was considered
if(table.put(node.board(), node.getCost())){
queue.push(node);
}
}
}
if( hashInfo ){
System.out.printf("Considered: %d Relevant: %d Abandoned: %d Closed: %d. ",
nodesConsidered,table.size(),(nodesConsidered - table.size()),queue.size());
}
// the moveStack will hold the solution
// given by the node with the smallest path to the winning state
MoveStack stack = null ;
if(queue != null && !queue.isEmpty()){
stack = queue.peek().getPath();
}
// if the puzzle is solved or unsolvable an empty
// stack is returned
if( stack == null ){
stack = new MoveStack(1);
}
return stack ;
}
}
| HarrieO/RushHourSolver | src/PuzzleSolver.java | 676 | /*********************************
* H.R. Oosterhuis - 10196129
* Kunstmatige Intelligentie
* Datastructuren 2012-2013
* Project Opdracht
*********************************/ | block_comment | nl | /*********************************
* H.R. Oosterhuis -<SUF>*/
public abstract class PuzzleSolver {
/*
* if set to true, information about search tree and hash table
* used to solve the puzzle will be displayed
*/
public static boolean hashInfo = false ;
/* solves the puzzle using A*
* the algorithm is hardwired to discarded any boards
* it has reached before with a lower cost
*
* returns a stack containing the solution moves in order
*/
public static MoveStack solve( Board board ){
//NodeQueue is a priority queue it orders the nodes on expected cost
// queue is set to ascending meaning the lowest expected cost
// is returned first
NodeQueue newNodes, queue = new NodeQueue(500, true);
Node node = new Node(board);
BoardHashTable table = new BoardHashTable(1000);
//nodes considered holds the total of new nodes created
int nodesConsidered = 0;
// the first node is added to the table and queue
table.put(board, 0);
queue.push(node);
nodesConsidered++;
while(!queue.isEmpty() && !queue.peek().board().won()){
// since the queue is ordered on expected cost
// the popped node has the smallest expected cost
node = queue.pop();
newNodes = node.expandNode();
while(!newNodes.isEmpty()){
nodesConsidered++;
node = newNodes.pop();
//the node is only added to the open nodes
//if it is the first node containing that board
//or it has a lower cost than the last time the board was considered
if(table.put(node.board(), node.getCost())){
queue.push(node);
}
}
}
if( hashInfo ){
System.out.printf("Considered: %d Relevant: %d Abandoned: %d Closed: %d. ",
nodesConsidered,table.size(),(nodesConsidered - table.size()),queue.size());
}
// the moveStack will hold the solution
// given by the node with the smallest path to the winning state
MoveStack stack = null ;
if(queue != null && !queue.isEmpty()){
stack = queue.peek().getPath();
}
// if the puzzle is solved or unsolvable an empty
// stack is returned
if( stack == null ){
stack = new MoveStack(1);
}
return stack ;
}
}
|
64042_5 | package controller;
import model.Kofferslot;
public class KofferslotLauncher {
public static void main(String[] args) {
// Test of de default constructor van de klasse Kofferslot werkt.
Kofferslot slot1 = new Kofferslot();
System.out.println("Default constructor: " + slot1); // Verwacht: AA0
// Test of de all-args constructor van de klasse Kofferslot werkt.
Kofferslot slot2 = new Kofferslot('B', 'R', 9);
System.out.println("All-args constructor: " + slot2); // Verwacht: BR9
// Test of de methode volgende() van de klasse Kofferslot correct werkt.
// AA0 volgende moet zijn: AA1
Kofferslot slot3 = new Kofferslot('A', 'A', 0);
slot3.volgende();
System.out.println("Van AA0 naar: " + slot3); // Verwacht: AA1
// BR9 volgende moet zijn: BS0
Kofferslot slot4 = new Kofferslot('B', 'R', 9);
slot4.volgende();
System.out.println("Van BR9 naar: " + slot4); // Verwacht: BS0
// DZ9 volgende moet zijn: EA0
Kofferslot slot5 = new Kofferslot('D', 'Z', 9);
slot5.volgende();
System.out.println("Van DZ9 naar: " + slot5); // Verwacht: EA0
// ZZ9 volgende moet zijn: AA0
Kofferslot slot6 = new Kofferslot('Z', 'Z', 9);
slot6.volgende();
System.out.println("Van ZZ9 naar: " + slot6); // Verwacht: AA0
}
} | Hayac1113/PracticeObjectOrientedProgramming | src/controller/KofferslotLauncher.java | 466 | // DZ9 volgende moet zijn: EA0 | line_comment | nl | package controller;
import model.Kofferslot;
public class KofferslotLauncher {
public static void main(String[] args) {
// Test of de default constructor van de klasse Kofferslot werkt.
Kofferslot slot1 = new Kofferslot();
System.out.println("Default constructor: " + slot1); // Verwacht: AA0
// Test of de all-args constructor van de klasse Kofferslot werkt.
Kofferslot slot2 = new Kofferslot('B', 'R', 9);
System.out.println("All-args constructor: " + slot2); // Verwacht: BR9
// Test of de methode volgende() van de klasse Kofferslot correct werkt.
// AA0 volgende moet zijn: AA1
Kofferslot slot3 = new Kofferslot('A', 'A', 0);
slot3.volgende();
System.out.println("Van AA0 naar: " + slot3); // Verwacht: AA1
// BR9 volgende moet zijn: BS0
Kofferslot slot4 = new Kofferslot('B', 'R', 9);
slot4.volgende();
System.out.println("Van BR9 naar: " + slot4); // Verwacht: BS0
// DZ9 volgende<SUF>
Kofferslot slot5 = new Kofferslot('D', 'Z', 9);
slot5.volgende();
System.out.println("Van DZ9 naar: " + slot5); // Verwacht: EA0
// ZZ9 volgende moet zijn: AA0
Kofferslot slot6 = new Kofferslot('Z', 'Z', 9);
slot6.volgende();
System.out.println("Van ZZ9 naar: " + slot6); // Verwacht: AA0
}
} |
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));
}
}
|
117186_2 | /*******************************************************************************
* Copyright (c) 2011 The Hazelwire Team.
*
* This file is part of Hazelwire.
*
* Hazelwire 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.
*
* Hazelwire 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 Hazelwire. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.hazelwire.xml;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import org.hazelwire.modules.Flag;
import org.hazelwire.modules.Module;
import org.hazelwire.modules.ModulePackage;
import org.hazelwire.modules.Option;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* This class parses the configuration files that accompany the modules. All the information is extracted from the XML configuration file and
* with that information a module object is created that is linked to the original module files.
*
* @author Tim Strijdhorst
*
*/
public class ParserModuleConfig extends XMLParser
{
Module tempModule;
public ParserModuleConfig(String filePath) throws FileNotFoundException
{
super(filePath);
tempModule = new Module();
}
public ParserModuleConfig(InputStream in)
{
super(in);
}
@Override
public Object parseDocument() throws Exception
{
//get the root element
Element docElement = dom.getDocumentElement();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Get a nodelist of names (should be just one...)
NodeList generalNl = docElement.getElementsByTagName("general-info");
if(generalNl != null && generalNl.getLength() > 0)
{
//For now just get the name
Element el = (Element)generalNl.item(0);
//get the nodelist for general-info
tempModule.setName(this.getTextValue(el, "name"));
tempModule.setAuthor(this.getTextValue(el, "author"));
tempModule.setDate(dateFormat.parse(this.getTextValue(el, "date")));
tempModule.setFileName(this.getTextValue(el, "file"));
tempModule.setDeployPath(this.getTextValue(el, "deployscript"));
tempModule.setHidden(Boolean.valueOf(this.getTextValue(el, "hidden")));
//serviceport is a bit trickier
NodeList portNl = el.getElementsByTagName("serviceport");
if(portNl != null && portNl.getLength() > 0)
{
Element portEl = (Element)portNl.item(0);
tempModule.setServicePort(Integer.valueOf(portEl.getFirstChild().getNodeValue())); //set the default port
//serviceport is editable, add an option for this
//this is a bit of a dirty trick, but because this is done here it will always have id=0 ;)
if(Boolean.valueOf(portEl.getAttribute("editable")))
{
tempModule.addOption(new Option("Service port","integer",String.valueOf(tempModule.getServicePort())));
}
}
}
NodeList packageNl = docElement.getElementsByTagName("package");
if(packageNl != null && packageNl.getLength() > 0)
{
Element el = (Element)packageNl.item(0);
ModulePackage tempPackage = new ModulePackage(this.getIntValue(el, "id"),this.getTextValue(el, "name"));
tempModule.setModulePackage(tempPackage);
}
NodeList tagsNl = docElement.getElementsByTagName("tag");
if(tagsNl != null && tagsNl.getLength() > 0)
{
for(int i=0;i<tagsNl.getLength();i++)
{
Element el = (Element)tagsNl.item(i);
tempModule.addTag(el.getFirstChild().getNodeValue());
}
}
NodeList flagsNl = docElement.getElementsByTagName("flag");
if(flagsNl != null)
{
for(int i=0;i<flagsNl.getLength();i++)
{
Element el = (Element)flagsNl.item(i);
tempModule.addFlag(new Flag(this.getIntValue(el, "points"),
this.getIntValue(el, "points"))); //this might throw an exception
}
}
NodeList optionNl = docElement.getElementsByTagName("option");
if(optionNl != null)
{
for(int i=0;i<optionNl.getLength();i++)
{
Element el = (Element)optionNl.item(i);
String name = this.getTextValue(el, "name");
String value = getTextValue(el, "value");
NodeList valueNl = el.getElementsByTagName("value");
el = (Element)valueNl.item(0);
String type = el.getAttribute("type");
Option option = new Option(name,type,value);
tempModule.addOption(option);
}
}
return tempModule;
}
public Module getModule()
{
return tempModule;
}
}
| Hazelwire/Hazelwire | src/GenerationFramework/src/org/hazelwire/xml/ParserModuleConfig.java | 1,624 | //get the root element | line_comment | nl | /*******************************************************************************
* Copyright (c) 2011 The Hazelwire Team.
*
* This file is part of Hazelwire.
*
* Hazelwire 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.
*
* Hazelwire 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 Hazelwire. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.hazelwire.xml;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import org.hazelwire.modules.Flag;
import org.hazelwire.modules.Module;
import org.hazelwire.modules.ModulePackage;
import org.hazelwire.modules.Option;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* This class parses the configuration files that accompany the modules. All the information is extracted from the XML configuration file and
* with that information a module object is created that is linked to the original module files.
*
* @author Tim Strijdhorst
*
*/
public class ParserModuleConfig extends XMLParser
{
Module tempModule;
public ParserModuleConfig(String filePath) throws FileNotFoundException
{
super(filePath);
tempModule = new Module();
}
public ParserModuleConfig(InputStream in)
{
super(in);
}
@Override
public Object parseDocument() throws Exception
{
//get the<SUF>
Element docElement = dom.getDocumentElement();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Get a nodelist of names (should be just one...)
NodeList generalNl = docElement.getElementsByTagName("general-info");
if(generalNl != null && generalNl.getLength() > 0)
{
//For now just get the name
Element el = (Element)generalNl.item(0);
//get the nodelist for general-info
tempModule.setName(this.getTextValue(el, "name"));
tempModule.setAuthor(this.getTextValue(el, "author"));
tempModule.setDate(dateFormat.parse(this.getTextValue(el, "date")));
tempModule.setFileName(this.getTextValue(el, "file"));
tempModule.setDeployPath(this.getTextValue(el, "deployscript"));
tempModule.setHidden(Boolean.valueOf(this.getTextValue(el, "hidden")));
//serviceport is a bit trickier
NodeList portNl = el.getElementsByTagName("serviceport");
if(portNl != null && portNl.getLength() > 0)
{
Element portEl = (Element)portNl.item(0);
tempModule.setServicePort(Integer.valueOf(portEl.getFirstChild().getNodeValue())); //set the default port
//serviceport is editable, add an option for this
//this is a bit of a dirty trick, but because this is done here it will always have id=0 ;)
if(Boolean.valueOf(portEl.getAttribute("editable")))
{
tempModule.addOption(new Option("Service port","integer",String.valueOf(tempModule.getServicePort())));
}
}
}
NodeList packageNl = docElement.getElementsByTagName("package");
if(packageNl != null && packageNl.getLength() > 0)
{
Element el = (Element)packageNl.item(0);
ModulePackage tempPackage = new ModulePackage(this.getIntValue(el, "id"),this.getTextValue(el, "name"));
tempModule.setModulePackage(tempPackage);
}
NodeList tagsNl = docElement.getElementsByTagName("tag");
if(tagsNl != null && tagsNl.getLength() > 0)
{
for(int i=0;i<tagsNl.getLength();i++)
{
Element el = (Element)tagsNl.item(i);
tempModule.addTag(el.getFirstChild().getNodeValue());
}
}
NodeList flagsNl = docElement.getElementsByTagName("flag");
if(flagsNl != null)
{
for(int i=0;i<flagsNl.getLength();i++)
{
Element el = (Element)flagsNl.item(i);
tempModule.addFlag(new Flag(this.getIntValue(el, "points"),
this.getIntValue(el, "points"))); //this might throw an exception
}
}
NodeList optionNl = docElement.getElementsByTagName("option");
if(optionNl != null)
{
for(int i=0;i<optionNl.getLength();i++)
{
Element el = (Element)optionNl.item(i);
String name = this.getTextValue(el, "name");
String value = getTextValue(el, "value");
NodeList valueNl = el.getElementsByTagName("value");
el = (Element)valueNl.item(0);
String type = el.getAttribute("type");
Option option = new Option(name,type,value);
tempModule.addOption(option);
}
}
return tempModule;
}
public Module getModule()
{
return tempModule;
}
}
|
83986_7 | package oop.voetbalmanager.model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.jdom2.DataConversionException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class XMLreader {
public XMLreader(){
}
public Divisie readDivisie(String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
ArrayList<Team> teamList = new ArrayList<Team>();
String divisieNaam = "";
int speeldag = -1;
int stand = -1;
String avatarPath = "";
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
//parse naam en get teamlist
divisieNaam = divisieEl.getChildText("naam");
teamList = readTeamList(divisieEl);
//parse speeldag
speeldag = Integer.parseInt(divisieEl.getChildText("speeldag"));
stand = Integer.parseInt(divisieEl.getChildText("stand"));
avatarPath = divisieEl.getChildText("avatarPath");
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
//maak divisie
Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath);
return divisie;
}
public ArrayList<Team> readTeamList(Element divisie){
ArrayList<Team> teamList = new ArrayList<Team>();
//maak lijst van alle <team>
List<Element> teamElementList = divisie.getChildren("team");
//<team> als element in arrraylist toevoegen
for (int i = 0; i < teamElementList.size(); i++) {
//parse teamNaam, rank en get spelerList
Element teamEl = (Element) teamElementList.get(i);
//parse naam, rank, spelerslijst, winst ....
teamList.add(readTeam(teamEl));
}
return teamList;
}
public Team readTeam(Element teamEl){
//parse naam, rank, spelerslijst, winst ....
String teamNaam = teamEl.getChildText("naam");
int rank = Integer.parseInt(teamEl.getChildText("rank"));
ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl);
int winst = Integer.parseInt(teamEl.getChildText("winst"));
int verlies = Integer.parseInt(teamEl.getChildText("verlies"));
int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel"));
int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo"));
int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen"));
int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor"));
double budget = Double.parseDouble(teamEl.getChildText("budget"));
int score = Integer.parseInt(teamEl.getChildText("score"));
Team team = new Team(teamNaam, rank, spelerList, winst, verlies,
gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score);
return team;
}
public ArrayList<Speler> readSpelerList(String teamNaam, Element team){
ArrayList<Speler> spelerList = new ArrayList<Speler>();
//maak lijst van alle <team>
List<Element> spelerElementList = team.getChildren("speler");
//<team> als element in arrraylist toevoegen
for (int i = 0; i < spelerElementList.size(); i++) {
//parse teamNaam, rank, get spelerList ...
Element spelerEl = (Element) spelerElementList.get(i);
spelerList.add(readSpeler(spelerEl));
}
return spelerList;
}
public Speler readSpeler(Element spelerEl){
String spelerNaam = spelerEl.getChildText("naam");
int nummer=-1;
try {
nummer = spelerEl.getAttribute("id").getIntValue();
} catch (DataConversionException e) {
e.printStackTrace();
}
String type = spelerEl.getChildText("type");
int offense = Integer.parseInt(spelerEl.getChildText("offense"));
int defence = Integer.parseInt(spelerEl.getChildText("defence"));
int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding"));
String beschikbaarheid = spelerEl.getChildText("beschikbaarheid");
double prijs = Double.parseDouble(spelerEl.getChildText("prijs"));
Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs);
return speler;
}
public ArrayList<Opstelling> readOpstellingList(String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>();
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
Element opsteling = divisieEl.getChild("opstellingen");
//maak lijst van alle opstellingen
List<Element> opstElementList = opsteling.getChildren("opstelling_posities");
//<opstelling> als element in arrraylist toevoegen
for (int i = 0; i < opstElementList.size(); i++) {
//parse teamNaam, rank, get spelerList ...
Element opstEl = (Element) opstElementList.get(i);
opstellingen.add(readOpstelling(opstEl));
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
//parse naam, rank, spelerslijst, winst ....
return opstellingen;
}
public Opstelling readOpstelling(Element opstEl){
List<Element> positiesList = opstEl.getChildren();
ArrayList<Positie> posities = new ArrayList<Positie>();
for (int i = 1; i < positiesList.size(); i++) {
int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]);
int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]);
String type = positiesList.get(i).getName();
type = type.substring(0, type.length()-1);
Positie speler = new Positie(x, y, type);
posities.add(speler);
}
Collections.sort(posities, new Comparator<Positie>() {
@Override
public int compare(Positie p1, Positie p2) {
return Integer.compare(p2.getY(), p1.getY());
}
});
//parse naam, spelerslijst ....
Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities);
return opstelling;
}
public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
Wedstrijdteam wteam = null;
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
Element wteamElement = divisieEl.getChild("Wedstrijdteam");
//parse naam, rank, spelerslijst, winst ....
String opstelling = wteamElement.getChildText("opstelling");
int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek"));
String spelers = wteamElement.getChildText("spelers");
String gespeeldMet = wteamElement.getChildText("gespeeldMet");
if(userteam==null){
String teamNaam = wteamElement.getChildText("TeamNaam");
Team team = Divisie.findTeamByName(teamNaam);
User.setTeam(team);
wteam = new Wedstrijdteam(team);
}else{
wteam = new Wedstrijdteam(userteam);
}
ArrayList<Speler> spelerList = new ArrayList<Speler>();
for(Speler s: wteam.getSpelerList()){
if(spelers.contains(s.getNaam())){
spelerList.add(s);
}
}
if(spelerList.size()<1){
for(Speler s: wteam.getSpelerList()){
if(s.getType().contains("doelman")){
spelerList.add(s);
break;
}
}
for(Speler s: wteam.getSpelerList()){
if(!s.getType().contains("doelman")){
spelerList.add(s);
}
if(spelerList.size()==11){
break;
}
}
}
Collections.reverse(spelerList);
Speler[] spelersArray = new Speler[11];
spelerList.toArray(spelersArray);
ArrayList<Opstelling> opstellingen = readOpstellingList(infile);
for(Opstelling op: opstellingen){
if(op.getNaam().equals(opstelling)){
wteam.setOpstelling(op);
}
}
wteam.setTactiek(tactiek);
wteam.setWSpelers(spelersArray);
wteam.setGespeeldMet(gespeeldMet);
System.out.println("xmlreader: "+gespeeldMet);
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
return wteam;
}
}
| Hazinck/OOP-project | Voetbalmanager/src/oop/voetbalmanager/model/XMLreader.java | 2,920 | //maak lijst van alle <team> | line_comment | nl | package oop.voetbalmanager.model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.jdom2.DataConversionException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class XMLreader {
public XMLreader(){
}
public Divisie readDivisie(String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
ArrayList<Team> teamList = new ArrayList<Team>();
String divisieNaam = "";
int speeldag = -1;
int stand = -1;
String avatarPath = "";
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
//parse naam en get teamlist
divisieNaam = divisieEl.getChildText("naam");
teamList = readTeamList(divisieEl);
//parse speeldag
speeldag = Integer.parseInt(divisieEl.getChildText("speeldag"));
stand = Integer.parseInt(divisieEl.getChildText("stand"));
avatarPath = divisieEl.getChildText("avatarPath");
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
//maak divisie
Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath);
return divisie;
}
public ArrayList<Team> readTeamList(Element divisie){
ArrayList<Team> teamList = new ArrayList<Team>();
//maak lijst van alle <team>
List<Element> teamElementList = divisie.getChildren("team");
//<team> als element in arrraylist toevoegen
for (int i = 0; i < teamElementList.size(); i++) {
//parse teamNaam, rank en get spelerList
Element teamEl = (Element) teamElementList.get(i);
//parse naam, rank, spelerslijst, winst ....
teamList.add(readTeam(teamEl));
}
return teamList;
}
public Team readTeam(Element teamEl){
//parse naam, rank, spelerslijst, winst ....
String teamNaam = teamEl.getChildText("naam");
int rank = Integer.parseInt(teamEl.getChildText("rank"));
ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl);
int winst = Integer.parseInt(teamEl.getChildText("winst"));
int verlies = Integer.parseInt(teamEl.getChildText("verlies"));
int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel"));
int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo"));
int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen"));
int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor"));
double budget = Double.parseDouble(teamEl.getChildText("budget"));
int score = Integer.parseInt(teamEl.getChildText("score"));
Team team = new Team(teamNaam, rank, spelerList, winst, verlies,
gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score);
return team;
}
public ArrayList<Speler> readSpelerList(String teamNaam, Element team){
ArrayList<Speler> spelerList = new ArrayList<Speler>();
//maak lijst<SUF>
List<Element> spelerElementList = team.getChildren("speler");
//<team> als element in arrraylist toevoegen
for (int i = 0; i < spelerElementList.size(); i++) {
//parse teamNaam, rank, get spelerList ...
Element spelerEl = (Element) spelerElementList.get(i);
spelerList.add(readSpeler(spelerEl));
}
return spelerList;
}
public Speler readSpeler(Element spelerEl){
String spelerNaam = spelerEl.getChildText("naam");
int nummer=-1;
try {
nummer = spelerEl.getAttribute("id").getIntValue();
} catch (DataConversionException e) {
e.printStackTrace();
}
String type = spelerEl.getChildText("type");
int offense = Integer.parseInt(spelerEl.getChildText("offense"));
int defence = Integer.parseInt(spelerEl.getChildText("defence"));
int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding"));
String beschikbaarheid = spelerEl.getChildText("beschikbaarheid");
double prijs = Double.parseDouble(spelerEl.getChildText("prijs"));
Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs);
return speler;
}
public ArrayList<Opstelling> readOpstellingList(String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>();
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
Element opsteling = divisieEl.getChild("opstellingen");
//maak lijst van alle opstellingen
List<Element> opstElementList = opsteling.getChildren("opstelling_posities");
//<opstelling> als element in arrraylist toevoegen
for (int i = 0; i < opstElementList.size(); i++) {
//parse teamNaam, rank, get spelerList ...
Element opstEl = (Element) opstElementList.get(i);
opstellingen.add(readOpstelling(opstEl));
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
//parse naam, rank, spelerslijst, winst ....
return opstellingen;
}
public Opstelling readOpstelling(Element opstEl){
List<Element> positiesList = opstEl.getChildren();
ArrayList<Positie> posities = new ArrayList<Positie>();
for (int i = 1; i < positiesList.size(); i++) {
int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]);
int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]);
String type = positiesList.get(i).getName();
type = type.substring(0, type.length()-1);
Positie speler = new Positie(x, y, type);
posities.add(speler);
}
Collections.sort(posities, new Comparator<Positie>() {
@Override
public int compare(Positie p1, Positie p2) {
return Integer.compare(p2.getY(), p1.getY());
}
});
//parse naam, spelerslijst ....
Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities);
return opstelling;
}
public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(infile);
Wedstrijdteam wteam = null;
try {
//open xml
Document document = (Document) builder.build(xmlFile);
//maak element van <divisie>
Element divisieEl = document.getRootElement();
Element wteamElement = divisieEl.getChild("Wedstrijdteam");
//parse naam, rank, spelerslijst, winst ....
String opstelling = wteamElement.getChildText("opstelling");
int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek"));
String spelers = wteamElement.getChildText("spelers");
String gespeeldMet = wteamElement.getChildText("gespeeldMet");
if(userteam==null){
String teamNaam = wteamElement.getChildText("TeamNaam");
Team team = Divisie.findTeamByName(teamNaam);
User.setTeam(team);
wteam = new Wedstrijdteam(team);
}else{
wteam = new Wedstrijdteam(userteam);
}
ArrayList<Speler> spelerList = new ArrayList<Speler>();
for(Speler s: wteam.getSpelerList()){
if(spelers.contains(s.getNaam())){
spelerList.add(s);
}
}
if(spelerList.size()<1){
for(Speler s: wteam.getSpelerList()){
if(s.getType().contains("doelman")){
spelerList.add(s);
break;
}
}
for(Speler s: wteam.getSpelerList()){
if(!s.getType().contains("doelman")){
spelerList.add(s);
}
if(spelerList.size()==11){
break;
}
}
}
Collections.reverse(spelerList);
Speler[] spelersArray = new Speler[11];
spelerList.toArray(spelersArray);
ArrayList<Opstelling> opstellingen = readOpstellingList(infile);
for(Opstelling op: opstellingen){
if(op.getNaam().equals(opstelling)){
wteam.setOpstelling(op);
}
}
wteam.setTactiek(tactiek);
wteam.setWSpelers(spelersArray);
wteam.setGespeeldMet(gespeeldMet);
System.out.println("xmlreader: "+gespeeldMet);
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
return wteam;
}
}
|
56145_3 | package nl.hr.cmi.infdev226a;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* Een wachtrij (queue) werkt via het
* first-in first-out principe; elementen worden toegevoegd
* aan de achterkant en worden verwijderd aan de voorkant.
*
* In deze klasse implementeer je een Queue door alleen
* maar gebruik te maken van de opslagmethode die de
* klasse GelinkteLijst je biedt. De Node komt niet voor in deze klasse!
*
* In [Hubbard, hoofdstuk 6] wordt de Queue besproken.
*
*/
public class Wachtrij{
private GelinkteLijst lijst;
public Wachtrij(){
lijst = new GelinkteLijst();
}
/**
* Zet iets in de wachtrij
* aan de achterkant: FIFO
*/
public void enqueue(Object o){
lijst.insertFirst(o); //bijvoorbeeld zo
}
/**
* Haal iets van de wachtrij
* Aan de voorkant: FIFO
*/
public Object dequeue(){throw new NotImplementedException();}
/**
* Het aantal elementen in de wachtrij
* @return
*/
public int size(){throw new NotImplementedException();}
/**
* Is de lijst leeg?
* @return
*/
public boolean isEmpty(){throw new NotImplementedException();}
/**
* Bekijk het eerste element in de wachtrij,
* maar haalt het niet er vanaf.
* Note: het eerste element is als eerste toegevoegd.
* @return
*/
public Object front(){throw new NotImplementedException();}
}
| HeadhunterXamd/GelinkteLijsten | src/main/java/nl/hr/cmi/infdev226a/Wachtrij.java | 480 | /**
* Haal iets van de wachtrij
* Aan de voorkant: FIFO
*/ | block_comment | nl | package nl.hr.cmi.infdev226a;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* Een wachtrij (queue) werkt via het
* first-in first-out principe; elementen worden toegevoegd
* aan de achterkant en worden verwijderd aan de voorkant.
*
* In deze klasse implementeer je een Queue door alleen
* maar gebruik te maken van de opslagmethode die de
* klasse GelinkteLijst je biedt. De Node komt niet voor in deze klasse!
*
* In [Hubbard, hoofdstuk 6] wordt de Queue besproken.
*
*/
public class Wachtrij{
private GelinkteLijst lijst;
public Wachtrij(){
lijst = new GelinkteLijst();
}
/**
* Zet iets in de wachtrij
* aan de achterkant: FIFO
*/
public void enqueue(Object o){
lijst.insertFirst(o); //bijvoorbeeld zo
}
/**
* Haal iets van<SUF>*/
public Object dequeue(){throw new NotImplementedException();}
/**
* Het aantal elementen in de wachtrij
* @return
*/
public int size(){throw new NotImplementedException();}
/**
* Is de lijst leeg?
* @return
*/
public boolean isEmpty(){throw new NotImplementedException();}
/**
* Bekijk het eerste element in de wachtrij,
* maar haalt het niet er vanaf.
* Note: het eerste element is als eerste toegevoegd.
* @return
*/
public Object front(){throw new NotImplementedException();}
}
|
210154_32 | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
| HeatDeath/AlgorithmsSedgewick | StdLib/StdRandom.java | 3,017 | // between i and N-1 | line_comment | nl | /*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
*/
public static int discrete(double[] a) {
// precondition: sum of array entries equals 1
double r = uniform();
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
assert false;
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i<SUF>
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
}
}
|
69826_2 | import ij.*;
import ij.io.*;
import ij.plugin.*;
import java.io.*;
import java.util.*;
/**
Opens multi-image 8-bits tiff files created by Leica confocal microscope
systems using each channels own LUT. Modified by Nico Stuurman June 2000
*/
public class Leica_SP_Reader implements PlugIn {
int nr_channels = 1;
public void run(String arg) {
if (IJ.versionLessThan("1.18h"))
return;
OpenDialog od = new OpenDialog("Open Leica SP...", arg);
String dir = od.getDirectory();
String name = od.getFileName();
if (name==null)
return;
IJ.showStatus("Opening: " + dir + name);
try {
FileInfo[] fi = getFileInfo(dir, name);
//ij.IJ.write ("Leica_Reader: " + nr_channels + "\n");
openStacks(fi);
} catch (IOException e) {
String msg = e.getMessage();
if (msg==null || msg.equals(""))
msg = ""+e;
IJ.showMessage("Leica SP Reader", msg);
}
}
FileInfo[] getFileInfo(String directory, String name) throws IOException {
LeicaTiffDecoder td = new LeicaTiffDecoder(directory, name);
if (IJ.debugMode) td.enableDebugging();
FileInfo[] info = td.getTiffInfo();
nr_channels = td.nr_channels;
//ij.IJ.write ("in getFileInfo: " + nr_channels + "\n");
if (info==null)
throw new IOException("This file does not appear to be in TIFF format.");
if (IJ.debugMode) // dump tiff tags
IJ.write(info[0].info);
return info;
}
void openStacks(FileInfo[] fi) throws IOException {
if (fi[0].fileType!=FileInfo.COLOR8)
throw new IOException("This does not appear to be a stack of 8-bit color images.");
int maxStacks = nr_channels;
ImageStack[] stacks = new ImageStack[maxStacks];
int width = fi[0].width;
int height = fi[0].height;
String name = fi[0].fileName;
int length_per_channel = fi.length/nr_channels;
//ij.IJ.write ("Leica_Reader: " + length_per_channel + "\n");
for (int j=0; j<nr_channels; j++){
if (stacks[j]==null)
stacks[j] = new ImageStack(width,height);
for (int i=0; i<length_per_channel; i++) {
int k = i + j * length_per_channel;
if (fi[k].width!=width || fi[k].height!=height)
break;
FileOpener fo = new FileOpener(fi[k]);
ImagePlus imp = fo.open(false);
if (imp!=null)
stacks[j].addSlice("", imp.getProcessor());
}
if (stacks[j]!=null){
int l = j+1;
new ImagePlus(name+"(channel "+l+")", stacks[j]).show ();
}
}
}
}
/* This class inherits ImageJ's TiffDecoder and overrides the decodeImageDescription method.
The Leica SP files start their image description with "[GLOBAL]". The number
of channels in a Leica SP TIFF file is given within the image description as "NumOfVisualisations"=x.
*/
class LeicaTiffDecoder extends TiffDecoder{
public int nr_channels = 1;
public LeicaTiffDecoder(String directory, String name) {
super(directory, name);
}
public void decodeImageDescription(byte[] description, FileInfo fi) {
if (new String (description,0,8).equals("[GLOBAL]")) {
if (debugMode) ij.IJ.write ("Leica file detected..." + "\n");
String file_specs = new String (description);
if (debugMode) ij.IJ.write(file_specs);
StringTokenizer st = new StringTokenizer(file_specs, "\n= ");
while (st.hasMoreTokens()) {
if(st.hasMoreTokens()) {
String s = st.nextToken();
if (s.equals ("NumOfVisualisations")) {
//ij.IJ.write ("found" +"\n");
String temp = new String (st.nextToken());
//ij.IJ.write ("temp: " + temp + "l" + "\n");
temp = temp.trim();
try {Integer a = new Integer (temp);
nr_channels = a.intValue();}
catch (NumberFormatException e) {return;}
if (debugMode) ij.IJ.write ("channels detected: " +nr_channels+ "\n");
break; //out of while loop
}
}
}
}
}
} //class Leica_TiffDecoder
| HelioScan/HelioScan | tools/HelioImageJ/source/Leica_SP_Reader.java | 1,402 | //ij.IJ.write ("in getFileInfo: " + nr_channels + "\n");
| line_comment | nl | import ij.*;
import ij.io.*;
import ij.plugin.*;
import java.io.*;
import java.util.*;
/**
Opens multi-image 8-bits tiff files created by Leica confocal microscope
systems using each channels own LUT. Modified by Nico Stuurman June 2000
*/
public class Leica_SP_Reader implements PlugIn {
int nr_channels = 1;
public void run(String arg) {
if (IJ.versionLessThan("1.18h"))
return;
OpenDialog od = new OpenDialog("Open Leica SP...", arg);
String dir = od.getDirectory();
String name = od.getFileName();
if (name==null)
return;
IJ.showStatus("Opening: " + dir + name);
try {
FileInfo[] fi = getFileInfo(dir, name);
//ij.IJ.write ("Leica_Reader: " + nr_channels + "\n");
openStacks(fi);
} catch (IOException e) {
String msg = e.getMessage();
if (msg==null || msg.equals(""))
msg = ""+e;
IJ.showMessage("Leica SP Reader", msg);
}
}
FileInfo[] getFileInfo(String directory, String name) throws IOException {
LeicaTiffDecoder td = new LeicaTiffDecoder(directory, name);
if (IJ.debugMode) td.enableDebugging();
FileInfo[] info = td.getTiffInfo();
nr_channels = td.nr_channels;
//ij.IJ.write ("in<SUF>
if (info==null)
throw new IOException("This file does not appear to be in TIFF format.");
if (IJ.debugMode) // dump tiff tags
IJ.write(info[0].info);
return info;
}
void openStacks(FileInfo[] fi) throws IOException {
if (fi[0].fileType!=FileInfo.COLOR8)
throw new IOException("This does not appear to be a stack of 8-bit color images.");
int maxStacks = nr_channels;
ImageStack[] stacks = new ImageStack[maxStacks];
int width = fi[0].width;
int height = fi[0].height;
String name = fi[0].fileName;
int length_per_channel = fi.length/nr_channels;
//ij.IJ.write ("Leica_Reader: " + length_per_channel + "\n");
for (int j=0; j<nr_channels; j++){
if (stacks[j]==null)
stacks[j] = new ImageStack(width,height);
for (int i=0; i<length_per_channel; i++) {
int k = i + j * length_per_channel;
if (fi[k].width!=width || fi[k].height!=height)
break;
FileOpener fo = new FileOpener(fi[k]);
ImagePlus imp = fo.open(false);
if (imp!=null)
stacks[j].addSlice("", imp.getProcessor());
}
if (stacks[j]!=null){
int l = j+1;
new ImagePlus(name+"(channel "+l+")", stacks[j]).show ();
}
}
}
}
/* This class inherits ImageJ's TiffDecoder and overrides the decodeImageDescription method.
The Leica SP files start their image description with "[GLOBAL]". The number
of channels in a Leica SP TIFF file is given within the image description as "NumOfVisualisations"=x.
*/
class LeicaTiffDecoder extends TiffDecoder{
public int nr_channels = 1;
public LeicaTiffDecoder(String directory, String name) {
super(directory, name);
}
public void decodeImageDescription(byte[] description, FileInfo fi) {
if (new String (description,0,8).equals("[GLOBAL]")) {
if (debugMode) ij.IJ.write ("Leica file detected..." + "\n");
String file_specs = new String (description);
if (debugMode) ij.IJ.write(file_specs);
StringTokenizer st = new StringTokenizer(file_specs, "\n= ");
while (st.hasMoreTokens()) {
if(st.hasMoreTokens()) {
String s = st.nextToken();
if (s.equals ("NumOfVisualisations")) {
//ij.IJ.write ("found" +"\n");
String temp = new String (st.nextToken());
//ij.IJ.write ("temp: " + temp + "l" + "\n");
temp = temp.trim();
try {Integer a = new Integer (temp);
nr_channels = a.intValue();}
catch (NumberFormatException e) {return;}
if (debugMode) ij.IJ.write ("channels detected: " +nr_channels+ "\n");
break; //out of while loop
}
}
}
}
}
} //class Leica_TiffDecoder
|
36143_2 | package hint.interpreter;
import java.util.*;
import java.io.*;
import hint.util.*;
/**
* Abstraction of the commandline that can be used as input for the
* Runtime.exec() method. It'll search the paths provided by the environment
* to find the actual location of the executable. This prevents 'strange'
* behavior when the user uses (for example) batch files with the same name
* in the active directory.
*
* @author Arie Middelkoop <[email protected]>
* @version 1.1 (12 feb 2003)
* @since HI 1.0
*/
public class Commandline
{
private LinkedList parameters;
private String absolutePath;
private File workingDirectory;
private static final String EXTENSION = ".exe";
public Commandline(String commandName)
{
this(commandName, null);
}
public Commandline(String commandName, File workingDirectory)
{
this.absolutePath = commandName;
this.parameters = new LinkedList();
this.workingDirectory = workingDirectory;
}
public void addParameters(String parameter)
{
String [] parameters = Utils.prepareForExec(parameter);
for (int i=0; i<parameters.length; i++) {
addParameter(parameters[i]);
}
/* The old way:
StringTokenizer tokenizer = new StringTokenizer(parameters);
while(tokenizer.hasMoreTokens())
addParameter(tokenizer.nextToken());
*/
}
public void addParameter(String param)
{
parameters.addLast(param);
}
public String[] toCommandArray()
{
LinkedList command = new LinkedList(parameters);
command.addFirst(absolutePath);
String[] commandArray = new String[1 + parameters.size()];
return (String[]) command.toArray(commandArray);
}
public String getAbsolutePath(String commandName)
{
String envPath = ProcessEnvironment.getEnvironment().getPathEnvironmentSetting();
if (envPath == null)
return commandName;
StringTokenizer tokenizer = new StringTokenizer(envPath, File.pathSeparator);
while(tokenizer.hasMoreTokens())
{
File dir = new File(tokenizer.nextToken());
File commandWithExtension = new File(dir, commandName + EXTENSION);
if (commandWithExtension.exists())
return commandWithExtension.getPath();
// !!! gevaarlijk omdat ie ook paden vindt zo (c:\apps\helium als c:\apps in je pad zit)
File commandWithoutExtension = new File(dir, commandName);
if (commandWithoutExtension.exists())
return commandWithoutExtension.getPath();
}
return commandName;
}
public String toString () {
LinkedList command = new LinkedList(parameters);
command.addFirst(absolutePath);
return command.toString();
}
public File getWorkingDirectory()
{
return workingDirectory;
}
}
| Helium4Haskell/hint | hint/interpreter/Commandline.java | 789 | // !!! gevaarlijk omdat ie ook paden vindt zo (c:\apps\helium als c:\apps in je pad zit) | line_comment | nl | package hint.interpreter;
import java.util.*;
import java.io.*;
import hint.util.*;
/**
* Abstraction of the commandline that can be used as input for the
* Runtime.exec() method. It'll search the paths provided by the environment
* to find the actual location of the executable. This prevents 'strange'
* behavior when the user uses (for example) batch files with the same name
* in the active directory.
*
* @author Arie Middelkoop <[email protected]>
* @version 1.1 (12 feb 2003)
* @since HI 1.0
*/
public class Commandline
{
private LinkedList parameters;
private String absolutePath;
private File workingDirectory;
private static final String EXTENSION = ".exe";
public Commandline(String commandName)
{
this(commandName, null);
}
public Commandline(String commandName, File workingDirectory)
{
this.absolutePath = commandName;
this.parameters = new LinkedList();
this.workingDirectory = workingDirectory;
}
public void addParameters(String parameter)
{
String [] parameters = Utils.prepareForExec(parameter);
for (int i=0; i<parameters.length; i++) {
addParameter(parameters[i]);
}
/* The old way:
StringTokenizer tokenizer = new StringTokenizer(parameters);
while(tokenizer.hasMoreTokens())
addParameter(tokenizer.nextToken());
*/
}
public void addParameter(String param)
{
parameters.addLast(param);
}
public String[] toCommandArray()
{
LinkedList command = new LinkedList(parameters);
command.addFirst(absolutePath);
String[] commandArray = new String[1 + parameters.size()];
return (String[]) command.toArray(commandArray);
}
public String getAbsolutePath(String commandName)
{
String envPath = ProcessEnvironment.getEnvironment().getPathEnvironmentSetting();
if (envPath == null)
return commandName;
StringTokenizer tokenizer = new StringTokenizer(envPath, File.pathSeparator);
while(tokenizer.hasMoreTokens())
{
File dir = new File(tokenizer.nextToken());
File commandWithExtension = new File(dir, commandName + EXTENSION);
if (commandWithExtension.exists())
return commandWithExtension.getPath();
// !!! gevaarlijk<SUF>
File commandWithoutExtension = new File(dir, commandName);
if (commandWithoutExtension.exists())
return commandWithoutExtension.getPath();
}
return commandName;
}
public String toString () {
LinkedList command = new LinkedList(parameters);
command.addFirst(absolutePath);
return command.toString();
}
public File getWorkingDirectory()
{
return workingDirectory;
}
}
|
138944_4 | package Prototype;
public class Kello implements Cloneable {
private Viisari tuntiviisari;
private Viisari minuuttiviisari;
private Viisari sekuntiViisari;
public Kello(int tunti, int minuutti, int sekunti) {
tuntiviisari = new Viisari(tunti);
minuuttiviisari = new Viisari(minuutti);
sekuntiViisari = new Viisari(sekunti);
}
public void tick() {
int sekunti = sekuntiViisari.addArvo(1);
if (sekunti >= 59) {
sekuntiViisari.setArvo(0);
int minuutti = minuuttiviisari.addArvo(1);
if (minuutti >= 59) {
minuuttiviisari.setArvo(0);
int tunti = tuntiviisari.addArvo(1);
if (tunti >= 23) {
tuntiviisari.setArvo(0);
}
}
}
}
// Java-clone metodi (shallow copy)
@Override
public Kello clone() {
try {
Kello kello = (Kello) super.clone();
// Shallow copy
kello.sekuntiViisari = this.sekuntiViisari;
kello.minuuttiviisari = this.minuuttiviisari;
kello.tuntiviisari = this.tuntiviisari;
// Deep copy
// kello.sekuntiViisari = new Viisari(this.sekuntiViisari.getArvo());
// kello.minuuttiviisari = new Viisari(this.minuuttiviisari.getArvo());
// kello.tuntiviisari = new Viisari(this.tuntiviisari.getArvo());
return kello;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return (Kello) null;
}
}
// Oma implementaatio (Deep copy)
public Kello copy() {
/*
* Voisi tehdä myös clone ja asettaa viisarit uudelleen niinkuin ylempänä, mutta tämä on parempi
* tapa.
*/
return new Kello(this.tuntiviisari.getArvo(), this.minuuttiviisari.getArvo(),
this.sekuntiViisari.getArvo());
}
public void printTime() {
System.out.println(tuntiviisari.getArvo() + ":" + minuuttiviisari.getArvo() + ":" + sekuntiViisari.getArvo());
}
public void setTunti(int tunti) {
tuntiviisari.setArvo(tunti);
}
public void setMinuutti(int minuutti) {
minuuttiviisari.setArvo(minuutti);
}
public void setSekunti(int sekunti) {
sekuntiViisari.setArvo(sekunti);
}
}
class Viisari implements Cloneable {
int arvo;
public Viisari(int arvo) {
this.arvo = arvo;
}
public void setArvo(int arvo) {
this.arvo = arvo;
}
public int getArvo() {
return arvo;
}
public int addArvo(int arvo) {
this.arvo += arvo;
return this.arvo;
}
}
| Henriui/Java-design-patterns | Prototype/Kello.java | 981 | // Oma implementaatio (Deep copy) | line_comment | nl | package Prototype;
public class Kello implements Cloneable {
private Viisari tuntiviisari;
private Viisari minuuttiviisari;
private Viisari sekuntiViisari;
public Kello(int tunti, int minuutti, int sekunti) {
tuntiviisari = new Viisari(tunti);
minuuttiviisari = new Viisari(minuutti);
sekuntiViisari = new Viisari(sekunti);
}
public void tick() {
int sekunti = sekuntiViisari.addArvo(1);
if (sekunti >= 59) {
sekuntiViisari.setArvo(0);
int minuutti = minuuttiviisari.addArvo(1);
if (minuutti >= 59) {
minuuttiviisari.setArvo(0);
int tunti = tuntiviisari.addArvo(1);
if (tunti >= 23) {
tuntiviisari.setArvo(0);
}
}
}
}
// Java-clone metodi (shallow copy)
@Override
public Kello clone() {
try {
Kello kello = (Kello) super.clone();
// Shallow copy
kello.sekuntiViisari = this.sekuntiViisari;
kello.minuuttiviisari = this.minuuttiviisari;
kello.tuntiviisari = this.tuntiviisari;
// Deep copy
// kello.sekuntiViisari = new Viisari(this.sekuntiViisari.getArvo());
// kello.minuuttiviisari = new Viisari(this.minuuttiviisari.getArvo());
// kello.tuntiviisari = new Viisari(this.tuntiviisari.getArvo());
return kello;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return (Kello) null;
}
}
// Oma implementaatio<SUF>
public Kello copy() {
/*
* Voisi tehdä myös clone ja asettaa viisarit uudelleen niinkuin ylempänä, mutta tämä on parempi
* tapa.
*/
return new Kello(this.tuntiviisari.getArvo(), this.minuuttiviisari.getArvo(),
this.sekuntiViisari.getArvo());
}
public void printTime() {
System.out.println(tuntiviisari.getArvo() + ":" + minuuttiviisari.getArvo() + ":" + sekuntiViisari.getArvo());
}
public void setTunti(int tunti) {
tuntiviisari.setArvo(tunti);
}
public void setMinuutti(int minuutti) {
minuuttiviisari.setArvo(minuutti);
}
public void setSekunti(int sekunti) {
sekuntiViisari.setArvo(sekunti);
}
}
class Viisari implements Cloneable {
int arvo;
public Viisari(int arvo) {
this.arvo = arvo;
}
public void setArvo(int arvo) {
this.arvo = arvo;
}
public int getArvo() {
return arvo;
}
public int addArvo(int arvo) {
this.arvo += arvo;
return this.arvo;
}
}
|
178607_3 | package com.kh.great.domain.dao.member;
import com.kh.great.domain.dao.product.Product;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
public class Member {
private Long memNumber; //mem_number number(9), --회원번호
private String memType; //mem_type varchar2(15), --회원유형
private String memId; //mem_id varchar2(30), --아이디
private String memPassword; //mem_password varchar2(18), --비밀번호
private String memName; //mem_name varchar2(18), --이름
private String memNickname; //mem_nickname varchar2(18), --닉네임
private String memEmail; //mem_email varchar2(30), --이메일
private String memBusinessnumber; //mem_businessnumber varchar2(10), --사업자번호
private String memStoreName; //mem_store_name varchar2(45), --가게명
private String memStorePhonenumber; //mem_store_phonenumber varchar2(15), --가게연락처
private String memStoreLocation; //mem_store_location varchar2(150), --가게주소
private String memStoreLatitude; //mem_store_latitude number(15, 9), --가게위도
private String memStoreLongitude; //mem_store_longitude number(15, 9), --가게경도
private String memStoreIntroduce; //mem_store_introduce varchar2(150), --가게소개
private String memStoreSns; //mem_store_sns varchar2(150), --가게SNS
private LocalDateTime memRegtime; //mem_regtime date, --가입일자
private LocalDateTime memLockExpiration; //mem_lock_expiration date, --정지기간
private String memAdmin; //mem_admin varchar2(3) --관리자여부
private Product product;
public Member(String memType, String memId, String memPassword, String memName, String memNickname, String memEmail, String memBusinessnumber, String memStoreName, String memStroePhonenumber, String memStoreLocation, String memStoreLatitude, String memStoreLongitude, String memStoreIntroduce, String memStoreSns, LocalDateTime memRegtime, LocalDateTime memLockExpiration, String memAdmin) {
this.memType = memType;
this.memId = memId;
this.memPassword = memPassword;
this.memName = memName;
this.memNickname = memNickname;
this.memEmail = memEmail;
this.memBusinessnumber = memBusinessnumber;
this.memStoreName = memStoreName;
this.memStorePhonenumber = memStroePhonenumber;
this.memStoreLocation = memStoreLocation;
this.memStoreLatitude = memStoreLatitude;
this.memStoreLongitude = memStoreLongitude;
this.memStoreIntroduce = memStoreIntroduce;
this.memStoreSns = memStoreSns;
this.memRegtime = memRegtime;
this.memLockExpiration = memLockExpiration;
this.memAdmin = memAdmin;
}
}
| Heoveloper/great | src/main/java/com/kh/great/domain/dao/member/Member.java | 880 | //mem_password varchar2(18), --비밀번호 | line_comment | nl | package com.kh.great.domain.dao.member;
import com.kh.great.domain.dao.product.Product;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
public class Member {
private Long memNumber; //mem_number number(9), --회원번호
private String memType; //mem_type varchar2(15), --회원유형
private String memId; //mem_id varchar2(30), --아이디
private String memPassword; //mem_password varchar2(18),<SUF>
private String memName; //mem_name varchar2(18), --이름
private String memNickname; //mem_nickname varchar2(18), --닉네임
private String memEmail; //mem_email varchar2(30), --이메일
private String memBusinessnumber; //mem_businessnumber varchar2(10), --사업자번호
private String memStoreName; //mem_store_name varchar2(45), --가게명
private String memStorePhonenumber; //mem_store_phonenumber varchar2(15), --가게연락처
private String memStoreLocation; //mem_store_location varchar2(150), --가게주소
private String memStoreLatitude; //mem_store_latitude number(15, 9), --가게위도
private String memStoreLongitude; //mem_store_longitude number(15, 9), --가게경도
private String memStoreIntroduce; //mem_store_introduce varchar2(150), --가게소개
private String memStoreSns; //mem_store_sns varchar2(150), --가게SNS
private LocalDateTime memRegtime; //mem_regtime date, --가입일자
private LocalDateTime memLockExpiration; //mem_lock_expiration date, --정지기간
private String memAdmin; //mem_admin varchar2(3) --관리자여부
private Product product;
public Member(String memType, String memId, String memPassword, String memName, String memNickname, String memEmail, String memBusinessnumber, String memStoreName, String memStroePhonenumber, String memStoreLocation, String memStoreLatitude, String memStoreLongitude, String memStoreIntroduce, String memStoreSns, LocalDateTime memRegtime, LocalDateTime memLockExpiration, String memAdmin) {
this.memType = memType;
this.memId = memId;
this.memPassword = memPassword;
this.memName = memName;
this.memNickname = memNickname;
this.memEmail = memEmail;
this.memBusinessnumber = memBusinessnumber;
this.memStoreName = memStoreName;
this.memStorePhonenumber = memStroePhonenumber;
this.memStoreLocation = memStoreLocation;
this.memStoreLatitude = memStoreLatitude;
this.memStoreLongitude = memStoreLongitude;
this.memStoreIntroduce = memStoreIntroduce;
this.memStoreSns = memStoreSns;
this.memRegtime = memRegtime;
this.memLockExpiration = memLockExpiration;
this.memAdmin = memAdmin;
}
}
|
17890_5 | package com.beligum.thomasmore.mobielegidsen.beans.app;
import com.beligum.base.utils.Logger;
import com.beligum.thomasmore.mobielegidsen.beans.app.ifaces.*;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by bram on 4/13/16.
*/
public class Schorre extends AbstractRoute
{
//-----CONSTANTS-----
private static final int DEFAULT_ZOOM_LEVEL = 15;
private static final URI POSTER = URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/algemeen/poster.jpg");
private static final float LENGTH_KMS = 5f;
private static final float LENGTH_HOURS = 1f;
private static final URI[] IMAGES = new URI[] {
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/2.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/4.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/1.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/algemeen/tina.jpg"),
};
private static final MapLocation LOCATION = new MapLocation(51.0895, 4.382, 14);
private static final Accessibility[] ACCESSIBILITY = new Accessibility[] {
new DefaultAccessibility("Waar begint de wandeling?",
"Deze wandeling start in het congrescentum De Pitte. Dit is het centrale gebouw midden in het " +
"domein waar je ook de onthaalbalie van De Schorre vindt. (Je wandelt eerst twee bruggetjes over, " +
"volg de pijlen in het domein)."),
new DefaultAccessibility("Met de fiets",
"Vanuit alle richtingen bereik je De Schorre makkelijk en snel met de fiets. Kom je via de Rupeldijk, " +
"dan kies je best voor de fietstunnel onder de Kapelstraat (via fietsknooppunt 26). " +
"<a href=\"http://www.fietsnet.be/\" target=\"_blank\">Hier</a> kan je " +
"eenvoudig je fietsroute uitstippelen (geef knooppunt 26 of 24 als eindbestemming in)."),
new DefaultAccessibility("Met de trein",
"Het station van Boom ligt op de lijn Antwerpen-Puurs. " +
"Plan <a href=\"http://www.belgianrail.be/\" target=\"_blank\">hier</a> je route met de trein. Vanaf het " +
"station is het 25 min. wandelen naar De Schorre. Je kan ook bus 182 of 295 richting Antwerpen " +
"nemen tot halte De Schorre. Let op: in het weekend en op feestdagen stoppen er geen treinen in " +
"Boom. Dan neem je best de trein tot Antwerpen-Centraal of Mechelen en neem je buslijn 500 tot " +
"halte Schorre."),
new DefaultAccessibility("Met De Lijn",
"Er bevinden zich twee haltes nabij De Schorre:" +
"<ul>" +
"<li>Halte 'Boom De Schorre' bevindt zich aan de hoofdingang van het domein in de " +
"Schommelei. Lijnen <a href=\"https://www.delijn.be/nl/lijnen/lijn//1/132/8/BUS\" target=\"_blank\">132</a>, " +
"<a href=\"https://www.delijn.be/nl/lijnen/lijn//1/182/7/BUS\" target=\"_blank\">182</a>, " +
"<a href=\"https://www.delijn.be/nl/lijnen/lijn//1/295/7/BUS\" target=\"_blank\">295</a> en " +
"<a href=\"https://www.delijn.be/nl/lijnen/lijn/1/298/7\" target=\"_blank\">298</a> " +
"bedienen deze halte.</li>" +
"<li>Halte 'Boom Schorre' bevindt zich in de Kapelstraat. Lijn 500 bedient deze halte.</li>" +
"</ul>" +
"<a href=\"https://www.delijn.be/\" target=\"_blank\">Hier</a> vind je dienstregelingen en een reisroute op maat."),
new DefaultAccessibility("Met de auto",
"Geef in je GPS ‘Schommelei, Boom’ in. De Schorre is bereikbaar vanaf de A12 en E19:" +
"<ul>" +
"<li>Vanaf E19: neem afrit 7 Kontich en volg de pijlen richting Boom en De Schorre.</li>" +
"<li>Vanaf A12: neem afrit 9 Boom en volg de pijlen richting De Schorre.</li>" +
"</ul>" +
"Parkeren kan op P1 (Schommelei, aan de hoofdingang) en P2 (Kapelstraat). Voor autocars en " +
"personen met een beperking zijn parkeerplaatsen voorzien op P1."
),
new DefaultAccessibility("Hoe ziet deze wandeling eruit?",
LENGTH_KMS+" km of "+LENGTH_HOURS+" uur wandelen over voornamelijk verharde wegen."),
new DefaultAccessibility("Toegankelijkheid",
"De wandeling is geschikt voor rolstoelgebruikers of kinderwagens."),
};
public static Route INSTANCE = new Schorre();
//-----VARIABLES-----
private Map<String, Stop> stops;
//-----CONSTRUCTORS-----
public Schorre()
{
Stop[] STOPS_ARRAY = new Stop[0];
try {
STOPS_ARRAY = new Stop[] {
new DefaultStop("Startpunt wandeling De Schorre",
"Startpunt wandeling De Schorre",
"Schommelei", "1/1", "2850", "Boom",
null,
"Dit is de start van onze wandeling. Onze gids in het bovenstaande filmpje legt je in een notendop uit wat De Schorre zo speciaal maakt.",
null,
null,
null,
new MapLocation(51.087721448164324, 4.3819355964660645, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/reconversie-de-schorre.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/reconversie-de-schorre.jpg")),
}
),
new DefaultStop("Ramp Steenbakkerij",
"Ramp Steenbakkerij",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 16",
"Tussen het groen ligt een betonnen pijlerconstructie verscholen. Het vormt een feëriek decor voor het jaarlijks evenement Putteke Winter.",
"De opgaande ramp onderstut door pijlers is nog een overblijfsel van de ramp van Steenbakkerij Anverreet. Over de ramp lopen sporen waarlangs de wagonnetjes de klei uit de put naar de machinehal brachten. De machinehal is verdwenen, maar verderop is er nog een oude bagger van Anverreet bewaard in één van de waterpartijen.",
null,
"erfgoed, steenbakkerijnijverheid",
new MapLocation(51.087040793866144, 4.386935234069824, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/ramp-steenbakkerij/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/ramp-steenbakkerij/2.jpg")),
}
),
new DefaultStop("Oude Bagger",
"Oude Bagger",
"Schommelei", "1/1", "2850", "Boom",
"",
"Aan de rand van deze vroegere kleiput staat nog een oude bagger. In de laatste periode van de kleiopgravingen gebruikte men zulke baggers om de klei van de wanden van de put te schrapen.",
null,
null,
null,
new MapLocation(51.08931858773361, 4.3883514404296875, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/impressie-van-de-handmatige-ontginning-fotoreeks.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/impressie-van-de-handmatige-ontginning-fotoreeks.jpg")),
}
),
new DefaultStop("Deltaweide",
"Deltaweide",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 31",
"Van bovenaf heb je hier een goed uitzicht op De Schorre en de ruime omgeving. De deltaweide heet zo omdat hier deltavliegers en parapenters komen oefenen. Tot voor enkele decennia werd hier nog klei afgestoken. In de zomer is hier het hoofdpodium van Tomorrowland.",
null,
null,
"parapent, deltavliegen, teambuilding, steenbakkerijnijverheid",
new MapLocation(51.09285298955352, 4.3861788511276245, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/deltaweide/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/deltaweide/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1900-1975.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1900-1975.jpg")),
}
),
new DefaultStop("One World brug",
"One World brug",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 00",
"One World by the People of Tomorrow is een kunstinstallatie van Arne Quinze in Provinciaal Recreatiedomein De Schorre. Ze werd in 2015 ontworpen naar aanleiding van 10 jaar Tomorrowland.",
"De kunstinstallatie is een permanente brug die een functie vervult als wandel- en fietspad doorheen het domein. Ze is geïnspireerd door de Nike van Samothrache, een beeld uit de klassieke oudheid dat de overwinning van de vrijheid voorstelt. De kunstinstallatie verbindt op een symbolische manier personen van over de hele wereld. Iedereen -waar ook ter wereld- kon een persoonlijke boodschap laten vereeuwigen in één van 210.000 planken van de installatie.",
new Stop.SubSection[] {
new Stop.SubSection("One World brug vervangt stuk historisch erfgoed.",
"De brug die de verschillende gebieden van het domein verbindt, is op de plaats gekomen van de voormalige brug of ramp van steenbakkerij Verstrepen. Hierlangs trok men de klei uit de kleiput met wagonnetjes naar de machinehal. De brug was dringend aan vervanging toe.")
},
"kunstwerk, Arne Quinze, Tomorrowland",
new MapLocation(51.09063601789197, 4.382901191711426, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/de-schorre-fotoreeks.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/de-schorre-fotoreeks.jpg")),
}
),
new DefaultStop("Machinehal",
"Machinehal",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 00",
"Een hedendaags congrescentrum in industriële look, uitgerust met de nieuwste multimedia, met een aula voor 120 personen en verschillende vergaderzalen. Een verzorgde catering en combinatiemogelijkheden met buitenactiviteiten zijn een extra troef.",
"Congrescentrum de Pitte is ingericht in de vroegere machinehal van Steenbakkerij Verstrepen. Hier werd tot ca. 1970 de klei gekneed, geperst tot strengen en versneden tot baksteen. De basisstructuur is overeind gebleven bij deze hedendaagse renovatie: stalen structuren, rode baksteen en grote open ruimten zorgen voor een eigentijds loftgevoel en een trendy look. Je kunt er terecht voor congressen, vergaderingen, workshops en netwerkevenementen. De ruime parkeergelegenheid, rustgevende omgeving, verzorgde catering en combinatiemogelijkheden met buitenactiviteiten, maken van congrescentrum De Pitte jouw ideale partner!",
null,
"Congrescentrum, erfgoed, steenbakkerijnijverheid",
new MapLocation(51.088216769500264, 4.3816620111465445, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/machinehal/1.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1975-1990.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1975-1990.jpg")),
}
),
new DefaultStop("Droogloodsen",
"Droogloodsen",
"Schommelei", "1/1", "2850", "Boom",
null,
"In deze vlakte stonden vroeger de droogloodsen. Hier werden de kleivormen gedroogd vooraleer ze in de oven gebakken werden. De hele Rupelstreek stond vroeger bijna vol met dergelijke loodsen. De meeste van dergelijke loodsen waren vrij open zodat de wind er makkelijk doorheen kon blazen om beter te drogen. Hier en daar waren er ook droogloodsen waar men met warme lucht de stenen droogde om het proces sneller te latern verlopen. ",
null,
null,
null,
new MapLocation(51.08687568314563, 4.3763190507888785, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/portret-leona.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/portret-leona.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/2.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/3.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/4.jpg")),
}
),
new DefaultStop("Afval",
"Afval",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 05",
"De schoorstenen in de Rupelstreek getuigen van een eens florerende baksteenindustrie. Om die stenen te vervaardigen moest men grote hoeveelheden klei delven en dat tast het landschap enorm aan.",
"De schoorstenen in de Rupelstreek getuigen van een eens florerende baksteenindustrie. Om die stenen te vervaardigen moest men grote hoeveelheden klei delven en dat tast het landschap enorm aan.",
null,
"afval",
new MapLocation(51.083441920502544, 4.374532699584961, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/afval.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/afval.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/afval/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/afval/2.jpg")),
}
),
new DefaultStop("Steenkaaien",
"Steenkaaien",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 05",
"De steiger en het ponton werden aangelegd aan de oude 'steenkaai' van Steenbakkerij Van Herck. Hier werd de baksteen getransporteerd naar Antwerpen om van daaruit te vertrekken naar het binnenland, Nederland, Engeland of zelfs de Verenigde Staten.",
"De steiger en het ponton werden met subsidies van Toerisme Vlaanderen aangelegd als toegang tot het Nautisch Bezoekerscentrum. In 2015 waren ze dringend aan renovatie toe. Het ponton werd hersteld; de brug verbreed voor meer comfort voor de passagiers.",
null,
"passagiersvaart, aanlegsteiger",
new MapLocation(51.082783107653015, 4.376506805419922, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/rivier-de-rupel.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/rivier-de-rupel.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/steenkaaien/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/steenkaaien/2.jpg")),
}
),
new DefaultStop("Ringoven en fietsbelevingspunt",
"Ringoven en fietsbelevingspunt",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 16",
"Je ziet hier nog de overblijfselen van een zogenaamde ringoven. Dit was een van de types ovens waar vroeger de bakstenen in gebakken werden. Men vulde de oven met klei in de vorm van bakstenen, met daartussen brandbaar materiaal. Dit stak men dan in brand om zo de stenen te bakken. Het vuur ging helemaal rond in de oven gedurende enkele weken totdat alle stenen gebakken waren.",
"Tegen 2018 wil de provincie dit gezellig pleintje renoveren tot een ontmoetingsplek voor recreatieve fietsers en wielerfanaten, met onder meer een toeristische balie, een wielercollectie, fietsenverhuur, een fietshersteldienst, elektrische oplaadpunten en een themacafé. De oude ringoven en andere steenbakkersrelicten worden in de nieuwe plannen geïntegreerd. ",
new Stop.SubSection[] {
new Stop.SubSection("Relicten ringoven De Roeck",
"Relicten van een ringoven. Maar voor de helft bewaard, het zuidelijke deel is gesloopt. Een ringoven is een ringvormige gang met toegangsdeuren langs de zijkanten –om de bakstenen in en uit te zetten- en stookgaten bovenaan. Dit nieuwe type oven uit het einde van de 19de eeuw zorgde ervoor dat er continu kon gebakken worden. Het vuur verplaatste zich doorheen de ring. Een ringoven werd nooit gedoofd, tenzij voor herstelwerkzaamheden.")
},
"erfgoed, steenbakkerijnijverheid",
new MapLocation(51.08330375592542, 4.3820321559906, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("http://www.youtube.com/embed/nI3IOSkS7Nw?rel=0&controls=0&&showinfo=0"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/fietsbelevingspunt-en-ringoven.jpg"))
}
),
};
}
catch (Exception e) {
Logger.error("Caught error while creating stop list for " + this.getName(), e);
}
this.stops = new LinkedHashMap<>();
for (Stop stop : STOPS_ARRAY) {
this.stops.put(stop.getSlug(), stop);
}
}
//-----PUBLIC METHODS-----
@Override
public String getName()
{
return "De Schorre";
}
@Override
public String getSlug()
{
return "de-schorre";
}
@Override
public String getIntroduction()
{
return "De Schorre is een put vol pit. Je vindt er een brede waaier aan recreatie- en sportmogelijkheden. Het is een prachtig provinciaal domein om te wandelen en te fietsen!";
}
@Override
public URI getPoster()
{
return POSTER;
}
@Override
public URI[] getImages()
{
return IMAGES;
}
@Override
public String getDescription()
{
return "<p>Provinciaal Recreatiedomein De Schorre is een geslaagde reconversie van een 75 ha grote kleiput naar een gebied met actieve recreatiemogelijkheden. Watersport, avonturentoren, sportvelden, speeltuin en wandelpaden met mooie uitzichtpunten zijn er de troeven. Een derde van het gebied is natuurgebied en een geliefde verzamelplaats voor waterjuffers, libellen, kikkers en watervogels.</p>";
}
@Override
public Region getRegion()
{
return Rupelstreek.INSTANCE;
}
@Override
public MapLocation getLocation()
{
return LOCATION;
}
@Override
public Map<String, Stop> getStops()
{
return stops;
}
@Override
public String getColor()
{
return "color-1";
}
@Override
public Accessibility[] getAccessibility()
{
return ACCESSIBILITY;
}
@Override
public String getLength()
{
return LENGTH_KMS+" km";
}
@Override
public String getDuration()
{
return "ca. "+LENGTH_HOURS+" uur";
}
@Override
public SurroundingEntry[] getSurroundingEntries()
{
return SurroundingEntry.SURROUNDING_ENTRIES_RUPELSTREEK;
}
//-----PROTECTED METHODS-----
//-----PRIVATE METHODS-----
}
| Hermanverschooten/thomasmore.mobielegidsen | src/main/java/com/beligum/thomasmore/mobielegidsen/beans/app/Schorre.java | 7,293 | //www.delijn.be/nl/lijnen/lijn//1/295/7/BUS\" target=\"_blank\">295</a> en " + | line_comment | nl | package com.beligum.thomasmore.mobielegidsen.beans.app;
import com.beligum.base.utils.Logger;
import com.beligum.thomasmore.mobielegidsen.beans.app.ifaces.*;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by bram on 4/13/16.
*/
public class Schorre extends AbstractRoute
{
//-----CONSTANTS-----
private static final int DEFAULT_ZOOM_LEVEL = 15;
private static final URI POSTER = URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/algemeen/poster.jpg");
private static final float LENGTH_KMS = 5f;
private static final float LENGTH_HOURS = 1f;
private static final URI[] IMAGES = new URI[] {
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/2.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/4.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/1.jpg"),
URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/algemeen/tina.jpg"),
};
private static final MapLocation LOCATION = new MapLocation(51.0895, 4.382, 14);
private static final Accessibility[] ACCESSIBILITY = new Accessibility[] {
new DefaultAccessibility("Waar begint de wandeling?",
"Deze wandeling start in het congrescentum De Pitte. Dit is het centrale gebouw midden in het " +
"domein waar je ook de onthaalbalie van De Schorre vindt. (Je wandelt eerst twee bruggetjes over, " +
"volg de pijlen in het domein)."),
new DefaultAccessibility("Met de fiets",
"Vanuit alle richtingen bereik je De Schorre makkelijk en snel met de fiets. Kom je via de Rupeldijk, " +
"dan kies je best voor de fietstunnel onder de Kapelstraat (via fietsknooppunt 26). " +
"<a href=\"http://www.fietsnet.be/\" target=\"_blank\">Hier</a> kan je " +
"eenvoudig je fietsroute uitstippelen (geef knooppunt 26 of 24 als eindbestemming in)."),
new DefaultAccessibility("Met de trein",
"Het station van Boom ligt op de lijn Antwerpen-Puurs. " +
"Plan <a href=\"http://www.belgianrail.be/\" target=\"_blank\">hier</a> je route met de trein. Vanaf het " +
"station is het 25 min. wandelen naar De Schorre. Je kan ook bus 182 of 295 richting Antwerpen " +
"nemen tot halte De Schorre. Let op: in het weekend en op feestdagen stoppen er geen treinen in " +
"Boom. Dan neem je best de trein tot Antwerpen-Centraal of Mechelen en neem je buslijn 500 tot " +
"halte Schorre."),
new DefaultAccessibility("Met De Lijn",
"Er bevinden zich twee haltes nabij De Schorre:" +
"<ul>" +
"<li>Halte 'Boom De Schorre' bevindt zich aan de hoofdingang van het domein in de " +
"Schommelei. Lijnen <a href=\"https://www.delijn.be/nl/lijnen/lijn//1/132/8/BUS\" target=\"_blank\">132</a>, " +
"<a href=\"https://www.delijn.be/nl/lijnen/lijn//1/182/7/BUS\" target=\"_blank\">182</a>, " +
"<a href=\"https://www.delijn.be/nl/lijnen/lijn//1/295/7/BUS\" target=\"_blank\">295</a><SUF>
"<a href=\"https://www.delijn.be/nl/lijnen/lijn/1/298/7\" target=\"_blank\">298</a> " +
"bedienen deze halte.</li>" +
"<li>Halte 'Boom Schorre' bevindt zich in de Kapelstraat. Lijn 500 bedient deze halte.</li>" +
"</ul>" +
"<a href=\"https://www.delijn.be/\" target=\"_blank\">Hier</a> vind je dienstregelingen en een reisroute op maat."),
new DefaultAccessibility("Met de auto",
"Geef in je GPS ‘Schommelei, Boom’ in. De Schorre is bereikbaar vanaf de A12 en E19:" +
"<ul>" +
"<li>Vanaf E19: neem afrit 7 Kontich en volg de pijlen richting Boom en De Schorre.</li>" +
"<li>Vanaf A12: neem afrit 9 Boom en volg de pijlen richting De Schorre.</li>" +
"</ul>" +
"Parkeren kan op P1 (Schommelei, aan de hoofdingang) en P2 (Kapelstraat). Voor autocars en " +
"personen met een beperking zijn parkeerplaatsen voorzien op P1."
),
new DefaultAccessibility("Hoe ziet deze wandeling eruit?",
LENGTH_KMS+" km of "+LENGTH_HOURS+" uur wandelen over voornamelijk verharde wegen."),
new DefaultAccessibility("Toegankelijkheid",
"De wandeling is geschikt voor rolstoelgebruikers of kinderwagens."),
};
public static Route INSTANCE = new Schorre();
//-----VARIABLES-----
private Map<String, Stop> stops;
//-----CONSTRUCTORS-----
public Schorre()
{
Stop[] STOPS_ARRAY = new Stop[0];
try {
STOPS_ARRAY = new Stop[] {
new DefaultStop("Startpunt wandeling De Schorre",
"Startpunt wandeling De Schorre",
"Schommelei", "1/1", "2850", "Boom",
null,
"Dit is de start van onze wandeling. Onze gids in het bovenstaande filmpje legt je in een notendop uit wat De Schorre zo speciaal maakt.",
null,
null,
null,
new MapLocation(51.087721448164324, 4.3819355964660645, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/reconversie-de-schorre.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/reconversie-de-schorre.jpg")),
}
),
new DefaultStop("Ramp Steenbakkerij",
"Ramp Steenbakkerij",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 16",
"Tussen het groen ligt een betonnen pijlerconstructie verscholen. Het vormt een feëriek decor voor het jaarlijks evenement Putteke Winter.",
"De opgaande ramp onderstut door pijlers is nog een overblijfsel van de ramp van Steenbakkerij Anverreet. Over de ramp lopen sporen waarlangs de wagonnetjes de klei uit de put naar de machinehal brachten. De machinehal is verdwenen, maar verderop is er nog een oude bagger van Anverreet bewaard in één van de waterpartijen.",
null,
"erfgoed, steenbakkerijnijverheid",
new MapLocation(51.087040793866144, 4.386935234069824, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/ramp-steenbakkerij/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/ramp-steenbakkerij/2.jpg")),
}
),
new DefaultStop("Oude Bagger",
"Oude Bagger",
"Schommelei", "1/1", "2850", "Boom",
"",
"Aan de rand van deze vroegere kleiput staat nog een oude bagger. In de laatste periode van de kleiopgravingen gebruikte men zulke baggers om de klei van de wanden van de put te schrapen.",
null,
null,
null,
new MapLocation(51.08931858773361, 4.3883514404296875, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/oude-bagger/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/impressie-van-de-handmatige-ontginning-fotoreeks.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/impressie-van-de-handmatige-ontginning-fotoreeks.jpg")),
}
),
new DefaultStop("Deltaweide",
"Deltaweide",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 31",
"Van bovenaf heb je hier een goed uitzicht op De Schorre en de ruime omgeving. De deltaweide heet zo omdat hier deltavliegers en parapenters komen oefenen. Tot voor enkele decennia werd hier nog klei afgestoken. In de zomer is hier het hoofdpodium van Tomorrowland.",
null,
null,
"parapent, deltavliegen, teambuilding, steenbakkerijnijverheid",
new MapLocation(51.09285298955352, 4.3861788511276245, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/deltaweide/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/deltaweide/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1900-1975.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1900-1975.jpg")),
}
),
new DefaultStop("One World brug",
"One World brug",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 00",
"One World by the People of Tomorrow is een kunstinstallatie van Arne Quinze in Provinciaal Recreatiedomein De Schorre. Ze werd in 2015 ontworpen naar aanleiding van 10 jaar Tomorrowland.",
"De kunstinstallatie is een permanente brug die een functie vervult als wandel- en fietspad doorheen het domein. Ze is geïnspireerd door de Nike van Samothrache, een beeld uit de klassieke oudheid dat de overwinning van de vrijheid voorstelt. De kunstinstallatie verbindt op een symbolische manier personen van over de hele wereld. Iedereen -waar ook ter wereld- kon een persoonlijke boodschap laten vereeuwigen in één van 210.000 planken van de installatie.",
new Stop.SubSection[] {
new Stop.SubSection("One World brug vervangt stuk historisch erfgoed.",
"De brug die de verschillende gebieden van het domein verbindt, is op de plaats gekomen van de voormalige brug of ramp van steenbakkerij Verstrepen. Hierlangs trok men de klei uit de kleiput met wagonnetjes naar de machinehal. De brug was dringend aan vervanging toe.")
},
"kunstwerk, Arne Quinze, Tomorrowland",
new MapLocation(51.09063601789197, 4.382901191711426, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/one-world-brug/2.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/de-schorre-fotoreeks.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/de-schorre-fotoreeks.jpg")),
}
),
new DefaultStop("Machinehal",
"Machinehal",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 00",
"Een hedendaags congrescentrum in industriële look, uitgerust met de nieuwste multimedia, met een aula voor 120 personen en verschillende vergaderzalen. Een verzorgde catering en combinatiemogelijkheden met buitenactiviteiten zijn een extra troef.",
"Congrescentrum de Pitte is ingericht in de vroegere machinehal van Steenbakkerij Verstrepen. Hier werd tot ca. 1970 de klei gekneed, geperst tot strengen en versneden tot baksteen. De basisstructuur is overeind gebleven bij deze hedendaagse renovatie: stalen structuren, rode baksteen en grote open ruimten zorgen voor een eigentijds loftgevoel en een trendy look. Je kunt er terecht voor congressen, vergaderingen, workshops en netwerkevenementen. De ruime parkeergelegenheid, rustgevende omgeving, verzorgde catering en combinatiemogelijkheden met buitenactiviteiten, maken van congrescentrum De Pitte jouw ideale partner!",
null,
"Congrescentrum, erfgoed, steenbakkerijnijverheid",
new MapLocation(51.088216769500264, 4.3816620111465445, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/machinehal/1.jpg")),
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1975-1990.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/productieproces-1975-1990.jpg")),
}
),
new DefaultStop("Droogloodsen",
"Droogloodsen",
"Schommelei", "1/1", "2850", "Boom",
null,
"In deze vlakte stonden vroeger de droogloodsen. Hier werden de kleivormen gedroogd vooraleer ze in de oven gebakken werden. De hele Rupelstreek stond vroeger bijna vol met dergelijke loodsen. De meeste van dergelijke loodsen waren vrij open zodat de wind er makkelijk doorheen kon blazen om beter te drogen. Hier en daar waren er ook droogloodsen waar men met warme lucht de stenen droogde om het proces sneller te latern verlopen. ",
null,
null,
null,
new MapLocation(51.08687568314563, 4.3763190507888785, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/portret-leona.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/portret-leona.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/2.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/3.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/droogloodsen/4.jpg")),
}
),
new DefaultStop("Afval",
"Afval",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 05",
"De schoorstenen in de Rupelstreek getuigen van een eens florerende baksteenindustrie. Om die stenen te vervaardigen moest men grote hoeveelheden klei delven en dat tast het landschap enorm aan.",
"De schoorstenen in de Rupelstreek getuigen van een eens florerende baksteenindustrie. Om die stenen te vervaardigen moest men grote hoeveelheden klei delven en dat tast het landschap enorm aan.",
null,
"afval",
new MapLocation(51.083441920502544, 4.374532699584961, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/afval.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/afval.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/afval/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/afval/2.jpg")),
}
),
new DefaultStop("Steenkaaien",
"Steenkaaien",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 05",
"De steiger en het ponton werden aangelegd aan de oude 'steenkaai' van Steenbakkerij Van Herck. Hier werd de baksteen getransporteerd naar Antwerpen om van daaruit te vertrekken naar het binnenland, Nederland, Engeland of zelfs de Verenigde Staten.",
"De steiger en het ponton werden met subsidies van Toerisme Vlaanderen aangelegd als toegang tot het Nautisch Bezoekerscentrum. In 2015 waren ze dringend aan renovatie toe. Het ponton werd hersteld; de brug verbreed voor meer comfort voor de passagiers.",
null,
"passagiersvaart, aanlegsteiger",
new MapLocation(51.082783107653015, 4.376506805419922, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/rivier-de-rupel.mp4"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/rivier-de-rupel.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/steenkaaien/1.jpg")),
new Image(URI.create("/webhdfs/v1/assets/images/app/routes/de-schorre/steenkaaien/2.jpg")),
}
),
new DefaultStop("Ringoven en fietsbelevingspunt",
"Ringoven en fietsbelevingspunt",
"Schommelei", "1/1", "2850", "Boom",
"+32 3 880 76 16",
"Je ziet hier nog de overblijfselen van een zogenaamde ringoven. Dit was een van de types ovens waar vroeger de bakstenen in gebakken werden. Men vulde de oven met klei in de vorm van bakstenen, met daartussen brandbaar materiaal. Dit stak men dan in brand om zo de stenen te bakken. Het vuur ging helemaal rond in de oven gedurende enkele weken totdat alle stenen gebakken waren.",
"Tegen 2018 wil de provincie dit gezellig pleintje renoveren tot een ontmoetingsplek voor recreatieve fietsers en wielerfanaten, met onder meer een toeristische balie, een wielercollectie, fietsenverhuur, een fietshersteldienst, elektrische oplaadpunten en een themacafé. De oude ringoven en andere steenbakkersrelicten worden in de nieuwe plannen geïntegreerd. ",
new Stop.SubSection[] {
new Stop.SubSection("Relicten ringoven De Roeck",
"Relicten van een ringoven. Maar voor de helft bewaard, het zuidelijke deel is gesloopt. Een ringoven is een ringvormige gang met toegangsdeuren langs de zijkanten –om de bakstenen in en uit te zetten- en stookgaten bovenaan. Dit nieuwe type oven uit het einde van de 19de eeuw zorgde ervoor dat er continu kon gebakken worden. Het vuur verplaatste zich doorheen de ring. Een ringoven werd nooit gedoofd, tenzij voor herstelwerkzaamheden.")
},
"erfgoed, steenbakkerijnijverheid",
new MapLocation(51.08330375592542, 4.3820321559906, DEFAULT_ZOOM_LEVEL),
new Media[] {
new Video(URI.create("http://www.youtube.com/embed/nI3IOSkS7Nw?rel=0&controls=0&&showinfo=0"),
URI.create("/webhdfs/v1/assets/videos/app/routes/de-schorre/fietsbelevingspunt-en-ringoven.jpg"))
}
),
};
}
catch (Exception e) {
Logger.error("Caught error while creating stop list for " + this.getName(), e);
}
this.stops = new LinkedHashMap<>();
for (Stop stop : STOPS_ARRAY) {
this.stops.put(stop.getSlug(), stop);
}
}
//-----PUBLIC METHODS-----
@Override
public String getName()
{
return "De Schorre";
}
@Override
public String getSlug()
{
return "de-schorre";
}
@Override
public String getIntroduction()
{
return "De Schorre is een put vol pit. Je vindt er een brede waaier aan recreatie- en sportmogelijkheden. Het is een prachtig provinciaal domein om te wandelen en te fietsen!";
}
@Override
public URI getPoster()
{
return POSTER;
}
@Override
public URI[] getImages()
{
return IMAGES;
}
@Override
public String getDescription()
{
return "<p>Provinciaal Recreatiedomein De Schorre is een geslaagde reconversie van een 75 ha grote kleiput naar een gebied met actieve recreatiemogelijkheden. Watersport, avonturentoren, sportvelden, speeltuin en wandelpaden met mooie uitzichtpunten zijn er de troeven. Een derde van het gebied is natuurgebied en een geliefde verzamelplaats voor waterjuffers, libellen, kikkers en watervogels.</p>";
}
@Override
public Region getRegion()
{
return Rupelstreek.INSTANCE;
}
@Override
public MapLocation getLocation()
{
return LOCATION;
}
@Override
public Map<String, Stop> getStops()
{
return stops;
}
@Override
public String getColor()
{
return "color-1";
}
@Override
public Accessibility[] getAccessibility()
{
return ACCESSIBILITY;
}
@Override
public String getLength()
{
return LENGTH_KMS+" km";
}
@Override
public String getDuration()
{
return "ca. "+LENGTH_HOURS+" uur";
}
@Override
public SurroundingEntry[] getSurroundingEntries()
{
return SurroundingEntry.SURROUNDING_ENTRIES_RUPELSTREEK;
}
//-----PROTECTED METHODS-----
//-----PRIVATE METHODS-----
}
|
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"
} |
29164_27 | package de.age.car2goil2k2;
import java.util.List;
import c2G.mobile.api.communication.Endpoint;
import c2G.mobile.api.objekts.Coordinate;
import c2G.mobile.api.objekts.GasStation;
import c2G.mobile.api.objekts.ParkingSpot;
import c2G.mobile.api.objekts.Vehicle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import de.gui.c2g.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Car2Go extends MapActivity implements OnTouchListener {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlaydot, itemizedOverlayCar, itemizedOverlayParkingSlot, itemizedOverlayGasStation;
private MyLocationOverlay myLocationOverlay;
private GeoPoint userlocation;
private Endpoint endpoint;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemapmain);
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
mapController.setCenter(new GeoPoint((int) (48.400833 * 1E6), (int) (9.987222* 1E6)));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
// myLocationOverlay.runOnFirstFix(new Runnable() {
// public void run() {
// mapView.getController().animateTo(myLocationOverlay.getMyLocation());
// }
// });
Drawable drawabledot = this.getResources().getDrawable(R.drawable.reddot);
Drawable drawableCar = this.getResources().getDrawable(R.drawable.car2go_icon_org_klein);
// Drawable drawableParkingSlot = null;
// Drawable drawableGasStation = null;
itemizedoverlaydot = new MyOverlays(drawabledot,this);
itemizedOverlayCar = new MyOverlays(drawableCar,this);
endpoint = new Endpoint();
// itemizedOverlayGasStation = new MyOverlays(drawableGasStation);
// itemizedOverlayParkingSlot = new MyOverlays(drawableParkingSlot);
// getAllFreeVehicle("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222));
createMarkerCars(endpoint.getAllFreeVehiclesInRange("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222)));
// getAllGasStations("ulm", "AdrianMarsch");
// getAllParkingSpots("ulm", "AdrianMarsch");
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
// int lat = (int) (location.getLatitude() * 1E6);
// int lng = (int) (location.getLongitude() * 1E6);
int lat = (int) (48.400833 * 1E6);
int lng = (int) (9.987222 * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
// createMarker();
// mapController.animateTo(point); // mapController.setCenter(point);
userlocation = point;
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedoverlaydot.adOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlaydot);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
// private void createMarkerCars(double latitude, double longitude) {
//
// int lat = (int) (latitude * 1E6);
// int lng = (int) (longitude * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
private void createMarkerCars(List<Vehicle> freeVehicle) {
for (int i = 0; i < freeVehicle.size(); i++) {
System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude()
+ "lon: " + freeVehicle.get(i).getPosition().getLongitude());
// createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude());
int lat = (int) (freeVehicle.get(i).getPosition().getLatitude() * 1E6);
int lng = (int) (freeVehicle.get(i).getPosition().getLongitude() * 1E6);
GeoPoint p = new GeoPoint(lat, lng);
OverlayItem overlayitem = new OverlayItem(p, freeVehicle.get(i).getPlate(), freeVehicle.get(i).getFuel());
itemizedOverlayCar.adOverlay(overlayitem);
if (itemizedOverlayCar.size() > 0) {
mapView.getOverlays().add(itemizedOverlayCar);
}
}
}
// private void createMarkerGasStations(Coordinate coordinate) {
//
// int lat = (int) (coordinate.getLatitude() * 1E6);
// int lng = (int) (coordinate.getLongitude() * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
// private void createMarkerParkingSlots(Coordinate coordinate) {
//
// int lat = (int) (coordinate.getLatitude() * 1E6);
// int lng = (int) (coordinate.getLongitude() * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
// private void createMarker() {
//
// int lat = (int) (48.7687 * 1E6);
// int lng = (int) (9.18293 * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
public void locateUser(View view) {
mapController.animateTo(userlocation);
}
// private List<Vehicle> getAllFreeVehicle(String location, String authorization,int range, Coordinate coordinate) {
//
// List<Vehicle> freeVehicle = endpoint.getAllFreeVehiclesInRange(location, authorization, range, coordinate);
//
// for (int i = 0; i < freeVehicle.size(); i++) {
// System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude()
// + "lon: " + freeVehicle.get(i).getPosition().getLongitude());
// createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude());
//
// }
//
// return freeVehicle;
//
// }
// private List<ParkingSpot> getAllParkingSpots(String location, String authorization) {
// List<ParkingSpot> allParkingSpots = endpoint.getAllParkingSpots(location, authorization);
//
// for (int i = 0; i < allParkingSpots.size(); i++) {
// createMarkerParkingSlots(allParkingSpots.get(i).getCoordinate());
// }
//
// return allParkingSpots;
// }
// private List<GasStation> getAllGasStations(String location, String authorization) {
// List<GasStation> allGasStations = endpoint.getAllPGasStations(location, authorization);
//
// for (int i = 0; i < allGasStations.size(); i++) {
// createMarkerGasStations(allGasStations.get(i).getCoordinate());
// }
//
// return allGasStations;
// }
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
Log.d(Car2Go.class.getCanonicalName(), "TAPPPPPPP");
}
return true;
}
} | Hft-Stuttgart-ILP/car2goil2k2 | src/de/age/car2goil2k2/Car2Go.java | 2,982 | // int lat = (int) (coordinate.getLatitude() * 1E6); | line_comment | nl | package de.age.car2goil2k2;
import java.util.List;
import c2G.mobile.api.communication.Endpoint;
import c2G.mobile.api.objekts.Coordinate;
import c2G.mobile.api.objekts.GasStation;
import c2G.mobile.api.objekts.ParkingSpot;
import c2G.mobile.api.objekts.Vehicle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import de.gui.c2g.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Car2Go extends MapActivity implements OnTouchListener {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlaydot, itemizedOverlayCar, itemizedOverlayParkingSlot, itemizedOverlayGasStation;
private MyLocationOverlay myLocationOverlay;
private GeoPoint userlocation;
private Endpoint endpoint;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemapmain);
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
mapController.setCenter(new GeoPoint((int) (48.400833 * 1E6), (int) (9.987222* 1E6)));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
// myLocationOverlay.runOnFirstFix(new Runnable() {
// public void run() {
// mapView.getController().animateTo(myLocationOverlay.getMyLocation());
// }
// });
Drawable drawabledot = this.getResources().getDrawable(R.drawable.reddot);
Drawable drawableCar = this.getResources().getDrawable(R.drawable.car2go_icon_org_klein);
// Drawable drawableParkingSlot = null;
// Drawable drawableGasStation = null;
itemizedoverlaydot = new MyOverlays(drawabledot,this);
itemizedOverlayCar = new MyOverlays(drawableCar,this);
endpoint = new Endpoint();
// itemizedOverlayGasStation = new MyOverlays(drawableGasStation);
// itemizedOverlayParkingSlot = new MyOverlays(drawableParkingSlot);
// getAllFreeVehicle("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222));
createMarkerCars(endpoint.getAllFreeVehiclesInRange("ulm", "AdrianMarsch", 1, new Coordinate(48.400833, 9.987222)));
// getAllGasStations("ulm", "AdrianMarsch");
// getAllParkingSpots("ulm", "AdrianMarsch");
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
// int lat = (int) (location.getLatitude() * 1E6);
// int lng = (int) (location.getLongitude() * 1E6);
int lat = (int) (48.400833 * 1E6);
int lng = (int) (9.987222 * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
// createMarker();
// mapController.animateTo(point); // mapController.setCenter(point);
userlocation = point;
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedoverlaydot.adOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlaydot);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
// private void createMarkerCars(double latitude, double longitude) {
//
// int lat = (int) (latitude * 1E6);
// int lng = (int) (longitude * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
private void createMarkerCars(List<Vehicle> freeVehicle) {
for (int i = 0; i < freeVehicle.size(); i++) {
System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude()
+ "lon: " + freeVehicle.get(i).getPosition().getLongitude());
// createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude());
int lat = (int) (freeVehicle.get(i).getPosition().getLatitude() * 1E6);
int lng = (int) (freeVehicle.get(i).getPosition().getLongitude() * 1E6);
GeoPoint p = new GeoPoint(lat, lng);
OverlayItem overlayitem = new OverlayItem(p, freeVehicle.get(i).getPlate(), freeVehicle.get(i).getFuel());
itemizedOverlayCar.adOverlay(overlayitem);
if (itemizedOverlayCar.size() > 0) {
mapView.getOverlays().add(itemizedOverlayCar);
}
}
}
// private void createMarkerGasStations(Coordinate coordinate) {
//
// int lat = (int) (coordinate.getLatitude() * 1E6);
// int lng = (int) (coordinate.getLongitude() * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
// private void createMarkerParkingSlots(Coordinate coordinate) {
//
// int lat<SUF>
// int lng = (int) (coordinate.getLongitude() * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
// private void createMarker() {
//
// int lat = (int) (48.7687 * 1E6);
// int lng = (int) (9.18293 * 1E6);
// GeoPoint p = new GeoPoint(lat, lng);
// OverlayItem overlayitem = new OverlayItem(p, "", "");
// itemizedOverlayCar.adOverlay(overlayitem);
// if (itemizedOverlayCar.size() > 0) {
// mapView.getOverlays().add(itemizedOverlayCar);
// }
// }
public void locateUser(View view) {
mapController.animateTo(userlocation);
}
// private List<Vehicle> getAllFreeVehicle(String location, String authorization,int range, Coordinate coordinate) {
//
// List<Vehicle> freeVehicle = endpoint.getAllFreeVehiclesInRange(location, authorization, range, coordinate);
//
// for (int i = 0; i < freeVehicle.size(); i++) {
// System.out.println("lat. " + freeVehicle.get(i).getPosition().getLatitude()
// + "lon: " + freeVehicle.get(i).getPosition().getLongitude());
// createMarkerCars(freeVehicle.get(i).getPosition().getLatitude(), freeVehicle.get(i).getPosition().getLongitude());
//
// }
//
// return freeVehicle;
//
// }
// private List<ParkingSpot> getAllParkingSpots(String location, String authorization) {
// List<ParkingSpot> allParkingSpots = endpoint.getAllParkingSpots(location, authorization);
//
// for (int i = 0; i < allParkingSpots.size(); i++) {
// createMarkerParkingSlots(allParkingSpots.get(i).getCoordinate());
// }
//
// return allParkingSpots;
// }
// private List<GasStation> getAllGasStations(String location, String authorization) {
// List<GasStation> allGasStations = endpoint.getAllPGasStations(location, authorization);
//
// for (int i = 0; i < allGasStations.size(); i++) {
// createMarkerGasStations(allGasStations.get(i).getCoordinate());
// }
//
// return allGasStations;
// }
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
Log.d(Car2Go.class.getCanonicalName(), "TAPPPPPPP");
}
return true;
}
} |
69566_5 | /*
* Copyright the State of the Netherlands
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package nl.overheid.aerius.shared.domain.v2.source.road;
/**
* NSL road speed types.
*/
public enum RoadSpeedType {
/**
* "buitenweg algemeen".
*
* Typisch buitenwegverkeer, een gemiddelde snelheid van ongeveer 60 km/h, gemiddeld ca. 0,2 stops per afgelegde km.
*/
NON_URBAN_TRAFFIC("B", "NON_URBAN_ROAD_GENERAL"),
/**
* "normaal stadsverkeer".
*
* Typisch stadsverkeer met een redelijke mate van congestie, een gemiddelde snelheid tussen de 15 en 30 km/h,
* gemiddeld ca. 2 stops per afgelegde km.
*/
URBAN_TRAFFIC_NORMAL("C", "URBAN_ROAD_NORMAL"),
/**
* "stagnerend stadsverkeer".
*
* Stadsverkeer met een grote mate van congestie, een gemiddelde snelheid kleiner dan 15 km/h, gemiddeld ca. 10 stops per afgelegde km.
*/
URBAN_TRAFFIC_STAGNATING("D", "URBAN_ROAD_STAGNATING"),
/**
* "stadsverkeer met minder congestie".
*
* Stadsverkeer met een relatief groter aandeel "free-flow" rijgedrag, een gemiddelde snelheid tussen de 30 en 45 km/h,
* gemiddeld ca. 1,5 stop per afgelegde km.
*/
URBAN_TRAFFIC_FREE_FLOW("E", "URBAN_ROAD_FREE_FLOW"),
/**
* "buitenweg nationale weg".
*
* Typisch buitenwegverkeer op een nationale weg.
*/
NATIONAL_ROAD("NATIONAL_ROAD", "NON_URBAN_ROAD_NATIONAL");
private final String legacyValue;
private final String roadTypeCode;
private RoadSpeedType(final String legacyValue, final String roadTypeCode) {
this.legacyValue = legacyValue;
this.roadTypeCode = roadTypeCode;
}
public static RoadSpeedType safeLegacyValueOf(final String snelheid) {
RoadSpeedType result = null;
for (final RoadSpeedType speedType : values()) {
if (speedType.legacyValue.equalsIgnoreCase(snelheid)) {
result = speedType;
}
}
return result;
}
public String getRoadTypeCode() {
return roadTypeCode;
}
}
| Hilbrand/IMAER-java | source/imaer-shared/src/main/java/nl/overheid/aerius/shared/domain/v2/source/road/RoadSpeedType.java | 894 | /**
* "stadsverkeer met minder congestie".
*
* Stadsverkeer met een relatief groter aandeel "free-flow" rijgedrag, een gemiddelde snelheid tussen de 30 en 45 km/h,
* gemiddeld ca. 1,5 stop per afgelegde km.
*/ | block_comment | nl | /*
* Copyright the State of the Netherlands
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package nl.overheid.aerius.shared.domain.v2.source.road;
/**
* NSL road speed types.
*/
public enum RoadSpeedType {
/**
* "buitenweg algemeen".
*
* Typisch buitenwegverkeer, een gemiddelde snelheid van ongeveer 60 km/h, gemiddeld ca. 0,2 stops per afgelegde km.
*/
NON_URBAN_TRAFFIC("B", "NON_URBAN_ROAD_GENERAL"),
/**
* "normaal stadsverkeer".
*
* Typisch stadsverkeer met een redelijke mate van congestie, een gemiddelde snelheid tussen de 15 en 30 km/h,
* gemiddeld ca. 2 stops per afgelegde km.
*/
URBAN_TRAFFIC_NORMAL("C", "URBAN_ROAD_NORMAL"),
/**
* "stagnerend stadsverkeer".
*
* Stadsverkeer met een grote mate van congestie, een gemiddelde snelheid kleiner dan 15 km/h, gemiddeld ca. 10 stops per afgelegde km.
*/
URBAN_TRAFFIC_STAGNATING("D", "URBAN_ROAD_STAGNATING"),
/**
* "stadsverkeer met minder<SUF>*/
URBAN_TRAFFIC_FREE_FLOW("E", "URBAN_ROAD_FREE_FLOW"),
/**
* "buitenweg nationale weg".
*
* Typisch buitenwegverkeer op een nationale weg.
*/
NATIONAL_ROAD("NATIONAL_ROAD", "NON_URBAN_ROAD_NATIONAL");
private final String legacyValue;
private final String roadTypeCode;
private RoadSpeedType(final String legacyValue, final String roadTypeCode) {
this.legacyValue = legacyValue;
this.roadTypeCode = roadTypeCode;
}
public static RoadSpeedType safeLegacyValueOf(final String snelheid) {
RoadSpeedType result = null;
for (final RoadSpeedType speedType : values()) {
if (speedType.legacyValue.equalsIgnoreCase(snelheid)) {
result = speedType;
}
}
return result;
}
public String getRoadTypeCode() {
return roadTypeCode;
}
}
|
167727_1 | /*
* This file is generated by jOOQ.
*/
package nl.overheid.aerius.emissionservice.jooq.template.tables.records;
import nl.overheid.aerius.emissionservice.jooq.template.tables.FarmLodgingFodderMeasureReductionFactors;
import org.jooq.Field;
import org.jooq.Record2;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;
/**
* Bevat de reductie factoren (factor 0..1) van de voer- en managementmaatregelen.
*
* Als er maatregelen op een stalsysteem worden toegepast, wordt van de combinatie
* van maatregelen eerst een enkele reductiefactor bepaalt. Deze reductiefactor
* wordt vervolgens toegepast op de totale emissie van het stalsysteem waarop
* gestapeld wordt, inclusief eventuele additionele en emissiereducerende
* staltechnieken die hierop gestapeld zijn.
*
* @column reduction_factor_floor De reductiefactor voor de emissie vanaf
* de vloer
* @column reduction_factor_cellar De reductiefactor voor de emissie uit de
* mestkelder
* @column reduction_factor_total De gecombineerde reductiefactor voor de
* emissie vanaf de vloer en uit de mestkelder
*
* @file source/database/src/main/sql/template/02_emission_factors/02-tables/farms.sql
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class FarmLodgingFodderMeasureReductionFactorsRecord extends UpdatableRecordImpl<FarmLodgingFodderMeasureReductionFactorsRecord> implements Record5<Integer, Short, Float, Float, Float> {
private static final long serialVersionUID = 1600934884;
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.farm_lodging_fodder_measure_id</code>.
*/
public void setFarmLodgingFodderMeasureId(Integer value) {
set(0, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.farm_lodging_fodder_measure_id</code>.
*/
public Integer getFarmLodgingFodderMeasureId() {
return (Integer) get(0);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.substance_id</code>.
*/
public void setSubstanceId(Short value) {
set(1, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.substance_id</code>.
*/
public Short getSubstanceId() {
return (Short) get(1);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_floor</code>.
*/
public void setReductionFactorFloor(Float value) {
set(2, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_floor</code>.
*/
public Float getReductionFactorFloor() {
return (Float) get(2);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_cellar</code>.
*/
public void setReductionFactorCellar(Float value) {
set(3, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_cellar</code>.
*/
public Float getReductionFactorCellar() {
return (Float) get(3);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_total</code>.
*/
public void setReductionFactorTotal(Float value) {
set(4, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_total</code>.
*/
public Float getReductionFactorTotal() {
return (Float) get(4);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record2<Integer, Short> key() {
return (Record2) super.key();
}
// -------------------------------------------------------------------------
// Record5 type implementation
// -------------------------------------------------------------------------
@Override
public Row5<Integer, Short, Float, Float, Float> fieldsRow() {
return (Row5) super.fieldsRow();
}
@Override
public Row5<Integer, Short, Float, Float, Float> valuesRow() {
return (Row5) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.FARM_LODGING_FODDER_MEASURE_ID;
}
@Override
public Field<Short> field2() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.SUBSTANCE_ID;
}
@Override
public Field<Float> field3() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_FLOOR;
}
@Override
public Field<Float> field4() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_CELLAR;
}
@Override
public Field<Float> field5() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_TOTAL;
}
@Override
public Integer component1() {
return getFarmLodgingFodderMeasureId();
}
@Override
public Short component2() {
return getSubstanceId();
}
@Override
public Float component3() {
return getReductionFactorFloor();
}
@Override
public Float component4() {
return getReductionFactorCellar();
}
@Override
public Float component5() {
return getReductionFactorTotal();
}
@Override
public Integer value1() {
return getFarmLodgingFodderMeasureId();
}
@Override
public Short value2() {
return getSubstanceId();
}
@Override
public Float value3() {
return getReductionFactorFloor();
}
@Override
public Float value4() {
return getReductionFactorCellar();
}
@Override
public Float value5() {
return getReductionFactorTotal();
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value1(Integer value) {
setFarmLodgingFodderMeasureId(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value2(Short value) {
setSubstanceId(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value3(Float value) {
setReductionFactorFloor(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value4(Float value) {
setReductionFactorCellar(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value5(Float value) {
setReductionFactorTotal(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord values(Integer value1, Short value2, Float value3, Float value4, Float value5) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached FarmLodgingFodderMeasureReductionFactorsRecord
*/
public FarmLodgingFodderMeasureReductionFactorsRecord() {
super(FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS);
}
/**
* Create a detached, initialised FarmLodgingFodderMeasureReductionFactorsRecord
*/
public FarmLodgingFodderMeasureReductionFactorsRecord(Integer farmLodgingFodderMeasureId, Short substanceId, Float reductionFactorFloor, Float reductionFactorCellar, Float reductionFactorTotal) {
super(FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS);
set(0, farmLodgingFodderMeasureId);
set(1, substanceId);
set(2, reductionFactorFloor);
set(3, reductionFactorCellar);
set(4, reductionFactorTotal);
}
}
| Hilbrand/emission-service | source/rest-service/src/main/generated/nl/overheid/aerius/emissionservice/jooq/template/tables/records/FarmLodgingFodderMeasureReductionFactorsRecord.java | 2,731 | /**
* Bevat de reductie factoren (factor 0..1) van de voer- en managementmaatregelen.
*
* Als er maatregelen op een stalsysteem worden toegepast, wordt van de combinatie
* van maatregelen eerst een enkele reductiefactor bepaalt. Deze reductiefactor
* wordt vervolgens toegepast op de totale emissie van het stalsysteem waarop
* gestapeld wordt, inclusief eventuele additionele en emissiereducerende
* staltechnieken die hierop gestapeld zijn.
*
* @column reduction_factor_floor De reductiefactor voor de emissie vanaf
* de vloer
* @column reduction_factor_cellar De reductiefactor voor de emissie uit de
* mestkelder
* @column reduction_factor_total De gecombineerde reductiefactor voor de
* emissie vanaf de vloer en uit de mestkelder
*
* @file source/database/src/main/sql/template/02_emission_factors/02-tables/farms.sql
*/ | block_comment | nl | /*
* This file is generated by jOOQ.
*/
package nl.overheid.aerius.emissionservice.jooq.template.tables.records;
import nl.overheid.aerius.emissionservice.jooq.template.tables.FarmLodgingFodderMeasureReductionFactors;
import org.jooq.Field;
import org.jooq.Record2;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;
/**
* Bevat de reductie<SUF>*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class FarmLodgingFodderMeasureReductionFactorsRecord extends UpdatableRecordImpl<FarmLodgingFodderMeasureReductionFactorsRecord> implements Record5<Integer, Short, Float, Float, Float> {
private static final long serialVersionUID = 1600934884;
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.farm_lodging_fodder_measure_id</code>.
*/
public void setFarmLodgingFodderMeasureId(Integer value) {
set(0, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.farm_lodging_fodder_measure_id</code>.
*/
public Integer getFarmLodgingFodderMeasureId() {
return (Integer) get(0);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.substance_id</code>.
*/
public void setSubstanceId(Short value) {
set(1, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.substance_id</code>.
*/
public Short getSubstanceId() {
return (Short) get(1);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_floor</code>.
*/
public void setReductionFactorFloor(Float value) {
set(2, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_floor</code>.
*/
public Float getReductionFactorFloor() {
return (Float) get(2);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_cellar</code>.
*/
public void setReductionFactorCellar(Float value) {
set(3, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_cellar</code>.
*/
public Float getReductionFactorCellar() {
return (Float) get(3);
}
/**
* Setter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_total</code>.
*/
public void setReductionFactorTotal(Float value) {
set(4, value);
}
/**
* Getter for <code>template.farm_lodging_fodder_measure_reduction_factors.reduction_factor_total</code>.
*/
public Float getReductionFactorTotal() {
return (Float) get(4);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record2<Integer, Short> key() {
return (Record2) super.key();
}
// -------------------------------------------------------------------------
// Record5 type implementation
// -------------------------------------------------------------------------
@Override
public Row5<Integer, Short, Float, Float, Float> fieldsRow() {
return (Row5) super.fieldsRow();
}
@Override
public Row5<Integer, Short, Float, Float, Float> valuesRow() {
return (Row5) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.FARM_LODGING_FODDER_MEASURE_ID;
}
@Override
public Field<Short> field2() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.SUBSTANCE_ID;
}
@Override
public Field<Float> field3() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_FLOOR;
}
@Override
public Field<Float> field4() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_CELLAR;
}
@Override
public Field<Float> field5() {
return FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS.REDUCTION_FACTOR_TOTAL;
}
@Override
public Integer component1() {
return getFarmLodgingFodderMeasureId();
}
@Override
public Short component2() {
return getSubstanceId();
}
@Override
public Float component3() {
return getReductionFactorFloor();
}
@Override
public Float component4() {
return getReductionFactorCellar();
}
@Override
public Float component5() {
return getReductionFactorTotal();
}
@Override
public Integer value1() {
return getFarmLodgingFodderMeasureId();
}
@Override
public Short value2() {
return getSubstanceId();
}
@Override
public Float value3() {
return getReductionFactorFloor();
}
@Override
public Float value4() {
return getReductionFactorCellar();
}
@Override
public Float value5() {
return getReductionFactorTotal();
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value1(Integer value) {
setFarmLodgingFodderMeasureId(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value2(Short value) {
setSubstanceId(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value3(Float value) {
setReductionFactorFloor(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value4(Float value) {
setReductionFactorCellar(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord value5(Float value) {
setReductionFactorTotal(value);
return this;
}
@Override
public FarmLodgingFodderMeasureReductionFactorsRecord values(Integer value1, Short value2, Float value3, Float value4, Float value5) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached FarmLodgingFodderMeasureReductionFactorsRecord
*/
public FarmLodgingFodderMeasureReductionFactorsRecord() {
super(FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS);
}
/**
* Create a detached, initialised FarmLodgingFodderMeasureReductionFactorsRecord
*/
public FarmLodgingFodderMeasureReductionFactorsRecord(Integer farmLodgingFodderMeasureId, Short substanceId, Float reductionFactorFloor, Float reductionFactorCellar, Float reductionFactorTotal) {
super(FarmLodgingFodderMeasureReductionFactors.FARM_LODGING_FODDER_MEASURE_REDUCTION_FACTORS);
set(0, farmLodgingFodderMeasureId);
set(1, substanceId);
set(2, reductionFactorFloor);
set(3, reductionFactorCellar);
set(4, reductionFactorTotal);
}
}
|
196376_15 | package pp2016.team13.client.gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import pp2016.team13.shared.Nachrichten.LoginNachricht;
/**
* Das Panel fuer die Anmeldung und die Startseite des Spiels
*
* @author Keser, Seyma, 5979919
*
*
*/
public class Anmeldung extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
// Anmelde Elemente
public JButton anmeldeButton;
JTextField textBenutzer;
JPasswordField passwortfeld;
JButton registrierButton;
JLabel benutzernameL;
JLabel passwortL;
boolean einloggen = false;
public String benutzername;
/**
* Erstellt das Panel mit ihren Buttons, Textfeldern, Hintergrund und macht
* die Buttons Benutzbar
*
* @author Keser, Seyma, 5979919
* @param fenster:
* Setzt das fenster fest, auf dem das Panel gezeichnet wird
*/
HindiBones fenster;
public Anmeldung(HindiBones fenster) {
this.fenster = fenster;
// Passwort Eingabe Feld
passwortfeld = new JPasswordField(15); // Erzeugen eines Passwortfeldes
// laenge 15
passwortfeld.setBounds(370, 250, 230, 35); // Grosse + Koord. wird
// festgelegt
this.add(passwortfeld);
// Benutzer Name Eingabe Feld
textBenutzer = new JTextField(15); // Erzeugen eines Textfeldes fuer
// Nicknamen
textBenutzer.setBounds(370, 200, 230, 35);// Grosse+Koord. wird
// festgelegt
textBenutzer.setBounds(370, 200, 230, 35);// Groesse+Koord. wird
// festgelegt
this.add(textBenutzer);
// Label /Beschriftungen
benutzernameL = new JLabel("Benutzername: "); // Erzeugen eines Labels
// heisst eines Textes
benutzernameL.setBounds(278, 190, 100, 50); // Groesse+ Koord. wird
// festgelegt
this.add(benutzernameL);
passwortL = new JLabel("Passwort: ");// " das selbe vorgehen wie mit
// username "
passwortL.setBounds(310, 240, 100, 50);
this.add(passwortL);
// Buttons u.a einlogg+ registrierungs Button
anmeldeButton = new JButton("Einloggen"); // Erzeugen eines Buttons
// "login"
anmeldeButton.setBounds(370, 320, 100, 50);// Grosse+Koord. wird
// festgelegt
this.add(anmeldeButton);
registrierButton = new JButton("Registrieren");// Erzeugen eines Buttons
// "registrieren"
registrierButton.setBounds(500, 320, 100, 50); // Groesse+Koord. wird
// festgelegt
this.add(registrierButton);
// Standard Einstellungen fuer das Anmelde Fenster
setSize(640, 400); // Groesse ensprechend an das Bild angepasst
setLocation(500, 280); // Zentrieren
this.setLayout(null);
// Eingabe Grau gesetzt
benutzernameL.setForeground(Color.GRAY);
passwortL.setForeground(Color.GRAY);
textBenutzer.setForeground(Color.GRAY);
textBenutzer.setText("");
// Anbindung an ActionListener
anmeldeButton.addActionListener(this);
registrierButton.addActionListener(this);
passwortfeld.addKeyListener(this);
// Standardaeinstellung
setVisible(true);
// Hintergrund Bild wird gesetzt
JLabel bildLabel = new JLabel();
bildLabel.setIcon(new ImageIcon("img/Bild.png"));
bildLabel.setBounds(0, 0, 640, 400);
this.add(bildLabel);
}
/**
* Beim druecken auf den Button anmelden, sollen Eingaben verglichen werden,
* anschliessend (vorr. richtige Eingabe) soll das Spielfenster geoeffnet
* werden.
*
* Alternativ Button Registrierung soll Register Klasse oeffnen siehe Rest
* da kommt auch die Verschluesselung zum Einsatz. Hier wird die Eingabe im
* Server verschluesselt und verglichen mit den im Nutzertext aufgelisteten
* Passwoertern und Nutzernamen.
*
*
* @author <Keser, Seyma, 5979919>
*
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == anmeldeButton) {
benutzername = textBenutzer.getText();
anmelden();
// Oeffnen der Registrierung
}
if (e.getSource() == registrierButton) {
try {
Thread.sleep(50);
new Registrierung(fenster);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
/**
* Anmeldung auch ueber Enter moeglich
*
* @author <Keser, Seyma, 5979919>
*
*/
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
anmelden();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
/**
*
* Anmelde Verbindung zum Client wird erzeugt von der Eingabe (passwort,
* benutzername)
*
* @author Keser, Seyma, 5979919
*/
public void anmelden() {
String nickname = textBenutzer.getText();
@SuppressWarnings("deprecation")
String pwt = passwortfeld.getText();
try {
LoginNachricht registrierung = new LoginNachricht(nickname, pwt, 0);
einloggen = fenster.client.einloggen(registrierung);
} catch (Exception e2) {
e2.printStackTrace();
}
if (einloggen == true) {
try {
// Systemnachricht wird versendet
Thread.sleep(100);
fenster.zeigeSpielfeld();
fenster.client.systemnachricht("Einloggen erfolgreich!");
fenster.client.systemnachricht("Willkommen, " + nickname);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Falsches Passwort oder Falscher Benutzername");
}
}
}
| HindiBones/project | src/pp2016/team13/client/gui/Anmeldung.java | 2,063 | // Groesse ensprechend an das Bild angepasst | line_comment | nl | package pp2016.team13.client.gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import pp2016.team13.shared.Nachrichten.LoginNachricht;
/**
* Das Panel fuer die Anmeldung und die Startseite des Spiels
*
* @author Keser, Seyma, 5979919
*
*
*/
public class Anmeldung extends JPanel implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
// Anmelde Elemente
public JButton anmeldeButton;
JTextField textBenutzer;
JPasswordField passwortfeld;
JButton registrierButton;
JLabel benutzernameL;
JLabel passwortL;
boolean einloggen = false;
public String benutzername;
/**
* Erstellt das Panel mit ihren Buttons, Textfeldern, Hintergrund und macht
* die Buttons Benutzbar
*
* @author Keser, Seyma, 5979919
* @param fenster:
* Setzt das fenster fest, auf dem das Panel gezeichnet wird
*/
HindiBones fenster;
public Anmeldung(HindiBones fenster) {
this.fenster = fenster;
// Passwort Eingabe Feld
passwortfeld = new JPasswordField(15); // Erzeugen eines Passwortfeldes
// laenge 15
passwortfeld.setBounds(370, 250, 230, 35); // Grosse + Koord. wird
// festgelegt
this.add(passwortfeld);
// Benutzer Name Eingabe Feld
textBenutzer = new JTextField(15); // Erzeugen eines Textfeldes fuer
// Nicknamen
textBenutzer.setBounds(370, 200, 230, 35);// Grosse+Koord. wird
// festgelegt
textBenutzer.setBounds(370, 200, 230, 35);// Groesse+Koord. wird
// festgelegt
this.add(textBenutzer);
// Label /Beschriftungen
benutzernameL = new JLabel("Benutzername: "); // Erzeugen eines Labels
// heisst eines Textes
benutzernameL.setBounds(278, 190, 100, 50); // Groesse+ Koord. wird
// festgelegt
this.add(benutzernameL);
passwortL = new JLabel("Passwort: ");// " das selbe vorgehen wie mit
// username "
passwortL.setBounds(310, 240, 100, 50);
this.add(passwortL);
// Buttons u.a einlogg+ registrierungs Button
anmeldeButton = new JButton("Einloggen"); // Erzeugen eines Buttons
// "login"
anmeldeButton.setBounds(370, 320, 100, 50);// Grosse+Koord. wird
// festgelegt
this.add(anmeldeButton);
registrierButton = new JButton("Registrieren");// Erzeugen eines Buttons
// "registrieren"
registrierButton.setBounds(500, 320, 100, 50); // Groesse+Koord. wird
// festgelegt
this.add(registrierButton);
// Standard Einstellungen fuer das Anmelde Fenster
setSize(640, 400); // Groesse ensprechend<SUF>
setLocation(500, 280); // Zentrieren
this.setLayout(null);
// Eingabe Grau gesetzt
benutzernameL.setForeground(Color.GRAY);
passwortL.setForeground(Color.GRAY);
textBenutzer.setForeground(Color.GRAY);
textBenutzer.setText("");
// Anbindung an ActionListener
anmeldeButton.addActionListener(this);
registrierButton.addActionListener(this);
passwortfeld.addKeyListener(this);
// Standardaeinstellung
setVisible(true);
// Hintergrund Bild wird gesetzt
JLabel bildLabel = new JLabel();
bildLabel.setIcon(new ImageIcon("img/Bild.png"));
bildLabel.setBounds(0, 0, 640, 400);
this.add(bildLabel);
}
/**
* Beim druecken auf den Button anmelden, sollen Eingaben verglichen werden,
* anschliessend (vorr. richtige Eingabe) soll das Spielfenster geoeffnet
* werden.
*
* Alternativ Button Registrierung soll Register Klasse oeffnen siehe Rest
* da kommt auch die Verschluesselung zum Einsatz. Hier wird die Eingabe im
* Server verschluesselt und verglichen mit den im Nutzertext aufgelisteten
* Passwoertern und Nutzernamen.
*
*
* @author <Keser, Seyma, 5979919>
*
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == anmeldeButton) {
benutzername = textBenutzer.getText();
anmelden();
// Oeffnen der Registrierung
}
if (e.getSource() == registrierButton) {
try {
Thread.sleep(50);
new Registrierung(fenster);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
/**
* Anmeldung auch ueber Enter moeglich
*
* @author <Keser, Seyma, 5979919>
*
*/
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
anmelden();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
/**
*
* Anmelde Verbindung zum Client wird erzeugt von der Eingabe (passwort,
* benutzername)
*
* @author Keser, Seyma, 5979919
*/
public void anmelden() {
String nickname = textBenutzer.getText();
@SuppressWarnings("deprecation")
String pwt = passwortfeld.getText();
try {
LoginNachricht registrierung = new LoginNachricht(nickname, pwt, 0);
einloggen = fenster.client.einloggen(registrierung);
} catch (Exception e2) {
e2.printStackTrace();
}
if (einloggen == true) {
try {
// Systemnachricht wird versendet
Thread.sleep(100);
fenster.zeigeSpielfeld();
fenster.client.systemnachricht("Einloggen erfolgreich!");
fenster.client.systemnachricht("Willkommen, " + nickname);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Falsches Passwort oder Falscher Benutzername");
}
}
}
|
45773_10 | package transformations;
import l2server.gameserver.datatables.SkillTable;
import l2server.gameserver.instancemanager.TransformationManager;
import l2server.gameserver.model.L2Transformation;
public class Zaken extends L2Transformation
{
private static final int[] SKILLS = {715, 716, 717, 718, 719, 5491, 619};
public Zaken()
{
// id, colRadius, colHeight
super(305, 16, 32);
}
@Override
public void onTransform()
{
if (getPlayer().getTransformationId() != 305 || getPlayer().isCursedWeaponEquipped())
{
return;
}
transformedSkills();
}
public void transformedSkills()
{
// Zaken Energy Drain (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(715, 4), false);
// Zaken Hold (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(716, 4), false);
// Zaken Concentrated Attack (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(717, 4), false);
// Zaken Dancing Sword (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(718, 4), false);
// Zaken Vampiric Rage
getPlayer().addSkill(SkillTable.getInstance().getInfo(719, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().addSkill(SkillTable.getInstance().getInfo(5491, 1), false);
// Transform Dispel
getPlayer().addSkill(SkillTable.getInstance().getInfo(619, 1), false);
getPlayer().setTransformAllowedSkills(SKILLS);
}
@Override
public void onUntransform()
{
removeSkills();
}
public void removeSkills()
{
// Zaken Energy Drain (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(715, 4), false);
// Zaken Hold (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(716, 4), false);
// Zaken Concentrated Attack (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(717, 4), false);
// Zaken Dancing Sword (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(718, 4), false);
// Zaken Vampiric Rage
getPlayer().removeSkill(SkillTable.getInstance().getInfo(719, 1), false, false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().removeSkill(SkillTable.getInstance().getInfo(5491, 1), false);
// Transform Dispel
getPlayer().removeSkill(SkillTable.getInstance().getInfo(619, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
public static void main(String[] args)
{
TransformationManager.getInstance().registerTransformation(new Zaken());
}
}
| Hl4p3x/L2T_Server | data/scripts/transformations/Zaken.java | 904 | // Zaken Dancing Sword (up to 4 levels)
| line_comment | nl | package transformations;
import l2server.gameserver.datatables.SkillTable;
import l2server.gameserver.instancemanager.TransformationManager;
import l2server.gameserver.model.L2Transformation;
public class Zaken extends L2Transformation
{
private static final int[] SKILLS = {715, 716, 717, 718, 719, 5491, 619};
public Zaken()
{
// id, colRadius, colHeight
super(305, 16, 32);
}
@Override
public void onTransform()
{
if (getPlayer().getTransformationId() != 305 || getPlayer().isCursedWeaponEquipped())
{
return;
}
transformedSkills();
}
public void transformedSkills()
{
// Zaken Energy Drain (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(715, 4), false);
// Zaken Hold (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(716, 4), false);
// Zaken Concentrated Attack (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(717, 4), false);
// Zaken Dancing Sword (up to 4 levels)
getPlayer().addSkill(SkillTable.getInstance().getInfo(718, 4), false);
// Zaken Vampiric Rage
getPlayer().addSkill(SkillTable.getInstance().getInfo(719, 1), false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().addSkill(SkillTable.getInstance().getInfo(5491, 1), false);
// Transform Dispel
getPlayer().addSkill(SkillTable.getInstance().getInfo(619, 1), false);
getPlayer().setTransformAllowedSkills(SKILLS);
}
@Override
public void onUntransform()
{
removeSkills();
}
public void removeSkills()
{
// Zaken Energy Drain (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(715, 4), false);
// Zaken Hold (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(716, 4), false);
// Zaken Concentrated Attack (up to 4 levels)
getPlayer().removeSkill(SkillTable.getInstance().getInfo(717, 4), false);
// Zaken Dancing<SUF>
getPlayer().removeSkill(SkillTable.getInstance().getInfo(718, 4), false);
// Zaken Vampiric Rage
getPlayer().removeSkill(SkillTable.getInstance().getInfo(719, 1), false, false);
// Decrease Bow/Crossbow Attack Speed
getPlayer().removeSkill(SkillTable.getInstance().getInfo(5491, 1), false);
// Transform Dispel
getPlayer().removeSkill(SkillTable.getInstance().getInfo(619, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
public static void main(String[] args)
{
TransformationManager.getInstance().registerTransformation(new Zaken());
}
}
|