DynamoDB: Handling ProvisionedThroughputExceededException without increasing Read/Write Capacity - amazon-dynamodb

Is there a good way to handle the ProvisionedThroughputExceededException without increasing the Read/Write capacity of the table? Ideally, I would like to decrease the throughput on the scripting side such that the exception won't be triggered.
function saveDataToDynamodb(data, scriptName){
let items = [];
var processItemsCallback = function (err, data) {
if (err) {
console.log(err);
setTimeout(() => {console.log('sleep for error')}, Math.floor(0.5 * 1000 + 1000));
}else {
if (Object.keys(data.UnprocessedItems).length > 0) {
//setTimeout(() => {console.log('sleep to wait')}, Math.floor(Math.random() * 1000 + 1000));
var params = {};
params.RequestItems = data.UnprocessedItems;
docClient.batchWrite(params, processItemsCallback);
}
}
};
data.forEach(station => {
let stationName = station.stationName
if (stationName == null) {
stationName = "null"
}
//console.log(station.stationId + "_" + stationName)
let pollutants = station.pollutants
let unique_set = new Set()
let aqiArr = [];
let sortedKey;
let timestamp;
pollutants.forEach(pollutant => {
timestamp = pollutant.utcMoment
sortedKey = station.stationId + "_" + timestamp + "_" + station.latitude + "_" + station.longitude + "_" + pollutant.pollutant;
if (!unique_set.has(sortedKey)) {
unique_set.add(sortedKey)
if (!scriptName.includes("Pollen")) { // calculate AQI if it's not pollen data
let polValue = processPollutant(pollutant.value, pollutant.pollutant);
let pollutantAQI;
if (pollutant.pollutant == "o3" && pollutant.avgInterval == "1h") {
pollutantAQI = aqiCalc.calcEpaAqi(polValue, pollutant.pollutant, true);
} else {
pollutantAQI = aqiCalc.calcEpaAqi(polValue, pollutant.pollutant, false);
}
//console.log("polValue: " + polValue + ", Pollutant value: " + pollutant.value + ", pollutant: " + pollutant.pollutant + ", AQI: " + pollutantAQI)
aqiArr.push(pollutantAQI);
}
items.push({
PutRequest: {
Item: {
"stationId": station.stationId,
"stationName": String(station.stationName),
"latitude": station.latitude,
"longitude": station.longitude,
"pollutant": pollutant.pollutant,
"avgInterval": pollutant.avgInterval,
"units": pollutant.units,
"initialUnits": pollutant.initialUnits,
"value": pollutant.value,
"sortedKey": sortedKey,
"timestamp": timestamp
}
}
});
if (items.length >= 24) {
let params = {
RequestItems: {
pollutantFullData: items
}
};
docClient.batchWrite(params, processItemsCallback);
items = []
}
}
});
if (aqiArr.length > 0) {
var finalAqi = getMaxAsInteger(aqiArr);
if (finalAqi > 500) {
finalAqi = 500;
}
items.push({
PutRequest: {
Item: {
"stationId": station.stationId,
"stationName": String(station.stationName),
"latitude": station.latitude,
"longitude": station.longitude,
"pollutant": "aqi",
"avgInterval": "1h",
"units": "ppb",
"initialUnits": "ppm",
"value": finalAqi,
"sortedKey": station.stationId + "_" + timestamp + "_" + station.latitude + "_" + station.longitude + "_aqi",
"timestamp": timestamp
}
}
});
}
if (items.length > 0) {
let params = {
RequestItems: {
pollutantFullData: items
}
};
docClient.batchWrite(params, processItemsCallback);
}
});
}
It seems as though the batchWrite operation is running asynchronously, such that the various threads are hitting the API endpoint at the same time, thus causing the error. How can the previous code be changed to resolve the error?

Related

Unable to convert string to date (dd/MMM,YYYY) format ASP.NET

var LR_No_Of_Days = "";
$("#DateRange").jqxDateTimeInput({ width: 250, height: 25, selectionMode: 'range' }); $("#DateRange").on('change', function (event) {
var selection = $("#DateRange").jqxDateTimeInput('getRange');
if (selection.from != null) {
$("#selection").html("<div>From: " + selection.from.toLocaleDateString() + " <br/>To: " + selection.to.toLocaleDateString() + "</div>");
}
var LR_Request_Date_From = selection.from.toLocaleDateString();
var LR_Request_Date_To = selection.to.toLocaleDateString();
$('#LR_Request_Date_From').val(LR_Request_Date_From);
$('#LR_Request_Date_To').val(LR_Request_Date_To);
NoOfdays();
function NoOfdays() {
var LR_No_Of_Days = Math.floor((Date.parse(LR_Request_Date_To) - Date.parse(LR_Request_Date_From)) / 86400000); if (LR_No_Of_Days == '0') {LR_No_Of_Days = 1;} else { LR_No_Of_Days-1; }; alert(LR_Request_Date_From + " &&& " + LR_Request_Date_To + " No of days:" + LR_No_Of_Days);
$("#LR_No_Of_Days").val(LR_No_Of_Days);}});
I'm unable to convert the string variable(LR_Request_Date_From and LR_Request_Date_To) to date format. I receive error converting string to date.
You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

which part of the d3 initialization should be put into meteor autorun to make the charts reactive?

Just started learning meteor and d3 / crossfilter charting libraries.
Picked up some example code off the Web, and have it working in my local app.
I do have an empty this.autorun() function in my meteor client code, but have no idea what part of the lengthy d3 initialization and composition routine should be put into autorun, in order for these charts to react to the data changes.
I have tried to just put the Flights.find().fetch() inside the autorun, but in that case, the page never seem to finish loading.
Here is my entire meteor code:
if (Meteor.isClient) {
Template.dashboard.helpers({
});
Template.dashboard.events({
});
Template.dashboard.rendered = function(){
var flights = Flights.find().fetch();
if (!flights.length) return;
var crossData = crossfilter(flights);
// d3.csv(data, function(error, flights) {
// Various formatters.
var formatNumber = d3.format(",d"),
formatChange = d3.format("+,d"),
formatDate = d3.time.format("%B %d, %Y"),
formatTime = d3.time.format("%I:%M %p");
// A nest operator, for grouping the flight list.
var nestByDate = d3.nest()
.key(function(d) { return d3.time.day(d.date); });
// A little coercion, since the CSV is untyped.
flights.forEach(function(d, i) {
d.index = i;
d.date = parseDate(d.date);
d.delay = +d.delay;
d.distance = +d.distance;
});
// Create the crossfilter for the relevant dimensions and groups.
var flight = crossfilter(flights),
all = flight.groupAll(),
date = flight.dimension(function(d) { return d.date; }),
dates = date.group(d3.time.day),
hour = flight.dimension(function(d) { return d.date.getHours() + d.date.getMinutes() / 60; }),
hours = hour.group(Math.floor),
delay = flight.dimension(function(d) { return Math.max(-60, Math.min(149, d.delay)); }),
delays = delay.group(function(d) { return Math.floor(d / 10) * 10; }),
distance = flight.dimension(function(d) { return Math.min(1999, d.distance); }),
distances = distance.group(function(d) { return Math.floor(d / 50) * 50; });
var charts = [
barChart()
.dimension(hour)
.group(hours)
.x(d3.scale.linear()
.domain([0, 24])
.rangeRound([0, 10 * 24])),
barChart()
.dimension(delay)
.group(delays)
.x(d3.scale.linear()
.domain([-60, 150])
.rangeRound([0, 10 * 21])),
barChart()
.dimension(distance)
.group(distances)
.x(d3.scale.linear()
.domain([0, 2000])
.rangeRound([0, 10 * 40])),
barChart()
.dimension(date)
.group(dates)
.round(d3.time.day.round)
.x(d3.time.scale()
.domain([new Date(2001, 0, 1), new Date(2001, 3, 1)])
.rangeRound([0, 10 * 90]))
.filter([new Date(2001, 1, 1), new Date(2001, 2, 1)])
];
// Given our array of charts, which we assume are in the same order as the
// .chart elements in the DOM, bind the charts to the DOM and render them.
// We also listen to the chart's brush events to update the display.
var chart = d3.selectAll(".chart")
.data(charts)
.each(function(chart) { chart.on("brush", renderAll).on("brushend", renderAll); });
// Render the initial lists.
var list = d3.selectAll(".list")
.data([flightList]);
// Render the total.
d3.selectAll("#total")
.text(formatNumber(flight.size()));
renderAll();
// Renders the specified chart or list.
function render(method) {
d3.select(this).call(method);
}
// Whenever the brush moves, re-rendering everything.
function renderAll() {
chart.each(render);
list.each(render);
d3.select("#active").text(formatNumber(all.value()));
}
// Like d3.time.format, but faster.
function parseDate(d) {
return new Date(2001,
d.substring(0, 2) - 1,
d.substring(2, 4),
d.substring(4, 6),
d.substring(6, 8));
}
window.filter = function(filters) {
filters.forEach(function(d, i) { charts[i].filter(d); });
renderAll();
};
window.reset = function(i) {
charts[i].filter(null);
renderAll();
};
function flightList(div) {
var flightsByDate = nestByDate.entries(date.top(40));
div.each(function() {
var date = d3.select(this).selectAll(".date")
.data(flightsByDate, function(d) { return d.key; });
date.enter().append("div")
.attr("class", "date")
.append("div")
.attr("class", "day")
.text(function(d) { return formatDate(d.values[0].date); });
date.exit().remove();
var flight = date.order().selectAll(".flight")
.data(function(d) { return d.values; }, function(d) { return d.index; });
var flightEnter = flight.enter().append("div")
.attr("class", "flight");
flightEnter.append("div")
.attr("class", "time")
.text(function(d) { return formatTime(d.date); });
flightEnter.append("div")
.attr("class", "origin")
.text(function(d) { return d.origin; });
flightEnter.append("div")
.attr("class", "destination")
.text(function(d) { return d.destination; });
flightEnter.append("div")
.attr("class", "distance")
.text(function(d) { return formatNumber(d.distance) + " mi."; });
flightEnter.append("div")
.attr("class", "delay")
.classed("early", function(d) { return d.delay < 0; })
.text(function(d) { return formatChange(d.delay) + " min."; });
flight.exit().remove();
flight.order();
});
}
function barChart() {
if (!barChart.id) barChart.id = 0;
var margin = {top: 10, right: 10, bottom: 20, left: 10},
x,
y = d3.scale.linear().range([100, 0]),
id = barChart.id++,
axis = d3.svg.axis().orient("bottom"),
brush = d3.svg.brush(),
brushDirty,
dimension,
group,
round;
function chart(div) {
var width = x.range()[1],
height = y.range()[0];
y.domain([0, group.top(1)[0].value]);
div.each(function() {
var div = d3.select(this),
g = div.select("g");
// Create the skeletal chart.
if (g.empty()) {
div.select(".title").append("a")
.attr("href", "javascript:reset(" + id + ")")
.attr("class", "reset")
.text("reset")
.style("display", "none");
g = div.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("clipPath")
.attr("id", "clip-" + id)
.append("rect")
.attr("width", width)
.attr("height", height);
g.selectAll(".bar")
.data(["background", "foreground"])
.enter().append("path")
.attr("class", function(d) { return d + " bar"; })
.datum(group.all());
g.selectAll(".foreground.bar")
.attr("clip-path", "url(#clip-" + id + ")");
g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(axis);
// Initialize the brush component with pretty resize handles.
var gBrush = g.append("g").attr("class", "brush").call(brush);
gBrush.selectAll("rect").attr("height", height);
gBrush.selectAll(".resize").append("path").attr("d", resizePath);
}
// Only redraw the brush if set externally.
if (brushDirty) {
brushDirty = false;
g.selectAll(".brush").call(brush);
div.select(".title a").style("display", brush.empty() ? "none" : null);
if (brush.empty()) {
g.selectAll("#clip-" + id + " rect")
.attr("x", 0)
.attr("width", width);
} else {
var extent = brush.extent();
g.selectAll("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
}
}
g.selectAll(".bar").attr("d", barPath);
});
function barPath(groups) {
var path = [],
i = -1,
n = groups.length,
d;
while (++i < n) {
d = groups[i];
path.push("M", x(d.key), ",", height, "V", y(d.value), "h9V", height);
}
return path.join("");
}
function resizePath(d) {
var e = +(d == "e"),
x = e ? 1 : -1,
y = height / 3;
return "M" + (.5 * x) + "," + y
+ "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6)
+ "V" + (2 * y - 6)
+ "A6,6 0 0 " + e + " " + (.5 * x) + "," + (2 * y)
+ "Z"
+ "M" + (2.5 * x) + "," + (y + 8)
+ "V" + (2 * y - 8)
+ "M" + (4.5 * x) + "," + (y + 8)
+ "V" + (2 * y - 8);
}
}
brush.on("brushstart.chart", function() {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", null);
});
brush.on("brush.chart", function() {
var g = d3.select(this.parentNode),
extent = brush.extent();
if (round) g.select(".brush")
.call(brush.extent(extent = extent.map(round)))
.selectAll(".resize")
.style("display", null);
g.select("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
dimension.filterRange(extent);
});
brush.on("brushend.chart", function() {
if (brush.empty()) {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", "none");
div.select("#clip-" + id + " rect").attr("x", null).attr("width", "100%");
dimension.filterAll();
}
});
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return x;
x = _;
axis.scale(x);
brush.x(x);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.dimension = function(_) {
if (!arguments.length) return dimension;
dimension = _;
return chart;
};
chart.filter = function(_) {
if (_) {
brush.extent(_);
dimension.filterRange(_);
} else {
brush.clear();
dimension.filterAll();
}
brushDirty = true;
return chart;
};
chart.group = function(_) {
if (!arguments.length) return group;
group = _;
return chart;
};
chart.round = function(_) {
if (!arguments.length) return round;
round = _;
return chart;
};
return d3.rebind(chart, brush, "on");
}
// });
this.autorun(function(){
})
}
}
if (Meteor.isServer) {
Meteor.startup(function () {
});
}
If this helps, here is my attempt at reproducing one of the d3 force layout examples with collision detection / custom gravity functions https://gist.github.com/gmlnchv/80dd206440cca39800b8. I'm using observe() to react to changes.

Fullcalendar recurring events limits (using dow)

I have been trying to make recurring events in fullcalendar, I really find dow feature helpful, but I really want to add date ranges to it.
In other words, dow : [1] will repeat a task for every single Monday, the problems is, I want to make it visible only in a date range I set.
You can not set ranges by using dow, you have to perform some custom functionality.
Lets suppose that you have fetched events data from your database which contains multiple event objects. each event object has start date end date property and also to and from properties which contains date range , isRecurring is a Boolean property which we will add true in case of recurring events otherwise it will be false.
Remember the recurring events take start and end time without date, you only need to give them time slots, like start = "16:00" and end = "20:00" You can extract time by using moment js like i did while initializing my event object
{
title:'Recurring Event',
start: moment.utc(event.start).format('HH:mm'),
end: moment.utc(event.end).format('HH:mm'),
isRecurrring: event.isRecurring,
ranges: [{
start: moment(event.from),
end: moment(event.to),
}],
}
I have used moment.utc() to ignore the timezone.
Now override the eventRender function while initializing your fullCalendar. Your eventRender function will be
eventRender: function(event, element, view){
if (event.isRecurrring) {
return (event.ranges.filter(function(range){
return (moment(event.start).isBefore(range.end) &&
moment(event.end).isAfter(range.start));
}).length) > 0;
}
}
You coulded set ranges as this example:
repeatingEvents.push({
title: "From: " + inputDateStart + " To: " + inputDateFinish,
start: vm.timeStart,
end: vm.timeFinish,
dow: listDay,
ranges: [{
start: dateStart,
end: dateFinish
}]
})
$("#calendar").fullCalendar("refetchEvents");
So you can use both "dow" and "ranges". Hope help for you!
function createCalendar() {
vm.uiConfig = timeProfileFactory.getCalendarConfig();
vm.uiConfig.calendar.eventClick = eventClick;
vm.uiConfig.calendar.eventDrop = alertOnDrop;
vm.uiConfig.calendar.eventResize = alertOnResize;
vm.uiConfig.calendar.eventRender = eventRender;
vm.uiConfig.calendar.select = selectSlot;
vm.uiConfig.calendar.header.center = "title";
vm.events = function(start, end, timezone, callback) {
callback(repeatingEvents);
}
vm.eventSources = [vm.events];
};
function selectSlot(start, end, jsEvent, view) {
var allDay = !start.hasTime() && !end.hasTime();
var offset = ((new Date()).getTimezoneOffset())/60;
var dateStart = (new Date(start)).setHours(0, 0, 0, 0);
dateStart = new Date(dateStart);
dateStart.setHours(dateStart.getHours() - offset);
dateStart = dateStart.toISOString();
var timeStart = (new Date(start)).toISOString();
var timeEnd = (new Date(end)).toISOString();
timeStart = timeStart.split('T')[0];
timeEnd = timeEnd.split('T')[0];
var length = repeatingEvents.length;
if(positionEvent == -1 || repeatingEvents.length == 0) {
positionEvent = 0;
} else {
positionEvent = repeatingEvents[length - 1].position + 1;
}
repeatingEvents.push({
title: "From: " + start.format("DD/MM/YYYY"),
start: start.format("HH:mm"),
end: end.format("HH:mm"),
dow: [new Date(start).getDay()],
ranges: [{
start: dateStart,
end: null
}],
position: positionEvent,
allDay: false
});
length++;
if(repeatingEvents[length - 1].end == "00:00") {
repeatingEvents[length - 1].end = "24:00";
}
if(allDay) {
repeatingEvents[length - 1].allDay = true;
repeatingEvents[length - 1].start = null;
repeatingEvents[length - 1].end = null;
}
$("#calendar").fullCalendar("refetchEvents");
};
function eventClick(event, date, jsEvent, view) {
isOpenDialog = true;
for(var i = 0; i < repeatingEvents.length; i++) {
if(repeatingEvents[i].position == event.position && isOpenDialog) {
selectIndex = i;
vm.timeStart = repeatingEvents[i].start;
vm.timeFinish = repeatingEvents[i].end;
vm.dateStart = repeatingEvents[i].title.split(' ')[1];
if(repeatingEvents[i].ranges[0].end == null) {
vm.dateFinish = "";
vm.radioValue = "never";
} else {
vm.dateFinish = repeatingEvents[i].title.split(' ')[3];
vm.radioValue = "on";
}
angular.forEach(vm.checkDays, function(item) {
item.checked = false;
});
angular.forEach(event.dow, function(index) {
vm.checkDays[index].checked = true;
})
openDialog();
break;
}
}
};
function alertOnResize(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
var timeFinish = event.end.format("HH:mm");
if(timeFinish == "00:00") {
timeFinish = "24:00";
}
repeatingEvents[i].end = timeFinish;
break;
}
}
$("#calendar").fullCalendar("refetchEvents");
};
function alertOnDrop(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
if(repeatingEvents[i].allDay || event.allDay) {
revertFunc();
} else {
var timeStart = event.start.format("HH:mm");
var timeFinish = event.end.format("HH:mm");
var dateStart = repeatingEvents[i].ranges[0].start;
var dateFinish = repeatingEvents[i].ranges[0].end;
var oldTimeStart = repeatingEvents[i].start.split(':')[0]*3600 + repeatingEvents[i].start.split(':')[1]*60;
var newTimeStart = timeStart.split(':')[0]*3600 + timeStart.split(':')[1]*60;
var deltaHour = newTimeStart - oldTimeStart;
var deltaDay = (delta/1000 - deltaHour)/86400;
dateStart = new Date(dateStart);
dateStart.setDate(dateStart.getDate() + deltaDay);
dateStart = dateStart.toISOString();
var title;
if(dateFinish != null) {
dateFinish = new Date(dateFinish);
dateFinish.setDate(dateFinish.getDate() + deltaDay);
dateFinish = dateFinish.toISOString();
title = "From: " + moment(dateStart).format("DD/MM/YYYY") + " To: " + moment(dateFinish).format("DD/MM/YYYY");
} else {
title = "From: " + moment(dateStart).format("DD/MM/YYYY");
}
for(var j in event.dow) {
repeatingEvents[i].dow[j] = parseInt(repeatingEvents[i].dow[j]) + deltaDay;
if(repeatingEvents[i].dow[j] > 6) {
repeatingEvents[i].dow.splice(j, 1);
}
}
repeatingEvents[i].start = timeStart;
repeatingEvents[i].end = timeFinish;
repeatingEvents[i].ranges[0].start = dateStart;
repeatingEvents[i].ranges[0].end = dateFinish;
repeatingEvents[i].title = title;
if(timeFinish == "00:00") {
repeatingEvents[i].end = "24:00";
}
$("#calendar").fullCalendar("refetchEvents");
}
break;
}
}
};
function eventRender(event, element, view) {
var removeEvent = $("<i class='removeEvent icons8-delete pull-right'></i>");
removeEvent.on("click", function() {
isOpenDialog = false;
vm.removeEvent(event);
});
element.find(".fc-content").prepend(removeEvent);
var result;
if(event.ranges[0].end == null) {
result = (event.ranges.filter(function(range) {
var startConvert = (new Date(event.start)).toISOString();
return (event.start.isAfter(range.start) || startConvert == range.start);
}).length) > 0;
} else {
result = (event.ranges.filter(function(range) {
return (event.start.isBefore(range.end) && event.end.isAfter(range.start));
}).length) > 0;
}
return result;
};

flot plots interfering with each other

and thank you once again for your expert support. I have a rather nice implementation of flot, that has one very unfortunate bug. The plot routine works in a loop, so it creates as many plots as there are data files, that pass muster, in the directory. If there is only one data file, then only one plot, the resulting flot plot works fine and the check boxes turn the lines on and off as expected. If I have more than one data file and hence more than one flot plot.. only the bottom one seems to work correctly, the remainder lock up after either one toggle or none.
Can someone give me an idea how to create the flot plots so they do not interfere? I have read elsewhere that the function name does not need to be different, but have not verified this, and I did change the labels, but this added additional weirdness.
Quite a long code.. but it gives you most of what I know...
The first section here actually builds the data sets for flot... then the rest creates the plot...
<script type='text/javascript'>//<![CDATA[
$(function(){
var results = [
<?php
$downsample = 5;
for($k=0;$k<2; $k++){
//$k =0 is Left, $k = 1 is right
if ($k==0){
$side = "L";
$offset = 1;
} elseif ($k==1) {
$side = "R";
$offset = 0;
}
for ($m = 1; $m <= count($trackdata)-1; $m++){
echo "\n{\n\"label\": \"".$m.$side."\",\n"; //echo "\n{\n\"label\": \"".$m." ".$side."\",\n";
echo "\"data\": [";
for ($n=1;$n<=count($PSD[$m*3-2]);$n=$n+$downsample){
$tmp = "[".$PSD[$m*3-2][$n].",".$PSD[$m*3-$offset][$n]."]";
echo $tmp;
if ($n > count($PSD[$m*3-2])-$downsample){
echo "]}";
} else {
echo ",";
}
}
if ($m <> count($trackdata)-1){
echo ",";
} else if ($k<1){
echo ",";
}
}
}
echo "];";
?>
var options = {
legend: {
show: true
},
series: {
points: {
show: false
},
lines: {
show: true
}
},
grid: {
hoverable: true
},
xaxis: {
},
yaxis: {
}
};
var i = 0;
var track = 0;
choiceContainer = $("#labeler<?php echo $i ?>");
var table = $('<table />');
var row = $('<tr/>');
var cell = $('<td width=\"100\"/>');
var temp = $(table);
$.each(results, function(key, val) {
track = track + 1;
val.color = i;
++i;
l = val.label;
if (track == 1){
temp.append(row);
row.append(cell);
cell.append('Left Channel');
} else if(track == <?php echo $tracks ?>){
row = $('<tr/>');
temp.append(row);
cell = $('<td width=\"100\">');
row.append(cell);
cell.append('Right Channel');
} //else if ((track == 7) or (track == 14) or (track == 21) or (track == 28) or (track == 35)){
//}
cell = $('<td width=\"60\"/>');
row.append(cell);
var bar = $('<div style=\"width:18px; white-space:nowrap; float:left\"><bar />');
cell.append(bar);
var inp = $('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked">');
cell.append(inp);
var bits = $('<label>', {
text: l,
'for': l
});
cell.append(bits);
choiceContainer.append(temp);
});
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function() {
var key = this.name;
for (var i = 0; i < results.length; i++) {
if (results[i].label === key) {
data.push(results[i]);
return true;
}
}
});
$.plot($("#placeholder<?php echo $i ?>"), data, options);
}
var previousPoint = null;
$("#placeholder<?php echo $i ?>").bind("plothover", function(event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " $" + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #fdd',
padding: '2px',
backgroundColor: '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
plotAccordingToChoices();
choiceContainer.find("input").change(plotAccordingToChoices);
$('.legendColorBox > div').each(function(i){
$(this).clone().prependTo(choiceContainer.find("bar").eq(i));
});
});//]]>
</script>
Okay.. so the dust settled and I did sort out my issue, along with cleaning up a few things. First of all, I created a function for the plot routine. This uncovered the issue I was having, where I was reusing the same variables for the divs into which the data was going, hence the mixed up results. By creating the function, and then driving the function with custom variables for each iteration, the plots operate independently as they should. – Mark
function flotplot(results, choiceContainer, plotholder, numtracks, legendcontainer){
// pass in results, choicecontainer, plotholder
// results = data
// choiceContainer = $("#labeler1");
// plotholder = $("#placeholder0");
var options = {
legend: {
show: true,
container: legendcontainer,
noColumns: 2,
sorted: false
},
series: {
points: {
show: false
},
lines: {
show: true
}
},
grid: {
hoverable: true
},
xaxes: [{
axisLabel: 'Frequency (Hz)',
}],
yaxes: [{
axisLabel: 'Power (dB)',
}],
crosshair: {
mode: "xy",
color: 001,
lineWidth: .5
}
};
var i = 0;
var track = 0;
var table = $('<table />');
var row = $('<tr/>');
var cell = $('<td width=\"100\"/>');
var temp = $(table);
$.each(results, function(key, val) {
track = track + 1;
val.color = i;
++i;
l = val.label;
if (track == 1){
temp.append(row);
row.append(cell);
cell.append('Left Channel');
} else if(track == numtracks){
row = $('<tr/>');
temp.append(row);
cell = $('<td width=\"100\">');
row.append(cell);
cell.append('Right Channel');
} //else if ((track == 7) or (track == 14) or (track == 21) or (track == 28) or (track == 35)){
//}
cell = $('<td width=\"70\"/>');
row.append(cell);
var bar = $('<div style=\"width:18px; white-space:nowrap; float:left\"><bar />');
cell.append(bar);
var inp = $('<input name="' + l + '" id="' + l + '" type="checkbox" checked="checked">');
cell.append(inp);
var bits = $('<label>', {
text: l,
'for': l
});
cell.append(bits);
choiceContainer.append(temp);
});
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function() {
var key = this.name;
for (var i = 0; i < results.length; i++) {
if (results[i].label === key) {
data.push(results[i]);
return true;
}
}
});
$.plot(plotholder, data, options);
}
var previousPoint = null;
plotholder.bind("plothover", function(event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " " + y + "dB");
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #fdd',
padding: '2px',
backgroundColor: '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
plotAccordingToChoices();
choiceContainer.find("input").change(plotAccordingToChoices);
$('.legendColorBox > div').each(function(i){
$(this).clone().prependTo(choiceContainer.find("bar").eq(i));
});
};//]]>
Here is the structure into which it writes:
echo "<div id=\"placeholder".$i."\" class=\"loading\" style=\"width:600px;height:300px;display: inline; position: relative; float: left\"></div>";
echo "<div id=\"legendholder".$i."\" class=\"loading\" style=\"width:200px; height:300px; display: inline; position: relative; float: left\"></div>";
echo "<div id=\"picker1\" style=\"clear: both\"><p id=\"choices".$i."\">Show the following Tracks:</p></div>";
echo "<div id=\"labeler".$i."\"></div>";

Change date format in js for jquery datatable

I have this date in table: "2013-10-08T00:00:00"
I want to set it in format "dd.MM.yyyy"
in datatable source i changed like this:
{
"bSortable": true,
"mData": "PublishDate",
"bSearchable": true,
"mRender": function (data, type, row) {
if (data) {
debugger;
var re = /-?\d+/;
var m = re.exec(data);
var d = new Date(parseInt(m[0]));
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var formatedDate = curr_date + "/" + curr_month + "/" + curr_year + " " + d.getHours() + ":" + d.getMinutes();
return formatedDate;
}
else
return data
},
},
But it always return 1/1/1970 2:0
have any suggestions?
Try this:
var m = data.split(/[T-]/);
var d = new Date(parseInt(m[0]),parseInt(m[1])-1,parseInt(m[2]));
See: http://jsfiddle.net/vHTWL/

Resources