How to draw a chart with OFC Python? - javascript

I need to visualize data for my trac Plugin. Therefore I want to use Open Flash Charts 2.
Trying to follow this didn't quite work out as expected.
Question
The Chartdata won't show, the only output is the loading-animation by OFC.
Everything looks similar too the html-source in the tutorial.
How can I load the JSON- Data into my chart?
Additional Information
I wrote a template where the processed data should be entered.
CHART_TEMPLATE = Template(
'''
<script type=\"text/javascript\" src=\"$json_path/json2.js\">
</script>
<script type=\"text/javascript\" src=\"$js_path/swfobject.js\">
</script>
<script type=\"text/javascript\">
swfobject.embedSWF(\"$ofc_path/open-flash-chart.swf\",
\"$chartname\", \"$width\", \"$height\", \"9.0.0\");
function open_flash_chart_data()
{
alert('reading data');
return JSON.stringify($json_chart_data);
}
function ofc_ready()
{
alert('ofc_ready');
}
</script>
<div id=\"$chartname\"></div>
'''
)
The data is transformed to JSON with Open Flash Charts python, which seems to work well.
def chartdata_from_timetable(self, dict, title):
'''
creates chartdata in JSON-format from 2 dim dictionary
'''
elements = []
x_labels = []
dc = DateConversion.DateConversion()
# if startdate on a weekend, startdate might
not be inluced in the dict->
choose next monday
for key in timetable[startdate]:
element = Chart()
element.type = "line"
element.text = key
values = []
for date in dict:
values.append(dict[date][key])
x_labels.append(string_from_date(date))
element.values = values
elements.append(element)
chart = Chart()
chart.x_axis.labels = x_labels
chart.title.text = title
chart.elements = elements
return chart.create().encode()
Afterwards the following data is returned, none seems to be missing:
CHART_TEMPLATE.safe_substitute(js_path = config['js_dir'],...,
json_chart_data = chart_data)

You have to check if the path of the ofc folder in trac.ini is right.
The function chartdata_from_timetable is also not right. You only see the values of the last entry because of overwriting.

Related

Chart.js chart.update() method is not doing anything

I am working with Chart.js. I have a chart that can display the data. I also have different datasets that I would like to interchange on a button press.
All the datasets are in an array and should just be interchanged with my method. Once I changed all the values, I call the update() method. Nothing happens!
I have checked the content of char.data.datasets.data and it does in fact contain the current data. The only thing is, that Chart.js does not seem to want to update.
What am I missing here?
The function that updates the chart:
let getValues = function(dataset, label)
{
return firebase.database().ref("/data/" + dataset).once("value").then(function(snapshot)
{
var amazon = snapshot.val().Amazon;
var google = snapshot.val().Google;
var facebook = snapshot.val().Facebook;
var twitter = snapshot.val().Twitter;
chart.data.datasets.data = [];
chart.data.labels = [];
chart.data.datasets.label = null;
chart.data.datasets.data = [amazon, google, facebook, twitter];
chart.data.labels = names;
chart.data.datasets.label = label;
chart.update();
console.log(chart.data.datasets.data);
});
}
If you need any more information please let me know.
chart.data.datasets is an array of datasets, not a single dataset. datasets does not have its own data and label attributes. Rather, each individual dataset in the array has its own data and label attributes. You therefore cannot do datasets.data or dataset.label.
If you want to update the data or label variable of a specific dataset, you need to select that object from the array. To select the first dataset, simply use datasets[0]:
chart.data.datasets[0].data = [amazon, google, facebook, twitter];
chart.data.datasets[0].label = label;
If you want to update all datasets, use a forEach loop to iterate through the array:
chart.data.datasets.forEach((dataset) => {
dataset.data = [amazon, google, facebook, twitter];
dataset.label = label;
});
Two more points:
One other possible problem is that the names variable is not initialized anywhere, though it could be that you just didn't include that part of the code in your question.
Also, why do you have the following three lines of code, if you just reassign all the values in the next three lines of code?
chart.data.datasets.data = [];
chart.data.labels = [];
chart.data.datasets.label = null;

How to get int array with javascript in play framework template?

When I tried to pass a list to the template I got an error.
The list is defined like:
myList: List<Map<String,int[]>>
Now the data of myList is :
[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]
I use chart.js to show a chart and so I need a int[] as data list.
my view:
#(myList: List[Map[String,Array[Int]]])
var list = #myList;
for(var i=0;i<list.length;i++){
var map = list[i];
for(var key in map){
myFunction(key,map[key]);
}
}
myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others
var myChart = new Chart(chartid, {
type: 'bar',
data: {
labels: [“a”, “b", “c”, ”s”],
datasets: [{
data: array
}]
}
}
But I got error when I try to traversal the List (The error line shown with Chrome debug)
var out = [{First Try=[I#6e37161d, Second Try=[I#5788d8a9}, {}];
// “Uncaught SyntaxError: Invalid or unexpected token”.
I know when directly output array with
System.out.println(array);
in java it will happen with the string like [I#6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .
Thank you very much.
You can't convert the Java object directly to a Javascript variable like you're attempting to do.
var list = #myList;
That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:
// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));
// Template
#(myListJson: String)
var list = JSON.parse("#myListJson");

Javascript: problems with the order of my index

I am working on Angular and i use Chart.js, to prepare my data for the chart, I rank them in a table template formated like this :
my_table[2014] [[01] = {array},[02] = {array},...,[12] = {array}]
my_table[2015] [[01] = {array},[02] = {array},[03] = {array}]
when i log this table with a console.log, the table is good , but when i do my populate code the order of my index changes automatically :
for(year in my_table){
for(month in my_table[year]){
labels_list.push(month+'/'+year);
total_nb_order.push(my_table[year][month]["nb_orders"]);
total_data.push(my_table[year][month]["amount_ttc"]);
vegetal_data.push(my_table[year][month]["amount_ttc_vgt"]);
manufacture_data.push(my_table[year][month]["amount_ttc_manu"]);
}
}
my chart is good but not in the right chronological order ... indexes out in this order : [10],[11],[12],[01],[02],[03],...
any idea to help me ? :p
Unfortunatly, 0 is a prefix for octal numbers. Change your code to my_table[2014] [[1] = {array},[2] = {array},...,[12] = {array}].

Correct proceedure for JSON/Javascript parsing in Rails?

In Rails, I am querying the database to build a data object for highcharts.
Here is my method from my controller:
def build_data_for_chart
data_array = Array.new
#data_array_as_json = ''
#issues.each {
|issue|
# returns an array of KeyIssue objects for a given issue
given_issue_array = KeyIssues.where(issue: issue).all
a = Array.new
#loop through each element extracting the timedate and % and add to new array
given_issue_array.each {
|entry|
a.push([entry.datetime.utc.to_date, entry.percentage])
}
#build the hash for an individual issue
temp_hash = {:name => issue, :data => a, :animation => false}
#add the individual issue and all its data to a final array that contains all the issues.
data_array.push(temp_hash)
}
#data_array_as_json = data_array.to_json.html_safe
end
Now I am trying to pull it out in a script in my view.
--- script ---
var data = $.parseJSON(<%= #data_array_as_json %>);
--- script ---
When I print to console, I can see the objects and all their data. Also when I print to html the output looks correct:
"[{\"name\":\"ABORIGINAL & NATIVE TITLE ISSUES\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\",27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996-01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09-01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30],[\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01\",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\"2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\",26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008-07-01\",29]],\"animation\":false}]"
But when I go to print the data variable it is null (obviously due to not being valid input). What am I messing up?
FYI..
I needed to wrap it in single quotes.. to make it work..
$.parseJSON(' <%= #data_array_as_json %> ');
You can try this:
<script type="text/javascript">
var data = <%== data_array.to_json %>
</script>

pass parameter to scripted datasource from another dataset

how to pass parameter from a dataset row value to java function accessed via scripted datasource?
I have a java class that deccrypts an encrypted string
class Decryptor{
public String decrypt(text)
{
.
.
StandardPBEStringEncryptor textEncryptor = new StandardPBEStringEncryptor();
return textEncryptor.decrypt(text);
}
}
I imported it to my birt report that goes like this:
I created a dataset named dsCode with column "code";
open:
sessionUtil = new Packages.com.reports.server.generator.data.SessionUtil();
sessionUtil.openCurrentSession();
c = new Decryptor();
textDecrpt = c.decrypt("O6pas1t9NyY9bmAtjvX2NA==");
fetch;
row["code"] = textDecrpt ;
return true;
this is working fine. however I want to pass a value to the decrypt function from anther dataset row value(encryptedCodecolumn of dsCustomerIfdo). How do I do this? I made the dsCode as datasource of a subreport and I added parameter called pmCode to the dsCode and passed a value to it using "Data Set Parameter Binding"
and made the script like this
textDecrpt = c.decrypt(params["pmCode"]);
this gives me an error end of file undefined.
How do i access a dataset row value in javascript? or pass a rowvalue of a dataset to a script function?
this is not working
var dset = reportContext.getDesignHandle().findDataSet("dsCustomerInfo");
textDecrpt = c.decrypt(dset.getRow("encryptedCode").value);
thanks
I solved it by not using another dataset like what I intially tried. Just used the dsCusotmerInfo, added a computed column called decryptedCode and added the scirpt on fetch on it. This decrypts all code of all customers.
sessionUtil = new Packages.com.reports.server.generator.data.SessionUtil();
sessionUtil.openCurrentSession();
c = new Decryptor();
row["decryptedCode"] = c.decrypt(row["encryptedCode"]);
return true;

Categories