Set fixed interval at Y-axis ChartJS Primefaces - primefaces

How do i set a fixed interval at the Y-axis with ChartJS Primefaces using LineChartModel, its is using a interval of 5 but i needed to make a 3 interval. I tried using extender with javascript but it didnt work, tried using methods but couldnt find the right methods.

You can use stepSize in the ChartsJS model object provided for Axes in the PrimeFaces model.
See: https://github.com/primefaces/primefaces/blob/master/src/main/java/org/primefaces/model/charts/axes/cartesian/linear/CartesianLinearTicks.java
/**
* Used to provide cartesian linear ticks. CartesianLinearTicks extends {#link CartesianTicks}
*/
public class CartesianLinearTicks extends CartesianTicks {
private static final long serialVersionUID = 1L;
private boolean beginAtZero;
private Number min;
private Number max;
private Number maxTicksLimit;
private Number precision;
private Number stepSize;
private Number suggestedMax;
private Number suggestedMin;

Related

Explanation to why two constructors are required

Unfortunately, I do not feel confident with my understanding of default constructors.
I have searched extensively to find a resource that provides an explanation to adhere to my personal learning curve of the Java language. However, upon completing an assignment, I feel I may not be meeting the assignment criteria due to my own feeling of redundancy to need for a default constructor. This is why i feel like i am misinterpreting the concept of different types of constructors all together.
I have created two constructors as the assignment requires. One that takes in no parameters and initializes instance variables to a default value. And another that takes in parameters to give values to the object variables when the new object is created in the main method.
Why am I creating a default constructor for the object if the default is never used in the main method? Below is a sample of my code:
public class Circle {
private double x; // declaring variable to hold value of x coordinate
private double y; // Variable to hold value of y coordinate
private double r; // Variable to hold value of the radius of a circle
/* default constructor */
Circle() {
x = 0.0;
y = 0.0;
r = 0.0;
}
/* constructor takes in three parameters and sets values for variables x, y, and r */
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
// test class created for main method
public class TestCircle {
public static void main (String[] args){
Circle c1 = new Circle(2.0,3.0,9.0);
System.out.println();
System.out.println(" A circle object has been created with the following attributes:");
c1.printAttributes();
System.out.println();
System.out.println("The circle is tested for the maximum radius of 8.0...");
c1.setRadius(8.0);
System.out.println();
System.out.println("... since the radius is more than the allowable maximum, the new attributes for the Circle are:");
c1.printAttributes();
System.out.println();
System.out.println("The area of the Circle is " + c1.area());
System.out.println("The Circumference of the circle is " + c1.circumference());
System.out.println();
System.out.println("The origin of the circle is now moved by a specified amount...");
c1.move(6,-7);
System.out.println();
System.out.println("The new attributes of the circle are:");
c1.printAttributes();
System.out.println();
System.out.println("Testing if the point (10,-20) is inside the circle...");
System.out.println();
if (c1.isInside(10,-20)){
System.out.println("The point (10,-20) is inside the circle");
}
else {
System.out.println("The point (10,-20) is not inside the circle");
}
} // end of main
} // end of class
If you don’t use it you should delete it. Sometimes you will need to create empty objects in order to set attributes a posteriori, but if you are not using it at all there is no point to have it
The point of making default constructors is sometimes for back end stuff and is considered a "good programming practice" no you don't use the default constructor here in your main and in fact your code would run just fine with no default constructor comment it out and re run your tester you will see it works fine.

Collision bit reaches its maximum value while Initialization in LIBGDX

I am using Category_bits for detecting collision in LIBGDX. I have used all the values ranging from 0 to 16384 . Since we have to use the power of 2 while initializing the values, I have exceeded the limit and I am not able to initialize any bits anymore. The range for short_ bit is 0 to 16384 and if I use the next multiple of that number, after type casting it to a short value, the Category_bits doesn't detect collision between objects. Nothing happens when the object collides when I set the value greater than 16384.
Here is how I initialize the values,
public static final short x = 0;
public static final short y = 1;
public static final short z = 2;
public static final short a = 4;
public static final short b = 8;
public static final short c = 16;
.....
public static final short d = 16384;
public static final short e = (short) 32768; // exceeded the limit so type casted the number to short
When I type cast and use it, nothing collision detection happens. I have to detect collision in many things in my game so I need the solution to get rid of this problem. Please help. Thanks in advance.
I would strongly advise re-checking over your code and decide whether you actually need that many different categories. Even if you have that many different types of objects I suspect you could group together those which have the same collision filters into just one bit, you can then use other ways of identifying which "type" of entity is involved in a collision.
If you do really need to use that many different objects then the Box2d World class has a method setContactFilter(ContactFilter filter) which will allow you to specify a custom ContactFilter. This contains a shouldCollide(Fixture a, Fixture b) which returns true if a and b should collide and vice versa.
short also worked for me with minus numbers, because it reaches from -32768 till 32767 so you can also use
-32678, -16384 and so on.
I don't know how to use the contact filters, but I work with UserData which also works pretty good for me.
when you create your body I wrote something like this:
b2body.createFixture(fdef).setUserData("something");
and in my collision detection I used something like this:
public class WorldContactListener implements ContactListener{
#Override
public void beginContact(Contact contact) {
Fixture fixA = contact.getFixtureA();
Fixture fixB = contact.getFixtureB();
int cdef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits;
switch(cdef) {
case BreedingSeason.HERO_BIT | BreedingSeason.TRAMPOLIN_BIT:
if(fixA.getUserData() == "somethingElse" && fixB.getUserData() == "something") {
...
} else if(fixB.getUserData() == "somethingElse" && fixA.getUserData() == "something") {
...
}
break;
}
and don't forget the break after each case in the switch ;)
i hope this helps you

Accuracy of Task.Delay

I'm developing Windows 10 Universal App in C#/Xaml, I'm using await Task.Delay(delayInMilliseconds) to suspend a method for given time. My scenario is somewhat realtime, so it's very sensitive to time changes, and I need to make sure that when i suspend a method for let's say 8 millisecods it is suspended for 8 millisecods. I have noticed that the actual time span for which ** Task.Delay ** suspends the method differes from what is passed as delay parameter, for 1 up to 30 ms, the length of "deviation" being different in each call. So, when I want to sleep for 8 milliseconds, my system sleeps for 9 to 39 milliseconds, and this completly ruins my scenario.
So, my question what is the best way to substitute ** Task.Delay ** and to achieve good precision? For the time being I use this method:
public static void Delay1(int delay)
{
long mt = delay * TimeSpan.TicksPerMillisecond;
Stopwatch s = Stopwatch.StarNew();
while (true)
{
if (s.Elapsed.TotalMilliseconds > delay)
{
return;
}
}
}
but it guees it consumes a lot of resources, that is 100% of a processor's core. If an user has small number of processor's cores, this would be very insufficient.
According to msdn it's not possible to achieve more accuracy due to system clock resolution:
This method depends on the system clock. This means that the time
delay will approximately equal the resolution of the system clock if
the millisecondsDelay argument is less than the resolution of the
system clock, which is approximately 15 milliseconds on Windows
systems.
Seems like I've found a sattisfactory solution: using ManualResetEvent(false).WaitOne(delay) instead of await Task.Delay(delayInMilliseconds).
I've used following code to test both methods:
async void Probe()
{
for (int i = 0; i < 1000; i++)
{
// METHOD 1
await Task.Delay(3);
// METHOD 2
new System.Threading.ManualResetEvent(false).WaitOne(3);
}
}
The code above should take exactly 3 seconds to execute. With METHOD 2 it took around 3300 ms, so the error is 0.3 ms per call. Acceptable for me. But the METHOD 1 took around 15 seconds (as mentioned by others and explained above) to execute which gives totally unacceptable error for my scenario.
EDIT: WaitOne() is a blocking call, so you'll probably want to run it as a task to get it off the UI thread (or any other thread with a message pump). #Abel has pointed out another high-res timer approach that is already baked into a task and will run in an alternate thread as shown here: (https://stackoverflow.com/a/62588903/111575). That approach makes cpu-intensive calls to Thread.Spinwait() and Thread.Sleep(0) for small intervals.
You should use multi-media timers. Those are much accurate.
Take a look here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/2024e360-d45f-42a1-b818-da40f7d4264c/accurate-timer
After working hard I found a solution to sleep the thread for specific time and the error is just 3 to 4 microseconds on my Core 2 Duo CPU 3.00 GHz.
Here it is:
Here is code.(C# code is also given at the end.) Use "ThreadSleepHandler":
Public Class ThreadSleepHandler
Private Stopwatch As New Stopwatch
Private SpinStopwatch As New Stopwatch
Private Average As New TimeSpan
Private Spinner As Threading.SpinWait
Public Sub Sleep(Time As TimeSpan)
Stopwatch.Restart()
If Average.Ticks = 0 Then Average = GetSpinTime()
While Stopwatch.Elapsed < Time
If Stopwatch.Elapsed + Average < Time Then
Average = TimeSpan.FromTicks((Average + GetSpinTime()).Ticks / 2)
End If
End While
End Sub
Public Function GetSpinTime() As TimeSpan
SpinStopwatch.Restart()
Spinner.SpinOnce()
SpinStopwatch.Stop()
Return SpinStopwatch.Elapsed
End Function
End Class
Here is example code:
Sub Main()
Dim handler As New ThreadSleepHandler
Dim stopwatch As New Stopwatch
Do
stopwatch.Restart()
handler.Sleep(TimeSpan.FromSeconds(1))
stopwatch.Stop()
Console.WriteLine(stopwatch.Elapsed)
Loop
End Sub
For c# programmers here is code (I have converted this code but I am not sure):
static class Main
{
public static void Main()
{
ThreadSleepHandler handler = new ThreadSleepHandler();
Stopwatch stopwatch = new Stopwatch();
do {
stopwatch.Restart();
handler.Sleep(TimeSpan.FromSeconds(1));
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
} while (true);
}
}
public class ThreadSleepHandler
{
private Stopwatch Stopwatch = new Stopwatch();
private Stopwatch SpinStopwatch = new Stopwatch();
private TimeSpan Average = new TimeSpan();
private Threading.SpinWait Spinner;
public void Sleep(TimeSpan Time)
{
Stopwatch.Restart();
if (Average.Ticks == 0)
Average = GetSpinTime();
while (Stopwatch.Elapsed < Time) {
if (Stopwatch.Elapsed + Average < Time) {
Average = TimeSpan.FromTicks((Average + GetSpinTime()).Ticks / 2);
}
}
}
public TimeSpan GetSpinTime()
{
SpinStopwatch.Restart();
Spinner.SpinOnce();
SpinStopwatch.Stop();
return SpinStopwatch.Elapsed;
}
}
Note:
"ThreadSleepHandler" is thread unsafe. You cannot use a single "ThreadSleepHandler" for multiple threads.
The first sleep time will not be enough accurate.
In my tests, I found that DispatcherTimer at 20ms intervals will deliver sufficiently smooth animation if you must do it in code. Doing it in XAML is another alternative as already mentioned.

ActionScript - Setter Parameters Within Constructor?

i've designed a custom class (or component?) that extends Sprite whose constructor has 15 parameters. only the first parameter is required, while the remaining 14 have default values assigned. all are necessary.
each of the parameters, except for the first required parameter are actually property setters. the class also contains public setter and getter functions, allowing for property changes at runtime after construction.
i've written the class on my desktop (27" screen) and realized i may have a problem when i was using the class on my 13" laptop - the code hinting was extending past the edges of the screen as it was too long.
is it normal/best practice to include optional setters as parameters in the constructor when setter functions are available, or should setters always be separate from the constructor?
In my opinion it comes down to ease of use at the class instantiating part of the code.
If you have 14 parameters that you either all set or all skip then it's probably the best solution.
var defaultRectangle:Rectangle = new Rectangle(); //square of 1 x 1)
var customRectangle:Rectangle = new Rectangle(0,0, 2,0 2,2, 0,2);
But if some of the 14 parameters are optional, it becomes a bit hard to read, then I think either the use of separate getter/setters is more readable, or a paramater object (mimicking named parameters)
//which parameter means what?
var girlfriend:Girl = new Girl("Blue", 0, 0, "", "", 1.8, 0, "", 140);
//named parameters
var girlfriend:Girl = new Girl({eyeColor: "Blue", height:1.8, iq:140});
//setters
var girlfriend:Girl = new Girl();
girlfriend.eyeColor = "Blue";
girlfriend.height = 1.8;
girlfriend.iq = 140;
I personally try to use Models as much as possible when working with "Views"
So if your object is a Sprite and thus a View. Maybe the best approach could be:
var friend:Person = new Person({name: "Ford Prefect"});
var profileView:ProfileView = new ProfileView(friend);
addChild(profileView);

swing: JSlider but with coarse/fine controls?

I have a JSlider with 65536 different values. It works great for coarse adjustments and for very fine adjustments (+/-1 using up/down arrow) but is very poor in the middle.
Is there anything out there that would be better? I can vaguely imagine taking 2 sliders one for coarse + fine adjustments, but can't really figure out how to get them to work together.
What about using a JSpinner instead of a JSlider? With a SpinnerNumberModel, you can set the step size and even change the step size dynamically.
If you're OK with having multiple controls, you could even have two spinners, one for setting your values and another for setting the step size that is used by the first spinner.
For an example of this, I took the SliderDemo code from the Swing slider tutorial and modified it instead to use two JSpinners instead of a single JSlider. Here's the most interesting part of the code that I changed:
//Create the slider^H^H^H^H^H^H spinners.
// JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
// FPS_MIN, FPS_MAX, FPS_INIT);
final int initStep = 1;
final SpinnerNumberModel animationModel = new SpinnerNumberModel(FPS_INIT,
FPS_MIN,
FPS_MAX,
initStep);
final SpinnerNumberModel stepSizeModel = new SpinnerNumberModel(initStep,
1,
10,
1);
final JSpinner framesSpinner = new JSpinner(animationModel);
framesSpinner.addChangeListener(this);
final JSpinner stepSpinner = new JSpinner(stepSizeModel);
stepSpinner.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent arg0)
{
animationModel.setStepSize(stepSizeModel.getNumber());
}
});
I also had to make a bunch of less interesting changes, such as creating a label for the step size spinner, adding the new label and new spinner to the container, and changing the stateChanged() method on this to cast the source of the event to a JSpinner instead of casting it to a JSlider.
You could, of course, elaborate on this further, such as increasing the step size for the step size spinner (for example, so that you can change the step size from 1 to 101 in a single click). You could also use a different control instead of a JSpinner to set the step size, such as a combo box.
Finally, to make this all really easy to use, you would likely want to hook up some keystroke accelerators (possibly through a menu?) so that you could change the step size without actually moving the mouse or the keyboard focus from one spinner to another.
Edit: Given that you have to use a JSlider no matter what, are you aware that you can use PgUp/PgDn to move up and down by 1/10th of the total range?
If you want to change that 1/10th amount (such as making it dynamic), then you'll need to override the the method BasicSliderUI.scrollByBlock().
Here's an example where I just overrode the UI class of a JSlider to step by 1/4th of the range, instead of 1/10th:
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.setUI(new javax.swing.plaf.metal.MetalSliderUI() {
private static final int SLIDER_FRACTION = 4;
/**
* This code is cut, paste, and modified from
* {#link javax.swing.plaf.basic.BasicSliderUI#scrollByBlock(int).
* I should be ashamed of cutting and pasting, but whoever hardcoded the magic
* number "10" in the original code should be more ashamed than me. ;-)
*
* #param direction
* either +1 or -1
*/
#Override
public void scrollByBlock(final int direction) {
synchronized(slider) {
int oldValue = slider.getValue();
int blockIncrement = (slider.getMaximum() - slider.getMinimum()) / SLIDER_FRACTION;
if (blockIncrement <= 0 && slider.getMaximum() > slider.getMinimum()) {
blockIncrement = 1;
}
int delta = blockIncrement * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL);
slider.setValue(oldValue + delta);
}
}
});
From here, it wouldn't be too hard to replace that constant SLIDER_FRACTION with a variable that was set by another slider or by a spinner, would it?