How to sort a PriorityQueue with bool and date in java - priority-queue

How can you sort a PriorityQueue that all object with a bool with a 'true' value will be always on the top and the other with false value at the bottom and sorted with the date.
import java.text.DateFormat;
import java.util.*;
import static java.text.DateFormat.*;
import static java.util.Locale.*;
public class Patient implements Comparable<Patient> {
private String name;
private Date termin;
private boolean emergency;
Patient(String name, Date termin, boolean emergency) {
this.name = name;
this.termin = termin;
this.emergency = emergency;
}
public String getName(){
return name;
}
#Override
public String toString()
{
if (emergency)
{
return "** Notfall! ** \t "+ this.name;
}
else
{
DateFormat df = getDateInstance(SHORT, GERMANY);
DateFormat tf = DateFormat.getTimeInstance(SHORT,GERMANY);
return df.format(this.termin)+" "+tf.format(this.termin)+" \t "+this.name;
}
}
#Override
public int compareTo(Patient o) {
int i = 0;/*
if (this.equals(null)|| o.equals(null))
{
i= 0;
}
if ( this.emergency == o.emergency)
{
if(this.termin.getTime() < o.termin.getTime()){
i=1;
}else{
i= -1;
}
}
if (this.emergency || o.emergency)
{
i= -1;
}
return i;*/
}
}
RESULT:
(is not sorted right )
Warteschlange:
at.htl.WaitingRoom#5cad8086
Nächster Patient: ** Notfall! ** Ralph
Nächster Patient: ** Notfall! ** anonym
Nächster Patient: 21.10.11 09:15 Antonia Adam
Nächster Patient: 21.10.11 08:30 Cäcilia Chlum
Nächster Patient: 21.10.11 09:30 Bert Bauer
The result should be like this:
Warteschlange:
at.htl.WaitingRoom#5cad8086
Nächster Patient: ** Notfall! ** Ralph
Nächster Patient: ** Notfall! ** anonym
Nächster Patient: 21.10.11 08:30 Cäcilia Chlum
Nächster Patient: 21.10.11 09:15 Antonia Adam
Nächster Patient: 21.10.11 09:30 Bert Bauer

You want to first sort by emergencies, second by date:
#Override
public int compareTo(Patient o) {
if(emergency && !o.emergency)
return -1;
if(!emergency && o.emergency)
return 1;
// at this point emergency == o.emergency
// since Java 7 you can return Long.compare(termin.getTime(), o.termin.getTime()) instead of the following:
if(termin.getTime() < o.termin.getTime())
return -1;
if(termin.getTime() > o.termin.getTime())
return 1;
return 0;
}

Related

The bouncing ball under gravity does not stop at bounds

I am making an application and need a ball to bounce under gravity. The ball bounces fine but it never stops.
I tried printing the coordinate of the points where it stopped and what was the velocity. This is the output of one of the cases:
Found it... line 24. (0.00)i + (-0.01)j {14.14(0.79)} (-1.79, 651.57)
So in the ball stopped at height 651.67 while the bound was 600. Here's another case:
Found it... line 24. (0.00)i + (-0.01)j {14.14(0.79)} (-1.79, 1624.58)
Here's the code:
GUI.java
import java.util.Timer;
import java.util.TimerTask;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.stage.Stage;
public class GUI extends Application {
#Override
public void start(Stage theStage) throws Exception {
theStage.setTitle("Bouncy Ball");
Group root = new Group();
Scene theScene = new Scene(root);
theStage.setScene(theScene);
Canvas canvas = new Canvas(750, 600);
root.getChildren().add(canvas);
CircleSprite sprite = new CircleSprite(30, new Point(50, 50));
root.getChildren().add(sprite.image);
sprite.setVelocity(new Vector(new Point(10, 10)));
theStage.show();
theStage.setOnCloseRequest(e -> {
System.exit(0);
});
AnimationTimer gameLoop = new AnimationTimer() {
#Override
public void handle(long now) {
if (sprite.update(new Bounds(700, 600))) {
this.stop();
}
}
};
gameLoop.start();
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Vector velocity = sprite.getVelocity();
velocity.setYComponent(velocity.getYComponent() + 1);
if (Math.abs(sprite.getVelocity().getYComponent()) <= 0.01
&& sprite.getCentre().getY() + 2 * sprite.getRadius() >= 500) {
System.out.println("Found it... line 55");
cancel();
}
}
}, 0, 100);
}
public static void main(String[] args) {
launch(args);
}
}
CircleSprite.java
public class CircleSprite extends Circle {
public javafx.scene.shape.Circle image;
public CircleSprite(long radius, Point centre) {
super(radius, centre);
image = new javafx.scene.shape.Circle(centre.getX(), centre.getY(), radius);
}
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
setCentre(finalPos);
if (finalPos.getX() <= 0 || finalPos.getX() + 2 * getRadius() >= bounds.maxX) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
if (finalPos.getY() <= 0 || finalPos.getY() + 2 * getRadius() >= bounds.maxY) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}
}
Bounds.java
public class Bounds {
public double maxX;
public double maxY;
public Bounds(double maxX, double maxY) {
this.maxX = maxX;
this.maxY = maxY;
}
}
Circle.java
public class Circle extends Shape {
private long radius;
private Point centre;
public Circle(long radius, Point centre) {
this.radius = radius;
this.centre = centre;
this.setVelocity(new Vector(new Point(0.0d, 0.0d), new Point(0, 0)));
this.setMass(0);
this.setRestitution(1);
this.setAcceleration(new Vector(new Point(0, 0), new Point(0, 0)));
}
/*
* Testing for whether or not two circles intersect is very simple: take the
* radii of the two circles and add them together, then check to see if this sum
* is greater than the distance between the two circles.
*/
public boolean isColliding(Circle a, Circle b) {
long dist = a.getRadius() + b.getRadius();
// In general multiplication is a much cheaper operation than taking the square
// root of a value.
return ((dist * dist) < (a.getCentre().getX() - b.getCentre().getX())
* (a.getCentre().getX() - b.getCentre().getX())
+ (a.getCentre().getY() - b.getCentre().getY()) * (a.getCentre().getY() - b.getCentre().getY()));
}
public long getRadius() {
return this.radius;
}
public void setRadius(long radius) {
this.radius = radius;
}
public Point getCentre() {
return this.centre;
}
public void setCentre(Point centre) {
this.centre = centre;
}
}
Shape.java
public class Shape {
private Vector velocity;
private Vector acceleration;
private long mass;
private double invMass;
private float restitution;
public Vector getAcceleration() {
return this.acceleration;
}
public void setAcceleration(Vector acceleration) {
this.acceleration = acceleration;
}
public long getMass() {
return this.mass;
}
public void setMass(long mass) {
this.mass = mass;
this.setInvMass(mass);
}
public Vector getVelocity() {
return this.velocity;
}
public void setVelocity(Vector velocity) {
this.velocity = velocity;
}
public double getInvMass() {
return this.invMass;
}
private void setInvMass(long mass) {
if (mass == 0) {
invMass = Long.MAX_VALUE;
return;
}
this.invMass = 1.0d / (double) mass;
}
public float getRestitution() {
return this.restitution;
}
public void setRestitution(float restitution) {
this.restitution = restitution;
}
}
Vector.java
public class Vector {
private Point p1;
private Point p2;
private double xComponent;
private double yComponent;
private double angle;
private double magnitude;
/*
* The constructor makes a vector crossing through two points p1 and p2.
*
* #param p1 The source point(x1, x2)
*/
public Vector(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
this.xComponent = this.p2.getX() - this.p1.getX();
this.yComponent = this.p2.getY() - this.p1.getY();
this.angle = Math.atan2(this.yComponent, this.xComponent);
this.magnitude = Math.sqrt(this.xComponent * this.xComponent + this.yComponent * this.yComponent);
}
public Vector(Point p2) {
Point p1 = new Point(0, 0);
this.p1 = p1;
this.p2 = p2;
this.xComponent = this.p2.getX() - this.p1.getX();
this.yComponent = this.p2.getY() - this.p1.getY();
this.angle = Math.atan2(this.yComponent, this.xComponent);
this.magnitude = Math.sqrt(this.xComponent * this.xComponent + this.yComponent * this.yComponent);
}
public Vector(double magnitude, Vector unitVector) {
scaledProduct(magnitude, unitVector);
}
private void scaledProduct(double magnitude, Vector unitVector) {
Point point = new Point(magnitude * unitVector.getXComponent(), magnitude * unitVector.getYComponent());
new Vector(point);
}
public static Vector scalarProduct(double magnitude, Vector unitVector) {
Point point = new Point(magnitude * unitVector.getXComponent(), magnitude * unitVector.getYComponent());
return new Vector(point);
}
public static double dotProduct(Vector v1, Vector v2) {
return (v1.xComponent * v2.xComponent + v1.yComponent * v2.yComponent);
}
public static Vector sum(Vector v1, Vector v2) {
return new Vector(new Point(v1.getXComponent() + v2.getXComponent(), v1.getYComponent() + v2.getYComponent()));
}
public static Vector difference(Vector from, Vector vector) {
return new Vector(new Point(from.getXComponent() - vector.getXComponent(),
from.getYComponent() - vector.getYComponent()));
}
public static double angleBetween(Vector v1, Vector v2) {
return Math.acos(Vector.dotProduct(v1, v2) / (v1.getMagnitude() * v2.getMagnitude()));
}
public Point getP1() {
return this.p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return this.p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
public double getXComponent() {
return this.xComponent;
}
public void setXComponent(double d) {
this.xComponent = d;
}
public double getYComponent() {
return this.yComponent;
}
public void setYComponent(double d) {
this.yComponent = d;
}
public double getAngle() {
return this.angle;
}
public void setAngle(double angle) {
this.angle = angle;
}
public double getMagnitude() {
return this.magnitude;
}
public void setMagnitude(double length) {
this.magnitude = length;
}
#Override
public boolean equals(Object v) {
Vector vector = (Vector) v;
return ((this.xComponent == vector.xComponent) && (this.yComponent == vector.yComponent));
}
#Override
public String toString() {
return String.format("(%.2f)i + (%.2f)j {%.2f(%.2f)}", this.xComponent, this.yComponent, this.magnitude,
this.angle);
}
}
Point.java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public static double distance(Point p1, Point p2) {
return Math.sqrt(
(p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) + (p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return String.format("(%.2f, %.2f)", this.x, this.y);
}
}
What's wrong with the code? I know something is wrong with the exit condition in the GUI.java and CircleSprite.java but can't figure out what. There's two thing that is bothering me:
1. Why is the height out of bound when it stops?
2. Why does the x goes negative?
What happens here is the following (considering x dimension only; same applies to y as well):
The ball passes through the bounds at a speed v. You reverse the speed and decrease its magnitude. This can result in the new velocity not being high enough to get back into the bounds in the next update step and you reverse the velocity again decreasing it even more. This results in the ball moving back and forth in smaller and smaller steps outside of the bounds effectively giving the impression of it stopping.
Example with values:
Frame 1
vx = -16
x = 1
Frame 2
vx = 12
x = -15
Frame 3
vx = -9
x = -3
Frame 4
vx = -6.75
x = -12
...
There are 2 ways of fixing this:
Only update the speed, if the ball is moving in the direction that made it exceede the bounds.
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
setCentre(finalPos);
if ((finalPos.getX() <= 0 && velocity.getXComponent() < 0) || (finalPos.getX() + 2 * getRadius() >= bounds.maxX && velocity.getXComponent() > 0)) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
if ((finalPos.getY() <= 0 && velocity.getYComponent() < 0) || (finalPos.getY() + 2 * getRadius() >= bounds.maxY && velocity.getYComponent() > 0)) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}
Prevent the ball from ending up outside of the bounds in the first place
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
boolean invertX = true;
if (finalPos.getX() <= 0) {
// mirror on left
finalPos.setX(-finalPos.getX());
} else if (finalPos.getX() + 2 * getRadius() >= bounds.maxX) {
// mirror on right
finalPos.setX(2 * (bounds.maxX - 2 * getRadius()) - finalPos.getX());
} else {
invertX = false;
}
if (invertX) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
boolean invertY = true;
if (finalPos.getY() <= 0) {
// mirror on top
finalPos.setY(-finalPos.getY());
} else if (finalPos.getY() + 2 * getRadius() >= bounds.maxY) {
// mirror on bottom
finalPos.setY(2 * (bounds.maxY - 2 * getRadius()) - finalPos.getY());
} else {
invertY = false;
}
if (invertY) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
setCentre(finalPos);
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}

No such property: getToHour for class: OutagePolicyScript

I 've continously getting error:
2019-05-06 14:37:40,128 [EPI-TaskExecutor-1] ERROR
ScriptExecutionExceptionHandler.handleScriptError(31) - Script with id
[3e2fd082-62f3-46a2-8fca-71b1f9cef028] and label [Outage definition
script] reports an error: : No such property: getToHour for class:
OutagePolicyScript.
Outages.xml file is OK, and is placed together with outage.dtd file in correct location.
import java.util.List;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.hp.opr.api.scripting.Event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang3.ArrayUtils;
class OutagePolicyScript
{
Object syncObject = new Object();
final static String fileName = "/opt/HP/BSM/Temp/outages.xml"; // for Windows it will be: "d:/HPBSM/Temp/outages.xml";
final static Log s_log = LogFactory.getLog("com.hp.opr.epi.OutagePolicyScript");
List<OutageDefinition> outageDefinitions = new ArrayList<OutageDefinition>();
Thread loadXMLThread;
final boolean isSuppressEventsOrClose = true;
def init()
{
LoadOutagesFromXML r1 = new LoadOutagesFromXML();
loadXMLThread = new Thread(r1);
loadXMLThread.start();
s_log.debug("init finished");
}
def destroy()
{
s_log.debug("going to stop thread....");
loadXMLThread.interrupt();
}
def process(List<Event> events)
{
synchronized(syncObject) {
try
{
events.each {Event event ->
handleEventSuppressionIfNeeded(event, "EST");
//event.setTitle("Modified by CA/EPI: " + event.getTitle());
// always include following check for each event
if(Thread.interrupted())
throw new InterruptedException()
}
}
catch(InterruptedException e)
{
s_log.error("process of events interrupted", e);
}
}
}
private void handleEventSuppressionIfNeeded(Event event, String timezoneId)
{
// Calculate if event was received during the accepted time window.
Date timeRecieved = event.getTimeReceived();
Calendar cal = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone(timezoneId);
if (tz != null)
cal = Calendar.getInstance(tz);
cal.setTime(timeRecieved);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int dow = cal.get(Calendar.DAY_OF_WEEK);
//event.addCustomAttribute("hour", Integer.toString(hour));
//event.addCustomAttribute("minute", Integer.toString(minute));
//event.addCustomAttribute("day of week", Integer.toString(dow));
// go over all the outage definitions, and compare event attributes to the rule
outageDefinitions.each {OutageDefinition outage ->
if (outage.getIsActive()) {
s_log.debug("Checking active rule: " + outage.getDescription());
// check if the event's day of week is one of the outage definition days. in case the rule cross day, reduce 1 for day of week
if (ArrayUtils.contains(outage.getDays(), dow) || (outage.getCrossDay() && ArrayUtils.contains(outage.getDays(), (dow == 1) ? 7 : dow-1 ))) {
// check if event hour and minute are inside rule's from/to
// convert all configurations to minutes
// if the rule cross a day, then add to "to" 24 hours in order to compare from <= event_time < to
// if the rule cross a day AND event hour < "from" then it means the event is in the next day and need to add 24 hours too
int eventTimeInMin = ((hour < outage.getFromHour() && outage.getCrossDay()) ? hour + 24 : hour) * 60 + minute;
int fromInMin = outage.getFromHour() * 60 + outage.getFromMinute();
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();
if (eventTimeInMin >= fromInMin && eventTimeInMin < toInMin) {
s_log.debug("event time is within this outage rule, proceed to compare event's attributes");
boolean foundMatch = true;
Set<String> attributeNames = outage.getAttributesList().keySet();
attributeNames.each {String name ->
boolean attMatchResult;
// at the moment, all comparisons are using "EQ"
switch (name) {
case "title" : attMatchResult = compareEventAttributeToOutageRuleForcontains("title", event.getTitle(), outage.getAttributesList().get(name)); break;
case "application" : attMatchResult = compareEventAttributeToOutageRule("application", event.getApplication(), outage.getAttributesList().get(name)); break;
case "object" : attMatchResult = compareEventAttributeToOutageRule("object", event.getObject(), outage.getAttributesList().get(name)); break;
case "category" : attMatchResult = compareEventAttributeToOutageRule("category", event.getCategory(), outage.getAttributesList().get(name)); break;
case "subcategory" : attMatchResult = compareEventAttributeToOutageRule("subcategory", event.getSubCategory(), outage.getAttributesList().get(name)); break;
case "nodeHint" : attMatchResult = compareEventAttributeToOutageRuleForcontains("nodeHint", event.getNodeHints().getHint(), outage.getAttributesList().get(name)); break;
default : s_log.error("attribute name [" + name + "] from outages.xml is not supported");
}
s_log.debug("result for attribute [" + name + "] is: " + attMatchResult);
foundMatch &= attMatchResult;
}
s_log.debug("result after processing all attributes in the rule is: " + foundMatch);
if (foundMatch) {
if (isSuppressEventsOrClose)
event.addCustomAttribute("SuppressDueToOutageRule", outage.getDescription());
else
event.setState(LifecycleState.CLOSED);
}
}
else {
s_log.debug("Current rule doesnt match for the event's time, this rule will be skipped");
}
}
else {
s_log.debug("Current rule doesnt match for the event's day, this rule will be skipped");
}
}
}
}
private boolean compareEventAttributeToOutageRule(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
if (ruleValues.contains(eventAttValue)) {
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
private boolean compareEventAttributeToOutageRuleForcontains(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
Iterator<String> itr = ruleValues.iterator();
while (itr.hasNext()) {
if (eventAttValue.indexOf(itr.next()) != -1) { // check if the event attribute contains the rule's value
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
class LoadOutagesFromXML implements Runnable
{
long lastModifiedTime = -1;
public void run()
{
while (!Thread.interrupted()) {
s_log.debug("in running.... current time: " + new Date());
// lock the sync object
synchronized(syncObject) {
long before = System.currentTimeMillis();
readOutageFile();
long after = System.currentTimeMillis();
s_log.debug("Loading outages definitions from XML took [" + (after - before) + "] ms.");
}
Thread.sleep(60000); // 60 seconds
}
s_log.debug("thread interrupted....");
}
private void readOutageFile()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File f = new File(fileName);
if (f.lastModified() == lastModifiedTime) {
// the file wasnt changed, no need to reload file
s_log.debug("file LastModifiedTime didn't change, no need to reload configuration");
return;
}
// otherwise, clear previous results and reload XML file
outageDefinitions.clear();
s_log.debug("going to load outage.xml");
Document doc = db.parse(f);
NodeList outages = doc.getElementsByTagName("outage");
for (int i=0 ; i<outages.getLength() ; ++i) {
s_log.debug("handle outage: " + Integer.toString(i));
// going to handle specific outage definition
Element aOutage = (Element)outages.item(i);
Element aTimeWindow = (Element)(aOutage.getElementsByTagName("timeWindow").item(0));
outageDefinitions.add(new OutageDefinition(aOutage.getAttribute("description"),
aOutage.getAttribute("isEnabled"),
aTimeWindow.getElementsByTagName("days").item(0).getTextContent(),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), false),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), false),
parseAttributesFromXML((Element)aOutage.getElementsByTagName("eventsFilter").item(0))));
}
lastModifiedTime = f.lastModified();
s_log.debug("Going to keep lastModifiedTime as " + lastModifiedTime);
}
catch (Exception e) {
s_log.error("caught exception during parsing of outage.xml", e);
lastModifiedTime = -1;
}
}
private int parseIntFromStr(String str, boolean isHour)
{
String[] array = str.trim().split(":");
if (array.length != 2) {
s_log.debug("Bad time format, expect HH:MM format but recieved: " + str);
return -1;
}
if (isHour)
return Integer.parseInt(array[0]);
else
return Integer.parseInt(array[1]);
}
private Map<String, Set<String>> parseAttributesFromXML(Element eventsFilter)
{
Map<String, Set<String>> result = new HashMap<String, Set<String>>();
NodeList eventAttributes = eventsFilter.getElementsByTagName("eventAttribute");
for (int i=0 ; i<eventAttributes.getLength() ; ++i) {
NodeList attributeValues = eventAttributes.item(i).getElementsByTagName("value");
Set<String> values = new HashSet<String>(attributeValues.getLength());
for (int j=0 ; j<attributeValues.getLength() ; j++) {
values.add(attributeValues.item(j).getTextContent());
}
result.put(eventAttributes.item(i).getAttribute("name"), values);
}
return result;
}
}
class OutageDefinition
{
String description;
boolean isActive;
int[] days;
int fromHour;
int fromMinute;
int toHour;
int toMinute;
boolean crossDay;
Map<String, Set<String>> attributesList;
public OutageDefinition(String desc, String active, String outageDays, int oFromHour, int oFromMinute, int oToHour, int oToMinute, Map<String, Set<String>> oAttributes) {
this.description = desc;
this.isActive = Boolean.parseBoolean(active);
this.fromHour = oFromHour;
this.fromMinute = oFromMinute;
this.toHour = oToHour;
this.toMinute = oToMinute;
this.attributesList = oAttributes;
this.crossDay = false;
// check if time cross a day
if (this.fromHour > this.toHour) {
s_log.debug("in rule [" + this.description + "] found time condition that crosses midnight, adjust toHour accordingly");
this.crossDay = true;
}
this.days = getDaysFromString(outageDays);
}
private int[] getDaysFromString(String str)
{
String[] days = str.trim().split(",");
int[] result = new int[days.length];
for (int i=0 ; i<days.length ; ++i) {
switch (days[i]) {
case "Sunday" : result[i] = 1; break;
case "Monday" : result[i] = 2; break;
case "Tuesday" : result[i] = 3; break;
case "Wednesday" : result[i] = 4; break;
case "Thursday" : result[i] = 5; break;
case "Friday" : result[i] = 6; break;
case "Saturday" : result[i] = 7; break;
default : result[i] = -1; break;
}
}
return result;
}
public String getDescription() {
return description;
}
public boolean getIsActive() {
return isActive;
}
public int[] getDays() {
return days;
}
public int getFromHour() {
return fromHour;
}
public int getFromMinute() {
return fromMinute;
}
public int getToHour() {
return toHour;
}
public int getToMinute() {
return toMinute;
}
public Map<String, Set<String>> getAttributesList() {
return attributesList;
}
public boolean getCrossDay() {
return crossDay;
}
}
}
Look closely at this line. You must either call a method (outage.getToHour()) or access a property (outage.getToHour), but here you do both things. Choose what is correct
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();

Exception in Application constructor

I wanna write a Snake game with javaFX , but there is exception that I don't know about and I want to know how to fix it. ( i know it's not complete yet )
and I want to know , the class that extends Application ( with start override )
is exactly the main in other programs?
as you see , here is not static void main BC I didn't need, but if i want to add main where shoud i do?
it's the Exeption...
Exception in Application constructor
Exception in thread "main" java.lang.NoSuchMethodException: Main_Snake.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1819)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
and my code is :
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Nadia on 1/5/2016.
*/
public class Main_Snake extends Application{
Snake snake = new Snake();
Apple apple = new Apple();
Canvas canvas = new Canvas(800, 600);
boolean goNorth = true, goSouth, goWest, goEast;
int x, y = 0; // marbut be apple
boolean j = false;
// int gm_ov = 0; // vase game over shodan
ArrayList<Integer> X = new ArrayList<Integer>();
ArrayList<Integer> Y = new ArrayList<>();
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane b = new BorderPane(canvas);
Scene scene = new Scene(b, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
//KeyBoard(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getText()) {
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
play();
}
public void play(){
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 40_000_000) { // payin avordane sor#
snake.pos_S(); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
apple.pos_A();
apple.random_Pos();
snake.Move();
lastUpdate = now; // sor#
}
}
};
timer.start();
}
/* public void KeyBoard(Scene scene) {
}*/
}
class Apple extends Main_Snake {
public void random_Pos() {
if (j == false) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) (Math.random() * 790 + 1);
y = (int) (Math.random() * 590 + 1);
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide*/
j = true;
}
}
public void pos_A() {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(x, y, 10, 10);
}
public void Point() {
if (X.get(0) == x && Y.get(0) == y) {
j = false;
}
}
}
class Snake extends Main_Snake {
Snake(){ //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
}
public void pos_S(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
apple.pos_A();
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--)
gc.fillRect(X.get(i), Y.get(i), 10, 10);
}
public void Move(){
int Px = X.get(X.size() - 1);
int Py = Y.get(Y.size() - 1);
for (int z = X.size() - 1 ; z > 0 ; z--){
X.remove(z);
X.add(z , X.get(z-1) ) ;
Y.remove(z);
Y.add(z , Y.get(z-1) ) ;
}
if (goNorth) {
Y.add(0 , Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0 , Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0 , X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0 , X.get(0) - 10);
X.remove(1);
}
apple.Point(); // emtiaz gerefte
if ( j == false) {
X.add(Px);
Y.add(Py);
}
if ( X.get(0) > 790 ){
X.remove(0);
X.add(0 , 0);
}
if ( X.get(0) < 0 ){
X.remove(0);
X.add(0 , 800);
}
if ( Y.get(0) > 590 ){
Y.remove(0);
Y.add(0 , 0);
}
if ( Y.get(0) < 0 ){
Y.remove(0);
Y.add(0 , 600);
}
}
}
The standard Oracle Java Runtime Environment can execute Application subclasses directly from the command line, even if they do not contain a main method. So assuming you are using a standard JRE, from the command line you can execute
java Main_Snake
and it will run (assuming no other errors, etc).
Other environments, and most IDEs, don't support this execution mode, so if you want to run in those environments (including running in Eclipse, for example), you need a main(...) method which launches your JavaFX application. So just add
public static void main(String[] args) {
launch(args);
}
to the Main_Snake class.

use JMX(jconsole) to monitor JVM GC.how to get young GC info and full GC info?

i can get " PS Scavenge ,PS MarkSweep" attributes: CollectionCount,CollectionTime through JMX .but my questiong is :"
which one is young gc info ?which one is full gc info ?
" how can i get more details on GC.
jstat is jstat GC info .the twos are Different.
the following bean:
import java.io.Serializable;
public class PerformanceBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6021047939070147624L;
/*
* Survivor space 0 utilization as a percentage of the space's current
* capacity.
*/
public final long jstatS0;
/*
* Survivor space 1 utilization as a percentage of the space's current
* capacity.
*/
public final long jstatS1;
/*
* Eden space utilization as a percentage of the space's current capacity.
*/
public final long jstatE;
/*
* Old space utilization as a percentage of the space's current capacity.
*/
public final long jstatO;
/*
* Permanent space utilization as a percentage of the space's current
* capacity.
*/
public final long jstatP;
/* Number of young generation GC events. */
public final long jstatYGC;
/* Young generation garbage collection time. */
public final long jstatYGCT;
/* Number of full GC events. */
public final long jstatFGC;
/* Full garbage collection time. */
public final long jstatFGCT;
/* Total garbage collection time. */
public final long jstatGCT;
/* Operation System info */
public final int availableProcessors;
public final double systemLoadAverage;
public final String osName;
public final String arch;
/*
*
* Below is a picture showing an example of a memory pool:
*<p>
*<pre>
* +----------------------------------------------+
* +//////////////// | +
* +//////////////// | +
* +----------------------------------------------+
*
* |--------|
* init
* |---------------|
* used
* |---------------------------|
* committed
* |----------------------------------------------|
* max
*<pre>
*/
/*
* Memory Usage--heapMemoryUsage
*/
public final long initHeap;
public final long usedHeap;
public final long committedHeap;
public final long maxHeap;
/* Memory Usage--nonHeapMemoryUsage */
public final long initNonHeap;
public final long usedNonHeap;
public final long committedNonHeap;
public final long maxNonHeap;
public static class Builder {
// Optional parameters - initialized to default values
private long jstatS0 = 0;
private long jstatS1 = 0;
private long jstatE = 0;
private long jstatO = 0;
private long jstatP = 0;
private long jstatYGC = 0;
private long jstatYGCT = 0;
private long jstatFGC = 0;
private long jstatFGCT = 0;
private long jstatGCT = 0;
public int availableProcessors = 0;
public double systemLoadAverage = 0;
public String osName = "";
public String arch = "";
private long initHeap = 0;
private long usedHeap = 0;
private long committedHeap = 0;
private long maxHeap = 0;
private long initNonHeap = 0;
private long usedNonHeap = 0;
private long committedNonHeap = 0;
private long maxNonHeap = 0;
public Builder jstatS0(long val) {
jstatS0 = val;
return this;
}
public Builder jstatS1(long val) {
jstatS1 = val;
return this;
}
public Builder jstatE(long val) {
jstatE = val;
return this;
}
public Builder jstatO(long val) {
jstatO = val;
return this;
}
public Builder jstatP(long val) {
jstatP = val;
return this;
}
public Builder jstatYGC(long val) {
jstatYGC = val;
return this;
}
public Builder jstatYGCT(long val) {
jstatYGCT = val;
return this;
}
public Builder jstatFGC(long val) {
jstatFGC = val;
return this;
}
public Builder jstatFGCT(long val) {
jstatFGCT = val;
return this;
}
public Builder jstatGCT(long val) {
jstatGCT = val;
return this;
}
public Builder availableProcessors(int val) {
availableProcessors = val;
return this;
}
public Builder systemLoadAverage(double val) {
systemLoadAverage = val;
return this;
}
public Builder arch(String val) {
arch = val;
return this;
}
public Builder osName(String val) {
osName = val;
return this;
}
public Builder initHeap(long val) {
initHeap = val;
return this;
}
public Builder usedHeap(long val) {
usedHeap = val;
return this;
}
public Builder committedHeap(long val) {
committedHeap = val;
return this;
}
public Builder maxHeap(long val) {
maxHeap = val;
return this;
}
public Builder initNonHeap(long val) {
initNonHeap = val;
return this;
}
public Builder usedNonHeap(long val) {
usedNonHeap = val;
return this;
}
public Builder committedNonHeap(long val) {
committedNonHeap = val;
return this;
}
public Builder maxNonHeap(long val) {
maxNonHeap = val;
return this;
}
public PerformanceBean build(){
return new PerformanceBean(this);
}
}
private PerformanceBean(Builder builder) {
jstatS0 = builder.jstatS0;
jstatS1 = builder.jstatS1;
jstatE = builder.jstatE;
jstatO = builder.jstatO;
jstatP = builder.jstatP;
jstatYGC = builder.jstatYGC;
jstatYGCT = builder.jstatYGCT;
jstatFGC = builder.jstatFGC;
jstatFGCT = builder.jstatFGCT;
jstatGCT = builder.jstatGCT;
availableProcessors = builder.availableProcessors;
systemLoadAverage = builder.systemLoadAverage;
osName = builder.osName;
arch = builder.arch;
initHeap = builder.initHeap;
usedHeap = builder.usedHeap;
committedHeap = builder.committedHeap;
maxHeap = builder.maxHeap;
initNonHeap = builder.initNonHeap;
usedNonHeap = builder.usedNonHeap;
committedNonHeap = builder.committedNonHeap;
maxNonHeap = builder.maxNonHeap;
}
// public static long getSerialversionuid() {
// return serialVersionUID;
// }
// public long getJstatS0() {
// return jstatS0;
// }
// public long getJstatS1() {
// return jstatS1;
// }
// public long getJstatE() {
// return jstatE;
// }
// public long getJstatO() {
// return jstatO;
// }
// public long getJstatP() {
// return jstatP;
// }
// public long getJstatYGC() {
// return jstatYGC;
// }
// public long getJstatYGCT() {
// return jstatYGCT;
// }
// public long getJstatFGC() {
// return jstatFGC;
// }
// public long getJstatFGCT() {
// return jstatFGCT;
// }
// public long getJstatGCT() {
// return jstatGCT;
// }
// public double getSystemLoadAverage() {
// return systemLoadAverage;
// }
// public String getOsName() {
// return osName;
// }
// public String getArch() {
// return arch;
// }
// public long getInitHeap() {
// return initHeap;
// }
// public long getUsedHeap() {
// return usedHeap;
// }
// public long getCommittedHeap() {
// return committedHeap;
// }
// public long getMaxHeap() {
// return maxHeap;
// }
// public long getInitNonHeap() {
// return initNonHeap;
// }
// public long getUsedNonHeap() {
// return usedNonHeap;
// }
// public long getCommittedNonHeap() {
// return committedNonHeap;
// }
// public long getMaxNonHeap() {
// return maxNonHeap;
// }
}

Passing Objects through Heap Sort

Having issues trying to pass an object class to be sorted via Heap Sort. Basically I have a class which holds employee data such as names, address, phone numbers and employee ID. We are to use Heap Sort to pass this class as a object and sort it by employee ID. My main issue is converting my heap sort structures to where they can take objects. This is for a beginning data structures course so we're not allowed to use advanced techniques. My road block is I'm stumped as to how to pass my objects into the heap sort methods which currently only take primitive data types.
Office Class:
public class Office_Staff
{
public String Name , Dept , Phonenumber;
public int Id, years;
Office_Staff()
{
Id = ("");
Name = ("");
Dept = ("");
Phonenumber = ("");
years = 0;
}
Office_Staff(int empid ,String empname, String empdept , String empphone, int service)
{
Id = empid;
Name = empname;
Dept = empdept;
Phonenumber = empphone;
years = service;
}
public void setId(int empid)
{
Id = empid;
}
public void setName(String empname)
{
Name = empname;
}
public void setDept(String empdept)
{
Dept = empdept;
}
public void setPhone(String empphone)
{
Phonenumber = empphone;
}
public void setYears(int service)
{
years = service;
}
public String getId()
{
return Id;
}
public String getName()
{
return Name;
}
public String getDept()
{
return Dept;
}
public String getPhone()
{
return Phonenumber;
}
public int getYears()
{
return years;
}
public String toString()
{
String str = "Office_Staff Name : " + Name + "Office_Staff ID : " + Id +
"Office_Staff Deaprtment : " + Dept + "Office_Staff Phone Number : "
+ Phonenumber + "Years Active : " + years;
return str;
}
}
Heap Sort:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
class zNode
{
private int iData;
public zNode(int key)
{
iData = key;
}
public int getKey()
{
return iData;
}
public void setKey(int k)
{
iData = k;
}
}
class HeapSort
{
private int [] currArray;
private int maxSize;
private int currentSize;
private int currIndex;
HeapSort(int mx)
{
maxSize = mx;
currentSize = 0;
currArray = new int[maxSize];
}
//buildheap
public boolean buildHeap(int [] currArray)
{
int key = currIndex;
if(currentSize==maxSize)
return false;
int newNode = key;
currArray[currentSize] = newNode;
siftUp(currArray , currentSize++);
return true;
}
//siftup
public void siftUp(int [] currArray , int currIndex)
{
int parent = (currIndex-1) / 2;
int bottom = currArray[currIndex];
while( currIndex > 0 && currArray[parent] < bottom )
{
currArray[currIndex] = currArray[parent];
currIndex = parent;
parent = (parent-1) / 2;
}
currArray[currIndex] = bottom;
}
//siftdown
public void siftDown(int [] currArray , int currIndex)
{
int largerChild;
int top = currArray[currIndex];
while(currIndex < currentSize/2)
{
int leftChild = 2*currIndex+1;
int rightChild = leftChild+1;
if(rightChild < currentSize && currArray[leftChild] < currArray[rightChild] )
largerChild = rightChild;
else
largerChild = leftChild;
if( top >= currArray[largerChild] )
break;
currArray[currIndex] = currArray[largerChild];
currIndex = largerChild;
}
currArray[currIndex] = top;
}
//remove max element
public int removeMaxElement(int [] currArray)
{
int root = currArray[0];
currArray[0] = currArray[--currentSize];
siftDown(currArray , 0);
return root;
}
//heapsort
private void _sortHeapArray(int [] currArray)
{
while(currentSize != 0)
{
removeMaxElement(currArray);
}
}
public void sortHeapArray()
{
_sortHeapArray(currArray);
}
//hepify
private int[] heapify(int[] currArray)
{
int start = (currentSize) / 2;
while (start >= 0)
{
siftDown(currArray, start);
start--;
}
return currArray;
}
//swap
private int[] swap(int[] currArray, int index1, int index2)
{
int swap = currArray[index1];
currArray[index1] = currArray[index2];
currArray[index2] = swap;
return currArray;
}
//heapsort
public int[] _heapSort(int[] currArray)
{
heapify(currArray);
int end = currentSize-1;
while (end > 0)
{
currArray = swap(currArray,0, end);
end--;
siftDown(currArray, end);
}
return currArray;
}
public void heapSort()
{
_heapSort(currArray);
}

Resources