Javascript: problems with the order of my index - javascript

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}].

Related

Sending large Model list from view to controller c# mvc razor

I have got very large model list in view and i would like to send the list back to controller using ajax query. I have tried to send the whole model list back but since the model is too large, it exceeds the json maxlength specified within web.config. The encode method works for smaller list though.
var jsonString = #Html.Raw(Json.Encode(Model.modelName_small));
Only way that i can vision it to work is but filtering the large model list into smaller list using javascript (similar to a 'Where' SQL statement). My script are as follows (razor):
<script type="text/javascript" language="javascript">
function functionName(input1_decimal) {
var smallerList = new Array();
#foreach (var item in Model.modelName)
{
//input1_decimal should be within a certain range
#:if (input1_decimal - 0.1 <= #item.Property1) && (#item.Property1 <= input1_decimal + 0.1)
{
#:smallerList.push("#item");
}
}
//convert smallerList to json and send it to controller
}
<script>
it seems quite straight forward but I just can not get it to work. Might be something quite trivial. I have also tried:
var smallerList= Model.modelName.Where(x => (input1_decimal - 0.1 <= x.Property1) && (x.Property1 <= input1_decimal + 0.1));
Similarly, i have also tried
var smallerList = Model.modelName.filter(function (item) {
return (input1_decimal - 0.1 <= item.Property1) && (item.Property1<= input1_decimal + 0.1)
});
Thank you for your patience. i hope i have explained it clearly as to what i am trying to achieve. I am not a developer. Programming just for fun and self education.
Are you modifying data on the view ? If so, one other approach is to post only modified data to the controller in order to minimized the json string length and retrieve the rest of the data directly in the controller.
instead of editing jsonmaxlength field within web.config, I assigned MaxJsonLength to Int32.MaxValue. Created a list and assigned properties to model properties and serialise into Json object list. Then i filtered the list using $.grep function. Finally, I was able to send objJsonSmallList back to controller... Happy days :)
#{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Create a list and assigning all the properties of the model
var data = Model.model_Name.Select(x => new
{
propName1 = x.property1,
propName2 = x.property2,
...
propNameN = x.propertyN
});
//serialize collection of anonymous objects
string strArr = js.Serialize(data);
}
var objJsonBigList = JSON.parse('#strArr'.replace(/"/g, '"'));
//small Filtered list send to controller via Ajax
var objJsonSmallList = $.grep(objJsonBigList, function (n) {
return ((input1_decimal- 0.1 <= n.Prop) && (n.Prop <= input1_decimal + 0.1))
});

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 use jade/pug conditionals inside a script block?

i'm struggling to get this working. im actually using Chart.js and trying to populate my graphs with arrays of data.
so my code looks like
block lower-scripts
script.
var data = {
labels : [
each visit in visitstats
#{visit.date},
],
the output i get looks like
<script>var data = {
labels : [
each visit in visitstats
04/17/2016,
],
and i dont think that is right. should it print the each statement out into the html output?
I've tried following a few questions but cant get this working.
It doesn't look like the each statement runs. tried using the - to make it run. tried the pipe in front of the js to make it the exception. nothing.
can anyone show me where i'm going wrong?
Put a hidden input tag in your body in jade e.g.
body
input(type="hidden", id="visit-stats-json", value= JSON.stringify(visitstats) )
script.
var visitStatsValue = document.getElementById("visit-stats-json");
var visitStatsJSON = JSON.parse( visitStatsValue );
var labelsArray = [];
for( var i = 0; i < visitStatsJSON.length; i++ )
{
var visit = visitStatsJSON[i];
labelsArray.push( visit.date );
}//for
var data = { labels: labelsArray };
Now your data variable should have the value you want.
Edit:
I use exactly the same syntax and it works. Please note that there is a space after value=. If it still doesn't work, you can also try following way to achieve the same result:
-var visitStatsString = JSON.stringify(visitstats);
input(type="hidden", id="visit-stats-json", value= visitStatsString )
Can use inline interpolation:
script.
var visitstats = #[JSON.stringify(visitstats)];
...

Parse.com issues while querying array of pointers, .include not getting nested pointer data in cloud code

I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name

How to draw a chart with OFC Python?

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.

Categories