I'm using JSF2 and PrimeFaces 5.1.
My problem is that I don't know how to put dates in the Y axis of my graph. It only accepts Number types.
/**
* Graph's definition
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel createLineModels() throws ParseException {
LineChartModel lineChartModel = new LineChartModel();
lineChartModel = initCategoryModel();
lineChartModel.setTitle("Graph's title");
lineChartModel.setLegendPosition("nw");
lineChartModel.getAxes().put(AxisType.X, new CategoryAxis("PV"));
Axis yAxis = this.lineChartModel.getAxis(AxisType.Y);
yAxis.setTickInterval("1");
yAxis.setLabel("Provisional dates");
return lineChartModel;
}
/**
* Initialization of the graph
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel initCategoryModel() throws ParseException {
LineChartModel model = new LineChartModel();
ChartSeries provisionalDates= new ChartSeries();
provisionalDates.setLabel("Dates");
//Here, I set my data in the Graph
//In x-axis the date and the y-axis a numerical value
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
model.addSeries(provisionalDates);
return model;
}
My issue are those lines:
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
The method set only accept a Numerical value. I want to have date instead.
Do you know a way so I can put my dates in the Y axis?
Thanks
I finally found an answer with jqPlot.
The method set only accept a numerical value so what I did is to convert my date in milliseconds.
long dateMS= myDate.getTime();
provisionalDates.set("2016-01-15", dateMS);
Then, you can add an extender to your chart with PF. The extender allows you to configure your chart:
model.setExtender("extender"); //Works with PF 5+
After that, you just need to make the extender function:
function extender() {
this.cfg.axes.yaxis.tickOptions = {
formatter: function (format, value) {
return $.jqplot.sprintf(convertDate(value));
}
};
}
The convertDate function only convert a getTime to dd/mm/yyyy.
function convertDate(ms) {
var dateReadable = new Date(ms);
var year = dateReadable.getFullYear();
var month = dateReadable.getMonth() + 1;
if (month < 10) {
month = "0" + month;
}
var day = dateReadable.getDate();
if (day < 10) {
day = "0" + day;
}
return day + "/" + month + "/" + year;
}
Related
My datagrid has a depth-dimensions column that shows fractions (one dimension used for example is 24 3/8). I have the ability to choose the text (fraction or decimal), but essentially I would need to be able to convert back and forth from 24 3/8 to 24.375.
Why the Decimal format is needed:
I have checkboxes to filter the depth-dimensions column, so I'll need decimal form for that logic (e.g. checkbox to see filter depth-dimensions between 20 and 26).
Why the fraction format is needed: I'll need the fraction format because that depth-dimension data will be referenced as a string in another part of the application. The filter doesn't work when in this format is used in the dataGrid, because it won't recognize 24 3/8 as a number/int.
So basically I'm looking for a way to convert between the two formats, 24 3/8 to 24.375 and 24.375 to 24 3/8.
Again, my apologies for the confusion - I'm able to re-edit and/or add more details if needed.
Thanks in advance!
--moe
Why the fraction format is needed: I'll need the fraction format
because that depth-dimension data will be referenced as a string in
another part of the application.
Your reason for needing the fraction format seems odd. Do you understand that you can use a Number data type in a String by casting it?
var decimalNum:Number = 3.14;
//concatenating a Number with a String automatically casts it
var autoCastString:String = "I want to eat some " + decimalNum;
trace(autoCastString);
// cast as String type
var decimalString:String = String(decimalNum);
trace("Mmmm! I like", decimalString);
Output:
I want to eat some 3.14
Mmmm! I like 3.14
But perhaps you have other reasons. The code below is from this link: Decimal to Fraction. I haven't tested it.
package com.lookmum.util
{
public class Fraction
{
private static var it :Number = 0;
public static var iterationLimit:Number = 10000;
public static var accuracy :Number = 0.00001;
public function Fraction()
{
}
private static function resetIt():void
{
it = 0;
}
private static function addIt():Boolean
{
it++;
if (it == iterationLimit)
{
trace('error : too many iterations');
return true;
}
else
{
return false;
}
}
public function getFractionString(num:Number):String
{
var fracString:String;
var fracArray:Array = getFraction(num);
switch (fracArray.length)
{
case 1 :
fracString = num.toString();
break;
case 2 :
fracString = fracArray[0].toString() + '/' + fracArray[1].toString();
break;
case 3 :
fracString = fracArray[0].toString() + ' ' + fracArray[1].toString() + '/' + fracArray[2].toString();
break;
}
return fracString;
}
public function getFraction(num:Number):Array
{
var fracArray:Array = new Array();
var hasWhole:Boolean = false;
if (num >= 1)
{
hasWhole = true;
fracArray.push(Math.floor(num));
}
if (num - Math.floor(num) == 0)
{
return fracArray;
}
if (hasWhole)
{
num = num - Math.floor(num);
}
var a:Number = num - int(num);
var p:Number = 0;
var q:Number = a;
resetIt();
while (Math.abs(q - Math.round(q)) > accuracy)
{
addIt();
p++;
q = p / a;
}
fracArray.push(Math.round(q * num));
fracArray.push(Math.round(q));
return fracArray;
}
}
}
I need to do this for my app, but I'm not sure how. Currently I'm trying to achieve it using Geolocator and a Timer.
Declare a Geolocator with a fixed ReportInterval
Store the locations
With the help of these methods compare current with stored location to detect movement
public const double EARTH_RADIUS_M = 6371000
private static double ToRad(double val)
{
return val * (Math.PI / 180);
}
public static double GetDistanceM(double lat0, double lng0, double lat1, double lng1)
{
double dLat = ToRad(lat1 - lat0);
double dLon = ToRad(lng1 - lng0);
double a = Math.Pow(Math.Sin(dLat / 2), 2) +
Math.Cos(ToRad(lat0)) * Math.Cos(ToRad(lat1)) *
Math.Pow(Math.Sin(dLon / 2), 2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double distance = EARTH_RADIUS_M * c;
return distance;
}
Considerations for windows 10:
private async void StartLocationExtensionSession()
{
session = new ExtendedExecutionSession();
session.Description = "Location Tracker";
session.Reason = ExtendedExecutionReason.LocationTracking;
var result = await session.RequestExtensionAsync();
}
Considerations for Windows Phone 8:
https://msdn.microsoft.com/en-us/library/windows/apps/jj662935(v=vs.105).aspx
Be happy with your new dynamic MovementThreshold ;)!
I would like to create an array of numbers and then randomize those numbers.
Here is what I've come up with. It does two things.
It gets an array from 0 to the length specified. What the main question was about.
It then randomizes the items in that array
// returns [1,2,3,4,5,6,7,8,9,10] except shuffled
var array:Array = getSequenceArray(10);
/**
* Get an array of the range of numbers from 1 to the number specified and randomize them.
* */
public function getRandomArray(count:int):Array {
// this part is not looped. yay!
var array:Array = new Array(count).map(function (item, index) { return index + 1; });
return randomizeArray(array);;
}
/**
* Randomize items in an array
* */
public function randomizeArray(original:Array, cloneArray:Boolean = true):Array {
var length:int = original.length;
var shuffledArray:Array = [];
var newArray:Array = original.slice();
var randomNumber:Number;
// this is still using a loop. this loop is less of an issue than the first
while (length) {
randomNumber = Math.floor(Math.random() * length);
shuffledArray.push(newArray.splice(randomNumber, 1)[0]);
length--;
}
if (!cloneArray) {
original.splice(0, shuffledArray.length);
original.push.apply(this, shuffledArray);
return original;
}
return shuffledArray;
}
I'm trying to get a random date in a date range and this is what i have so far but it doesnt seem to be working ??
Where I'm I Going wrong ??
//Gets the date difference
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference; }
// gets a random number
function randomRange(max:Number, min:Number = 0):Number {
return Math.round(Math.random() * (max - min) + min); }
protected function getRandomDate:void {
// TODO Auto-generated method stub
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
var num:Number = new Number(differenceBetweenDates(dat2,dat1));
var random:Number= new Number(randomRange(num));
currDate.setDate(dat2.date+random);
getComic(formatDate(currDate));
dat2 = new Date(1989, 4, 16)
}
I found a couple errors in your code.
currDate.setDate(dat2.date+random)
setDate sets the date in the month, not an arbitrary date in time. Also, you want to use dat2.time, not dat2.date.
Should be
currDate.setTime(dat2.time+random)
Here's a slightly different version you might want to try out. I removed the MS_PER_DAY computation, so, you may want to add that back in if you need it, but I found this easier to look at:
public function getRandomTimeBetweenDates(date1:Date, date2:Date):Number
{
return Math.round(Math.random() * (Math.abs(date2.time - date1.time)));
}
public function getRandomDate():Date {
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
dat2.setTime(dat2.time + getRandomTimeBetweenDates(dat2,dat1));
return dat2;
}
I do not know the reason why am i getting same values of different JSON date values.
Here is my code for parsing date values in JSON date format:
package com.jsondate.parsing;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JSONDateParsing extends Activity {
/** Called when the activity is first created. */
String myString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
//Date d = (new Date(1266029455L));
//Date d = (new Date(1266312467L));
Date d = (new Date(1266036226L));
//String s = d.getDate() + "-" + d.getMonth() + "-" + d.getYear() + d.getHours() + d.getMinutes() + d.getSeconds();
// SimpleDateFormat sdf=new SimpleDateFormat("yyyy MMM dd # hh:mm aa");
//Toast.makeText(this, d.toString(), Toast.LENGTH_SHORT);
Log.e("Value:", d.toString());
myString = d.toString();
String []words = myString.split(" ");
for(int i = 0;i < words.length; i++)
Log.e("Value:", words[i]);
myString = words[2] + "-" + words[1] + "-" + words[5] + " " + words[3];
tv.setText(myString);
setContentView(tv);
}
}
As far as I know, there is no standard way of representing a date in JSON. It looks as though what you are receiving is an integral value representing the number of seconds that have elapsed since the epoch of January 1, 1970, 00:00:00 GMT. This is somewhat different than what the Date(long date) constructor is expecting. The constructor is expecting milliseconds since the epoch. You need to multiply the values from the JSON by 1000 to use them correctly with Date.
long jsonDate = 1266036226L;
Date date = new Date(jsonDate * 1000);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
String stringDate = dateFormat.format(date);
Here are the different representations for the examples that you have given. Do they correspond with what you are expecting?
1266029455 <==> 12-Feb-2010 09:50:55
1266312467 <==> 16-Feb-2010 04:27:47
1266036226 <==> 12-Feb-2010 11:43:46
1266072180 <==> 13-Feb-2010 09:43:46
Note that the default behavior of SimpleDateFormat is to use the local time zone. In my case this is GMT-0500. A different time zone can be specified by calling the setTimeZone method.
var d1 = ui.item.IssueDate;
var d = new Date(parseInt(d1.slice(6, -2)));
var Issdate = ("0" + (d.getMonth() + 1)).slice(-2) + '/' + ("0" + d.getDate()).slice(-2) + '/' + d.getFullYear().toString();
$('#IssueDate').val(Issdate);