问:
Laravel get Images in Show User Template
I am trying to make my images table accessable from /users/show.blade.php.  I have this in my controlller..

```<code>public function show($id)
{

     /* Get All CSCS Images For User */
     $my_images= Image::all();

    /* Get User From ID */
    $user = User::find($id);

    /* Return View */
    return view('users.show')->with('user', $user)->with('images', $my_images);
}
</code>```

When I try and use the $my_images variable in my template I get an undefined variable error for $my_images

Where am I going wrong?

答:
You should try this:

```<code>public function show($id)
{

     /* Get All CSCS Images For User */
     $my_images= Image::all();

    /* Get User From ID */
    $user = User::find($id);

    /* Return View */
    return view('users.show',compact('user','my_images'));
}
</code>```

You pass $my_images name as image in your blade file for getting this error.

Body:
I am trying to make my images table accessable from /users/show.blade.php.  I have this in my controlller..

public function show($id)
{

     /* Get All CSCS Images For User */
     $my_images= Image::all();

    /* Get User From ID */
    $user = User::find($id);

    /* Return View */
    return view('users.show')->with('user', $user)->with('images', $my_images);
}

When I try and use the $my_images variable in my template I get an undefined variable error for $my_images

Where am I going wrong?

Body:
You should try this:

public function show($id)
{

     /* Get All CSCS Images For User */
     $my_images= Image::all();

    /* Get User From ID */
    $user = User::find($id);

    /* Return View */
    return view('users.show',compact('user','my_images'));
}

You pass $my_images name as image in your blade file for getting this error.


来源: stackexchange

问:
Does not work loop while in bash
I have logs in redmine, about users, that have connected from ip of my server. I can do this via command:

tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1

I need to write this parameter in variable.

No problem:

temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1)

It works. But it can return user name anonymous. To return other user name i should write head -n 2. If it still anonymous, i can change in my formula to head -n 3.

So ... of course i can do this work

```<code>#!/bin/bash
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1)

if [[ $temp == "anonymous" ]]; then
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 2 | tail -n 1)
fi
</code>```

But it will work for one iteration. I tried to:

```<code>while [ $tmp != "anonymous" ]; do
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n ((var=var+1)) | tail -n 1)
done
</code>```

But of course it does not work. I can't understand just logically, how can i do this ? Can you help me ? Thanks for your attention.

答:
You can also use grep -v :

```<code>temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | grep -v "anonymous" | awk '{print $3}' | head -n 1 )
</code>```

Note you don't need final tail -n 1 after head -n 1

ContentLicense: CC BY-SA 3.0

Title: Does not work loop while in bash

Body:
I have logs in redmine, about users, that have connected from ip of my server. I can do this via command:

tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1

I need to write this parameter in variable.

No problem:

temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1)

It works. But it can return user name anonymous. To return other user name i should write head -n 2. If it still anonymous, i can change in my formula to head -n 3.

So ... of course i can do this work

#!/bin/bash
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 1 | tail -n 1)

if [[ $temp == "anonymous" ]]; then
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n 2 | tail -n 1)
fi

But it will work for one iteration. I tried to:

while [ $tmp != "anonymous" ]; do
temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | awk '{print $3}' | head -n ((var=var+1)) | tail -n 1)
done

But of course it does not work. I can't understand just logically, how can i do this ? Can you help me ? Thanks for your attention.

Body:
You can also use grep -v :

temp=$(tail -n 100000 /usr/share/redmine/log/production.log | grep -A 3 "192.168.110.50" | grep "Current user" | grep -v "anonymous" | awk '{print $3}' | head -n 1 )

Note you don't need final tail -n 1 after head -n 1


问:
How do I execute a program or call a system command?
How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>

答: subprocess.check_call is convenient if you don't want to test return values. It throws an exception on any error.

OwnerDisplayName: alan lai

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
d3 - data - how to iterate over nested objects
i am trying to adapt the example in

http://bl.ocks.org/nbremer/62cf60e116ae821c06602793d265eaf6

to use a different data format as in accidents.js.

so instead of having

```<code>var accidents = [
  {day:2,hour:1,count:127},{day:4,hour:1,count:141},{day:1,hour:1,count:134},{day:5,hour:1,count:174},
  {day:3,hour:1,count:131},{day:6,hour:1,count:333},{day:7,hour:1,count:311},{day:2,hour:2,count:79},
  {day:4,hour:2,count:99},{day:1,hour:2,count:117},{day:5,hour:2,count:123},{day:3,hour:2,count:92},
  {day:6,hour:2,count:257},{day:7,hour:2,count:293},{day:2,hour:3,count:55},{day:4,hour:3,count:73},
  .
  .
  .
];
</code>```

I would like to use

```<code>var accidents_obj = {
  'Mon': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Tue': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  .
  .
  .
};
</code>```

but I'm unable to adapt the part of the code in which .attr("x" and .attr("y" are calculated to work with my data object:

```<code>var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });
</code>```

how do I have to iterate over accidents_obj to set .attr("x" and .attr("y" correctly?

full code in the hidden snippet below

/* accidents.js */
var accidents = [{
  day: 2,
  hour: 1,
  count: 127
}, {
  day: 4,
  hour: 1,
  count: 141
}, {
  day: 1,
  hour: 1,
  count: 134
}, {
  day: 5,
  hour: 1,
  count: 174
}, {
  day: 3,
  hour: 1,
  count: 131
}, {
  day: 6,
  hour: 1,
  count: 333
}, {
  day: 7,
  hour: 1,
  count: 311
}, {
  day: 2,
  hour: 2,
  count: 79
}, {
  day: 4,
  hour: 2,
  count: 99
}, {
  day: 1,
  hour: 2,
  count: 117
}, {
  day: 5,
  hour: 2,
  count: 123
}, {
  day: 3,
  hour: 2,
  count: 92
}, {
  day: 6,
  hour: 2,
  count: 257
}, {
  day: 7,
  hour: 2,
  count: 293
}, {
  day: 2,
  hour: 3,
  count: 55
}, {
  day: 4,
  hour: 3,
  count: 73
}, {
  day: 1,
  hour: 3,
  count: 107
}, {
  day: 5,
  hour: 3,
  count: 89
}, {
  day: 3,
  hour: 3,
  count: 66
}, {
  day: 6,
  hour: 3,
  count: 185
}, {
  day: 7,
  hour: 3,
  count: 262
}, {
  day: 2,
  hour: 4,
  count: 39
}, {
  day: 4,
  hour: 4,
  count: 67
}, {
  day: 1,
  hour: 4,
  count: 59
}, {
  day: 5,
  hour: 4,
  count: 83
}, {
  day: 3,
  hour: 4,
  count: 45
}, {
  day: 6,
  hour: 4,
  count: 180
}, {
  day: 7,
  hour: 4,
  count: 220
}, {
  day: 2,
  hour: 5,
  count: 48
}, {
  day: 4,
  hour: 5,
  count: 57
}, {
  day: 1,
  hour: 5,
  count: 73
}, {
  day: 5,
  hour: 5,
  count: 76
}, {
  day: 3,
  hour: 5,
  count: 72
}, {
  day: 6,
  hour: 5,
  count: 168
}, {
  day: 7,
  hour: 5,
  count: 199
}, {
  day: 2,
  hour: 6,
  count: 129
}, {
  day: 4,
  hour: 6,
  count: 102
}, {
  day: 1,
  hour: 6,
  count: 129
}, {
  day: 5,
  hour: 6,
  count: 140
}, {
  day: 3,
  hour: 6,
  count: 117
}, {
  day: 6,
  hour: 6,
  count: 148
}, {
  day: 7,
  hour: 6,
  count: 193
}, {
  day: 2,
  hour: 7,
  count: 314
}, {
  day: 4,
  hour: 7,
  count: 284
}, {
  day: 1,
  hour: 7,
  count: 367
}, {
  day: 5,
  hour: 7,
  count: 270
}, {
  day: 3,
  hour: 7,
  count: 310
}, {
  day: 6,
  hour: 7,
  count: 179
}, {
  day: 7,
  hour: 7,
  count: 192
}, {
  day: 2,
  hour: 8,
  count: 806
}, {
  day: 4,
  hour: 8,
  count: 811
}, {
  day: 1,
  hour: 8,
  count: 850
}, {
  day: 5,
  hour: 8,
  count: 609
}, {
  day: 3,
  hour: 8,
  count: 846
}, {
  day: 6,
  hour: 8,
  count: 208
}, {
  day: 7,
  hour: 8,
  count: 144
}, {
  day: 2,
  hour: 9,
  count: 1209
}, {
  day: 4,
  hour: 9,
  count: 1214
}, {
  day: 1,
  hour: 9,
  count: 1205
}, {
  day: 5,
  hour: 9,
  count: 960
}, {
  day: 3,
  hour: 9,
  count: 1073
}, {
  day: 6,
  hour: 9,
  count: 286
}, {
  day: 7,
  hour: 9,
  count: 152
}, {
  day: 2,
  hour: 10,
  count: 750
}, {
  day: 4,
  hour: 10,
  count: 808
}, {
  day: 1,
  hour: 10,
  count: 610
}, {
  day: 5,
  hour: 10,
  count: 655
}, {
  day: 3,
  hour: 10,
  count: 684
}, {
  day: 6,
  hour: 10,
  count: 482
}, {
  day: 7,
  hour: 10,
  count: 253
}, {
  day: 2,
  hour: 11,
  count: 591
}, {
  day: 4,
  hour: 11,
  count: 593
}, {
  day: 1,
  hour: 11,
  count: 573
}, {
  day: 5,
  hour: 11,
  count: 695
}, {
  day: 3,
  hour: 11,
  count: 622
}, {
  day: 6,
  hour: 11,
  count: 676
}, {
  day: 7,
  hour: 11,
  count: 326
}, {
  day: 2,
  hour: 12,
  count: 653
}, {
  day: 4,
  hour: 12,
  count: 679
}, {
  day: 1,
  hour: 12,
  count: 639
}, {
  day: 5,
  hour: 12,
  count: 736
}, {
  day: 3,
  hour: 12,
  count: 687
}, {
  day: 6,
  hour: 12,
  count: 858
}, {
  day: 7,
  hour: 12,
  count: 402
}, {
  day: 2,
  hour: 13,
  count: 738
}, {
  day: 4,
  hour: 13,
  count: 749
}, {
  day: 1,
  hour: 13,
  count: 631
}, {
  day: 5,
  hour: 13,
  count: 908
}, {
  day: 3,
  hour: 13,
  count: 888
}, {
  day: 6,
  hour: 13,
  count: 880
}, {
  day: 7,
  hour: 13,
  count: 507
}, {
  day: 2,
  hour: 14,
  count: 792
}, {
  day: 4,
  hour: 14,
  count: 847
}, {
  day: 1,
  hour: 14,
  count: 752
}, {
  day: 5,
  hour: 14,
  count: 1033
}, {
  day: 3,
  hour: 14,
  count: 942
}, {
  day: 6,
  hour: 14,
  count: 983
}, {
  day: 7,
  hour: 14,
  count: 636
}, {
  day: 2,
  hour: 15,
  count: 906
}, {
  day: 4,
  hour: 15,
  count: 1031
}, {
  day: 1,
  hour: 15,
  count: 954
}, {
  day: 5,
  hour: 15,
  count: 1199
}, {
  day: 3,
  hour: 15,
  count: 1014
}, {
  day: 6,
  hour: 15,
  count: 1125
}, {
  day: 7,
  hour: 15,
  count: 712
}, {
  day: 2,
  hour: 16,
  count: 1101
}, {
  day: 4,
  hour: 16,
  count: 1158
}, {
  day: 1,
  hour: 16,
  count: 1029
}, {
  day: 5,
  hour: 16,
  count: 1364
}, {
  day: 3,
  hour: 16,
  count: 1068
}, {
  day: 6,
  hour: 16,
  count: 1062
}, {
  day: 7,
  hour: 16,
  count: 736
}, {
  day: 2,
  hour: 17,
  count: 1303
}, {
  day: 4,
  hour: 17,
  count: 1426
}, {
  day: 1,
  hour: 17,
  count: 1270
}, {
  day: 5,
  hour: 17,
  count: 1455
}, {
  day: 3,
  hour: 17,
  count: 1407
}, {
  day: 6,
  hour: 17,
  count: 883
}, {
  day: 7,
  hour: 17,
  count: 666
}, {
  day: 2,
  hour: 18,
  count: 1549
}, {
  day: 4,
  hour: 18,
  count: 1653
}, {
  day: 1,
  hour: 18,
  count: 1350
}, {
  day: 5,
  hour: 18,
  count: 1502
}, {
  day: 3,
  hour: 18,
  count: 1507
}, {
  day: 6,
  hour: 18,
  count: 830
}, {
  day: 7,
  hour: 18,
  count: 652
}, {
  day: 2,
  hour: 19,
  count: 998
}, {
  day: 4,
  hour: 19,
  count: 1070
}, {
  day: 1,
  hour: 19,
  count: 787
}, {
  day: 5,
  hour: 19,
  count: 1027
}, {
  day: 3,
  hour: 19,
  count: 1019
}, {
  day: 6,
  hour: 19,
  count: 575
}, {
  day: 7,
  hour: 19,
  count: 519
}, {
  day: 2,
  hour: 20,
  count: 661
}, {
  day: 4,
  hour: 20,
  count: 756
}, {
  day: 1,
  hour: 20,
  count: 596
}, {
  day: 5,
  hour: 20,
  count: 730
}, {
  day: 3,
  hour: 20,
  count: 648
}, {
  day: 6,
  hour: 20,
  count: 494
}, {
  day: 7,
  hour: 20,
  count: 486
}, {
  day: 2,
  hour: 21,
  count: 431
}, {
  day: 4,
  hour: 21,
  count: 539
}, {
  day: 1,
  hour: 21,
  count: 430
}, {
  day: 5,
  hour: 21,
  count: 509
}, {
  day: 3,
  hour: 21,
  count: 457
}, {
  day: 6,
  hour: 21,
  count: 443
}, {
  day: 7,
  hour: 21,
  count: 421
}, {
  day: 2,
  hour: 22,
  count: 352
}, {
  day: 4,
  hour: 22,
  count: 428
}, {
  day: 1,
  hour: 22,
  count: 362
}, {
  day: 5,
  hour: 22,
  count: 462
}, {
  day: 3,
  hour: 22,
  count: 390
}, {
  day: 6,
  hour: 22,
  count: 379
}, {
  day: 7,
  hour: 22,
  count: 324
}, {
  day: 2,
  hour: 23,
  count: 329
}, {
  day: 4,
  hour: 23,
  count: 381
}, {
  day: 1,
  hour: 23,
  count: 293
}, {
  day: 5,
  hour: 23,
  count: 393
}, {
  day: 3,
  hour: 23,
  count: 313
}, {
  day: 6,
  hour: 23,
  count: 374
}, {
  day: 7,
  hour: 23,
  count: 288
}, {
  day: 2,
  hour: 24,
  count: 211
}, {
  day: 4,
  hour: 24,
  count: 249
}, {
  day: 1,
  hour: 24,
  count: 204
}, {
  day: 5,
  hour: 24,
  count: 417
}, {
  day: 3,
  hour: 24,
  count: 211
}, {
  day: 6,
  hour: 24,
  count: 379
}, {
  day: 7,
  hour: 24,
  count: 203
}];

/* script.js */
///////////////////////////////////////////////////////////////////////////
//////////////////// Set up and initiate svg containers ///////////////////
///////////////////////////////////////////////////////////////////////////

var days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  times = d3.range(24);

var margin = {
  top: 170,
  right: 50,
  bottom: 70,
  left: 50
};

var width = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
  gridSize = Math.floor(width / times.length),
  height = gridSize * (days.length + 2);

//SVG container
var svg = d3.select('#trafficAccidents')
  .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 + ")");

//Reset the overall font size
var newFontSize = width * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");

///////////////////////////////////////////////////////////////////////////
//////////////////////////// Draw Heatmap /////////////////////////////////
///////////////////////////////////////////////////////////////////////////

//Based on the heatmap example of: http://blockbuilder.org/milroc/7014412

var colorScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  }) / 2, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range(["#FFFFDD", "#3E9583", "#1F2D86"])
//.interpolate(d3.interpolateHcl);

var dayLabels = svg.selectAll(".dayLabel")
  .data(days)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", 0)
  .attr("y", function(d, i) {
    return i * gridSize;
  })
  .style("text-anchor", "end")
  .attr("transform", "translate(-6," + gridSize / 1.5 + ")")
  .attr("class", function(d, i) {
    return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
  });

var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", function(d, i) {
    return i * gridSize;
  })
  .attr("y", 0)
  .style("text-anchor", "middle")
  .attr("transform", "translate(" + gridSize / 2 + ", -6)")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 17) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
  });

var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });

//Append title to the top
svg.append("text")
  .attr("class", "title")
  .attr("x", width / 2)
  .attr("y", -90)
  .style("text-anchor", "middle")
  .text("Number of Traffic accidents per Day & Hour combination");
svg.append("text")
  .attr("class", "subtitle")
  .attr("x", width / 2)
  .attr("y", -60)
  .style("text-anchor", "middle")
  .text("The Netherlands | 2014");

//Append credit at bottom
svg.append("text")
  .attr("class", "credit")
  .attr("x", width / 2)
  .attr("y", gridSize * (days.length + 1) + 80)
  .style("text-anchor", "middle")
  .text("Based on Miles McCrocklin's Heatmap block");

///////////////////////////////////////////////////////////////////////////
//////////////// Create the gradient for the legend ///////////////////////
///////////////////////////////////////////////////////////////////////////

//Extra scale since the color scale is interpolated
var countScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range([0, width])

//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for (var i = 0; i < numStops; i++) {
  countPoint.push(i * countRange[2] / (numStops - 1) + countRange[0]);
} //for i

//Create the gradient
svg.append("defs")
  .append("linearGradient")
  .attr("id", "legend-traffic")
  .attr("x1", "0%").attr("y1", "0%")
  .attr("x2", "100%").attr("y2", "0%")
  .selectAll("stop")
  .data(d3.range(numStops))
  .enter().append("stop")
  .attr("offset", function(d, i) {
    return countScale(countPoint[i]) / width;
  })
  .attr("stop-color", function(d, i) {
    return colorScale(countPoint[i]);
  });

///////////////////////////////////////////////////////////////////////////
////////////////////////// Draw the legend ////////////////////////////////
///////////////////////////////////////////////////////////////////////////

var legendWidth = Math.min(width * 0.8, 400);
//Color Legend container
var legendsvg = svg.append("g")
  .attr("class", "legendWrapper")
  .attr("transform", "translate(" + (width / 2) + "," + (gridSize * days.length + 40) + ")");

//Draw the Rectangle
legendsvg.append("rect")
  .attr("class", "legendRect")
  .attr("x", -legendWidth / 2)
  .attr("y", 0)
  //.attr("rx", hexRadius*1.25/2)
  .attr("width", legendWidth)
  .attr("height", 10)
  .style("fill", "url(#legend-traffic)");

//Append title
legendsvg.append("text")
  .attr("class", "legendTitle")
  .attr("x", 0)
  .attr("y", -10)
  .style("text-anchor", "middle")
  .text("Number of Accidents");

//Set scale for x-axis
var xScale = d3.scale.linear()
  .range([-legendWidth / 2, legendWidth / 2])
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })]);

//Define x-axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .ticks(5)
  //.tickFormat(formatPercent)
  .scale(xScale);

//Set up X axis
legendsvg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + (10) + ")")
  .call(xAxis);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  font-size: 62.5%;
}

body {
  font-size: 1rem;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  fill: #8C8C8C;
  text-align: center;
}

.timeLabel,
.dayLabel {
  font-size: 1.6rem;
  fill: #AAAAAA;
  font-weight: 300;
}

text.axis-workweek,
text.axis-worktime {
  fill: #404040;
  font-weight: 400;
}

.title {
  font-size: 2.8rem;
  fill: #4F4F4F;
  font-weight: 300;
}

.subtitle {
  font-size: 1.4rem;
  fill: #AAAAAA;
  font-weight: 300;
}

.credit {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.axis path,
.axis tick,
.axis line {
  fill: none;
  stroke: none;
}

text {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.legendTitle {
  font-size: 1.6rem;
  fill: #4F4F4F;
  font-weight: 300;
}</code>```

```

Body:
i am trying to adapt the example in

http://bl.ocks.org/nbremer/62cf60e116ae821c06602793d265eaf6

to use a different data format as in accidents.js.

so instead of having

var accidents = [
  {day:2,hour:1,count:127},{day:4,hour:1,count:141},{day:1,hour:1,count:134},{day:5,hour:1,count:174},
  {day:3,hour:1,count:131},{day:6,hour:1,count:333},{day:7,hour:1,count:311},{day:2,hour:2,count:79},
  {day:4,hour:2,count:99},{day:1,hour:2,count:117},{day:5,hour:2,count:123},{day:3,hour:2,count:92},
  {day:6,hour:2,count:257},{day:7,hour:2,count:293},{day:2,hour:3,count:55},{day:4,hour:3,count:73},
  .
  .
  .
];

I would like to use

var accidents_obj = {
  'Mon': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Tue': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  .
  .
  .
};

but I'm unable to adapt the part of the code in which .attr("x" and .attr("y" are calculated to work with my data object:

var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });

how do I have to iterate over accidents_obj to set .attr("x" and .attr("y" correctly?

full code in the hidden snippet below

/* accidents.js */
var accidents = [{
  day: 2,
  hour: 1,
  count: 127
}, {
  day: 4,
  hour: 1,
  count: 141
}, {
  day: 1,
  hour: 1,
  count: 134
}, {
  day: 5,
  hour: 1,
  count: 174
}, {
  day: 3,
  hour: 1,
  count: 131
}, {
  day: 6,
  hour: 1,
  count: 333
}, {
  day: 7,
  hour: 1,
  count: 311
}, {
  day: 2,
  hour: 2,
  count: 79
}, {
  day: 4,
  hour: 2,
  count: 99
}, {
  day: 1,
  hour: 2,
  count: 117
}, {
  day: 5,
  hour: 2,
  count: 123
}, {
  day: 3,
  hour: 2,
  count: 92
}, {
  day: 6,
  hour: 2,
  count: 257
}, {
  day: 7,
  hour: 2,
  count: 293
}, {
  day: 2,
  hour: 3,
  count: 55
}, {
  day: 4,
  hour: 3,
  count: 73
}, {
  day: 1,
  hour: 3,
  count: 107
}, {
  day: 5,
  hour: 3,
  count: 89
}, {
  day: 3,
  hour: 3,
  count: 66
}, {
  day: 6,
  hour: 3,
  count: 185
}, {
  day: 7,
  hour: 3,
  count: 262
}, {
  day: 2,
  hour: 4,
  count: 39
}, {
  day: 4,
  hour: 4,
  count: 67
}, {
  day: 1,
  hour: 4,
  count: 59
}, {
  day: 5,
  hour: 4,
  count: 83
}, {
  day: 3,
  hour: 4,
  count: 45
}, {
  day: 6,
  hour: 4,
  count: 180
}, {
  day: 7,
  hour: 4,
  count: 220
}, {
  day: 2,
  hour: 5,
  count: 48
}, {
  day: 4,
  hour: 5,
  count: 57
}, {
  day: 1,
  hour: 5,
  count: 73
}, {
  day: 5,
  hour: 5,
  count: 76
}, {
  day: 3,
  hour: 5,
  count: 72
}, {
  day: 6,
  hour: 5,
  count: 168
}, {
  day: 7,
  hour: 5,
  count: 199
}, {
  day: 2,
  hour: 6,
  count: 129
}, {
  day: 4,
  hour: 6,
  count: 102
}, {
  day: 1,
  hour: 6,
  count: 129
}, {
  day: 5,
  hour: 6,
  count: 140
}, {
  day: 3,
  hour: 6,
  count: 117
}, {
  day: 6,
  hour: 6,
  count: 148
}, {
  day: 7,
  hour: 6,
  count: 193
}, {
  day: 2,
  hour: 7,
  count: 314
}, {
  day: 4,
  hour: 7,
  count: 284
}, {
  day: 1,
  hour: 7,
  count: 367
}, {
  day: 5,
  hour: 7,
  count: 270
}, {
  day: 3,
  hour: 7,
  count: 310
}, {
  day: 6,
  hour: 7,
  count: 179
}, {
  day: 7,
  hour: 7,
  count: 192
}, {
  day: 2,
  hour: 8,
  count: 806
}, {
  day: 4,
  hour: 8,
  count: 811
}, {
  day: 1,
  hour: 8,
  count: 850
}, {
  day: 5,
  hour: 8,
  count: 609
}, {
  day: 3,
  hour: 8,
  count: 846
}, {
  day: 6,
  hour: 8,
  count: 208
}, {
  day: 7,
  hour: 8,
  count: 144
}, {
  day: 2,
  hour: 9,
  count: 1209
}, {
  day: 4,
  hour: 9,
  count: 1214
}, {
  day: 1,
  hour: 9,
  count: 1205
}, {
  day: 5,
  hour: 9,
  count: 960
}, {
  day: 3,
  hour: 9,
  count: 1073
}, {
  day: 6,
  hour: 9,
  count: 286
}, {
  day: 7,
  hour: 9,
  count: 152
}, {
  day: 2,
  hour: 10,
  count: 750
}, {
  day: 4,
  hour: 10,
  count: 808
}, {
  day: 1,
  hour: 10,
  count: 610
}, {
  day: 5,
  hour: 10,
  count: 655
}, {
  day: 3,
  hour: 10,
  count: 684
}, {
  day: 6,
  hour: 10,
  count: 482
}, {
  day: 7,
  hour: 10,
  count: 253
}, {
  day: 2,
  hour: 11,
  count: 591
}, {
  day: 4,
  hour: 11,
  count: 593
}, {
  day: 1,
  hour: 11,
  count: 573
}, {
  day: 5,
  hour: 11,
  count: 695
}, {
  day: 3,
  hour: 11,
  count: 622
}, {
  day: 6,
  hour: 11,
  count: 676
}, {
  day: 7,
  hour: 11,
  count: 326
}, {
  day: 2,
  hour: 12,
  count: 653
}, {
  day: 4,
  hour: 12,
  count: 679
}, {
  day: 1,
  hour: 12,
  count: 639
}, {
  day: 5,
  hour: 12,
  count: 736
}, {
  day: 3,
  hour: 12,
  count: 687
}, {
  day: 6,
  hour: 12,
  count: 858
}, {
  day: 7,
  hour: 12,
  count: 402
}, {
  day: 2,
  hour: 13,
  count: 738
}, {
  day: 4,
  hour: 13,
  count: 749
}, {
  day: 1,
  hour: 13,
  count: 631
}, {
  day: 5,
  hour: 13,
  count: 908
}, {
  day: 3,
  hour: 13,
  count: 888
}, {
  day: 6,
  hour: 13,
  count: 880
}, {
  day: 7,
  hour: 13,
  count: 507
}, {
  day: 2,
  hour: 14,
  count: 792
}, {
  day: 4,
  hour: 14,
  count: 847
}, {
  day: 1,
  hour: 14,
  count: 752
}, {
  day: 5,
  hour: 14,
  count: 1033
}, {
  day: 3,
  hour: 14,
  count: 942
}, {
  day: 6,
  hour: 14,
  count: 983
}, {
  day: 7,
  hour: 14,
  count: 636
}, {
  day: 2,
  hour: 15,
  count: 906
}, {
  day: 4,
  hour: 15,
  count: 1031
}, {
  day: 1,
  hour: 15,
  count: 954
}, {
  day: 5,
  hour: 15,
  count: 1199
}, {
  day: 3,
  hour: 15,
  count: 1014
}, {
  day: 6,
  hour: 15,
  count: 1125
}, {
  day: 7,
  hour: 15,
  count: 712
}, {
  day: 2,
  hour: 16,
  count: 1101
}, {
  day: 4,
  hour: 16,
  count: 1158
}, {
  day: 1,
  hour: 16,
  count: 1029
}, {
  day: 5,
  hour: 16,
  count: 1364
}, {
  day: 3,
  hour: 16,
  count: 1068
}, {
  day: 6,
  hour: 16,
  count: 1062
}, {
  day: 7,
  hour: 16,
  count: 736
}, {
  day: 2,
  hour: 17,
  count: 1303
}, {
  day: 4,
  hour: 17,
  count: 1426
}, {
  day: 1,
  hour: 17,
  count: 1270
}, {
  day: 5,
  hour: 17,
  count: 1455
}, {
  day: 3,
  hour: 17,
  count: 1407
}, {
  day: 6,
  hour: 17,
  count: 883
}, {
  day: 7,
  hour: 17,
  count: 666
}, {
  day: 2,
  hour: 18,
  count: 1549
}, {
  day: 4,
  hour: 18,
  count: 1653
}, {
  day: 1,
  hour: 18,
  count: 1350
}, {
  day: 5,
  hour: 18,
  count: 1502
}, {
  day: 3,
  hour: 18,
  count: 1507
}, {
  day: 6,
  hour: 18,
  count: 830
}, {
  day: 7,
  hour: 18,
  count: 652
}, {
  day: 2,
  hour: 19,
  count: 998
}, {
  day: 4,
  hour: 19,
  count: 1070
}, {
  day: 1,
  hour: 19,
  count: 787
}, {
  day: 5,
  hour: 19,
  count: 1027
}, {
  day: 3,
  hour: 19,
  count: 1019
}, {
  day: 6,
  hour: 19,
  count: 575
}, {
  day: 7,
  hour: 19,
  count: 519
}, {
  day: 2,
  hour: 20,
  count: 661
}, {
  day: 4,
  hour: 20,
  count: 756
}, {
  day: 1,
  hour: 20,
  count: 596
}, {
  day: 5,
  hour: 20,
  count: 730
}, {
  day: 3,
  hour: 20,
  count: 648
}, {
  day: 6,
  hour: 20,
  count: 494
}, {
  day: 7,
  hour: 20,
  count: 486
}, {
  day: 2,
  hour: 21,
  count: 431
}, {
  day: 4,
  hour: 21,
  count: 539
}, {
  day: 1,
  hour: 21,
  count: 430
}, {
  day: 5,
  hour: 21,
  count: 509
}, {
  day: 3,
  hour: 21,
  count: 457
}, {
  day: 6,
  hour: 21,
  count: 443
}, {
  day: 7,
  hour: 21,
  count: 421
}, {
  day: 2,
  hour: 22,
  count: 352
}, {
  day: 4,
  hour: 22,
  count: 428
}, {
  day: 1,
  hour: 22,
  count: 362
}, {
  day: 5,
  hour: 22,
  count: 462
}, {
  day: 3,
  hour: 22,
  count: 390
}, {
  day: 6,
  hour: 22,
  count: 379
}, {
  day: 7,
  hour: 22,
  count: 324
}, {
  day: 2,
  hour: 23,
  count: 329
}, {
  day: 4,
  hour: 23,
  count: 381
}, {
  day: 1,
  hour: 23,
  count: 293
}, {
  day: 5,
  hour: 23,
  count: 393
}, {
  day: 3,
  hour: 23,
  count: 313
}, {
  day: 6,
  hour: 23,
  count: 374
}, {
  day: 7,
  hour: 23,
  count: 288
}, {
  day: 2,
  hour: 24,
  count: 211
}, {
  day: 4,
  hour: 24,
  count: 249
}, {
  day: 1,
  hour: 24,
  count: 204
}, {
  day: 5,
  hour: 24,
  count: 417
}, {
  day: 3,
  hour: 24,
  count: 211
}, {
  day: 6,
  hour: 24,
  count: 379
}, {
  day: 7,
  hour: 24,
  count: 203
}];

/* script.js */
///////////////////////////////////////////////////////////////////////////
//////////////////// Set up and initiate svg containers ///////////////////
///////////////////////////////////////////////////////////////////////////

var days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  times = d3.range(24);

var margin = {
  top: 170,
  right: 50,
  bottom: 70,
  left: 50
};

var width = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
  gridSize = Math.floor(width / times.length),
  height = gridSize * (days.length + 2);

//SVG container
var svg = d3.select('#trafficAccidents')
  .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 + ")");

//Reset the overall font size
var newFontSize = width * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");

///////////////////////////////////////////////////////////////////////////
//////////////////////////// Draw Heatmap /////////////////////////////////
///////////////////////////////////////////////////////////////////////////

//Based on the heatmap example of: http://blockbuilder.org/milroc/7014412

var colorScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  }) / 2, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range(["#FFFFDD", "#3E9583", "#1F2D86"])
//.interpolate(d3.interpolateHcl);

var dayLabels = svg.selectAll(".dayLabel")
  .data(days)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", 0)
  .attr("y", function(d, i) {
    return i * gridSize;
  })
  .style("text-anchor", "end")
  .attr("transform", "translate(-6," + gridSize / 1.5 + ")")
  .attr("class", function(d, i) {
    return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
  });

var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", function(d, i) {
    return i * gridSize;
  })
  .attr("y", 0)
  .style("text-anchor", "middle")
  .attr("transform", "translate(" + gridSize / 2 + ", -6)")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 17) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
  });

var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });

//Append title to the top
svg.append("text")
  .attr("class", "title")
  .attr("x", width / 2)
  .attr("y", -90)
  .style("text-anchor", "middle")
  .text("Number of Traffic accidents per Day & Hour combination");
svg.append("text")
  .attr("class", "subtitle")
  .attr("x", width / 2)
  .attr("y", -60)
  .style("text-anchor", "middle")
  .text("The Netherlands | 2014");

//Append credit at bottom
svg.append("text")
  .attr("class", "credit")
  .attr("x", width / 2)
  .attr("y", gridSize * (days.length + 1) + 80)
  .style("text-anchor", "middle")
  .text("Based on Miles McCrocklin's Heatmap block");

///////////////////////////////////////////////////////////////////////////
//////////////// Create the gradient for the legend ///////////////////////
///////////////////////////////////////////////////////////////////////////

//Extra scale since the color scale is interpolated
var countScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range([0, width])

//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for (var i = 0; i < numStops; i++) {
  countPoint.push(i * countRange[2] / (numStops - 1) + countRange[0]);
} //for i

//Create the gradient
svg.append("defs")
  .append("linearGradient")
  .attr("id", "legend-traffic")
  .attr("x1", "0%").attr("y1", "0%")
  .attr("x2", "100%").attr("y2", "0%")
  .selectAll("stop")
  .data(d3.range(numStops))
  .enter().append("stop")
  .attr("offset", function(d, i) {
    return countScale(countPoint[i]) / width;
  })
  .attr("stop-color", function(d, i) {
    return colorScale(countPoint[i]);
  });

///////////////////////////////////////////////////////////////////////////
////////////////////////// Draw the legend ////////////////////////////////
///////////////////////////////////////////////////////////////////////////

var legendWidth = Math.min(width * 0.8, 400);
//Color Legend container
var legendsvg = svg.append("g")
  .attr("class", "legendWrapper")
  .attr("transform", "translate(" + (width / 2) + "," + (gridSize * days.length + 40) + ")");

//Draw the Rectangle
legendsvg.append("rect")
  .attr("class", "legendRect")
  .attr("x", -legendWidth / 2)
  .attr("y", 0)
  //.attr("rx", hexRadius*1.25/2)
  .attr("width", legendWidth)
  .attr("height", 10)
  .style("fill", "url(#legend-traffic)");

//Append title
legendsvg.append("text")
  .attr("class", "legendTitle")
  .attr("x", 0)
  .attr("y", -10)
  .style("text-anchor", "middle")
  .text("Number of Accidents");

//Set scale for x-axis
var xScale = d3.scale.linear()
  .range([-legendWidth / 2, legendWidth / 2])
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })]);

//Define x-axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .ticks(5)
  //.tickFormat(formatPercent)
  .scale(xScale);

//Set up X axis
legendsvg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + (10) + ")")
  .call(xAxis);

html {
  font-size: 62.5%;
}

body {
  font-size: 1rem;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  fill: #8C8C8C;
  text-align: center;
}

.timeLabel,
.dayLabel {
  font-size: 1.6rem;
  fill: #AAAAAA;
  font-weight: 300;
}

text.axis-workweek,
text.axis-worktime {
  fill: #404040;
  font-weight: 400;
}

.title {
  font-size: 2.8rem;
  fill: #4F4F4F;
  font-weight: 300;
}

.subtitle {
  font-size: 1.4rem;
  fill: #AAAAAA;
  font-weight: 300;
}

.credit {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.axis path,
.axis tick,
.axis line {
  fill: none;
  stroke: none;
}

text {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.legendTitle {
  font-size: 1.6rem;
  fill: #4F4F4F;
  font-weight: 300;
}

Body:
You can rearrange your data to the structure that is used in blocks which you mention this way:

function getAccidents(data) {
    var result = [];

  Object.keys(data).forEach(function(dayName, index) {
    Object.keys(data[dayName]).forEach(function(hour, index) {
      result.push({
        hour: hour,
        day: Object.keys(data).indexOf(dayName) + 1,
        count: data[dayName][hour]
      })
    });
  });

    return result;
}

var accidents = getAccidents(accidents_obj);

Look at the working example in hidden snippets below:

First of this data structure:

{
  'Mon': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  ...
}

var accidents_obj = {
  'Mon': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Tue': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Wed': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Thu': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Fri': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Sat': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  'Sun': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
};

function getAccidents(data) {
 var result = [];

  Object.keys(data).forEach(function(dayName, index) {
    Object.keys(data[dayName]).forEach(function(hour, index) {
      result.push({
        hour: hour,
        day: Object.keys(data).indexOf(dayName) + 1,
        count: data[dayName][hour]
      })
    });
  });

 return result;
}

var accidents = getAccidents(accidents_obj);

var labels = Object.keys(accidents_obj),
  times = d3.range(24);

var margin = {
  top: 170,
  right: 50,
  bottom: 70,
  left: 70
};

var width = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
  gridSize = Math.floor(width / times.length),
  height = gridSize * (labels.length + 2);

//SVG container
var svg = d3.select('#trafficAccidents')
  .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 + ")");

//Reset the overall font size
var newFontSize = width * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");

///////////////////////////////////////////////////////////////////////////
//////////////////////////// Draw Heatmap /////////////////////////////////
///////////////////////////////////////////////////////////////////////////

//Based on the heatmap example of: http://blockbuilder.org/milroc/7014412

var colorScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  }) / 2, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range(["#FFFFDD", "#3E9583", "#1F2D86"])
//.interpolate(d3.interpolateHcl);

var dayLabels = svg.selectAll(".dayLabel")
  .data(labels)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", 0)
  .attr("y", function(d, i) {
    return i * gridSize;
  })
  .style("text-anchor", "end")
  .attr("transform", "translate(-6," + gridSize / 1.5 + ")")
  .attr("class", function(d, i) {
    return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
  });

var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", function(d, i) {
    return i * gridSize;
  })
  .attr("y", 0)
  .style("text-anchor", "middle")
  .attr("transform", "translate(" + gridSize / 2 + ", -6)")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 17) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
  });

var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });

//Append title to the top
svg.append("text")
  .attr("class", "title")
  .attr("x", width / 2)
  .attr("y", -90)
  .style("text-anchor", "middle")
  .text("Number of Traffic accidents per Day & Hour combination");
svg.append("text")
  .attr("class", "subtitle")
  .attr("x", width / 2)
  .attr("y", -60)
  .style("text-anchor", "middle")
  .text("The Netherlands | 2014");

//Append credit at bottom
svg.append("text")
  .attr("class", "credit")
  .attr("x", width / 2)
  .attr("y", gridSize * (labels.length + 1) + 80)
  .style("text-anchor", "middle")
  .text("Based on Miles McCrocklin's Heatmap block");

///////////////////////////////////////////////////////////////////////////
//////////////// Create the gradient for the legend ///////////////////////
///////////////////////////////////////////////////////////////////////////

//Extra scale since the color scale is interpolated
var countScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range([0, width])

//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for (var i = 0; i < numStops; i++) {
  countPoint.push(i * countRange[2] / (numStops - 1) + countRange[0]);
} //for i

//Create the gradient
svg.append("defs")
  .append("linearGradient")
  .attr("id", "legend-traffic")
  .attr("x1", "0%").attr("y1", "0%")
  .attr("x2", "100%").attr("y2", "0%")
  .selectAll("stop")
  .data(d3.range(numStops))
  .enter().append("stop")
  .attr("offset", function(d, i) {
    return countScale(countPoint[i]) / width;
  })
  .attr("stop-color", function(d, i) {
    return colorScale(countPoint[i]);
  });

///////////////////////////////////////////////////////////////////////////
////////////////////////// Draw the legend ////////////////////////////////
///////////////////////////////////////////////////////////////////////////

var legendWidth = Math.min(width * 0.8, 400);
//Color Legend container
var legendsvg = svg.append("g")
  .attr("class", "legendWrapper")
  .attr("transform", "translate(" + (width / 2) + "," + (gridSize * labels.length + 40) + ")");

//Draw the Rectangle
legendsvg.append("rect")
  .attr("class", "legendRect")
  .attr("x", -legendWidth / 2)
  .attr("y", 0)
  //.attr("rx", hexRadius*1.25/2)
  .attr("width", legendWidth)
  .attr("height", 10)
  .style("fill", "url(#legend-traffic)");

//Append title
legendsvg.append("text")
  .attr("class", "legendTitle")
  .attr("x", 0)
  .attr("y", -10)
  .style("text-anchor", "middle")
  .text("Number of Accidents");

//Set scale for x-axis
var xScale = d3.scale.linear()
  .range([-legendWidth / 2, legendWidth / 2])
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })]);

//Define x-axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .ticks(5)
  //.tickFormat(formatPercent)
  .scale(xScale);

//Set up X axis
legendsvg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + (10) + ")")
  .call(xAxis);

html {
  font-size: 62.5%;
}

body {
  font-size: 1rem;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  fill: #8C8C8C;
  text-align: center;
}

.timeLabel,
.dayLabel {
  font-size: 1.6rem;
  fill: #AAAAAA;
  font-weight: 300;
}

text.axis-workweek,
text.axis-worktime {
  fill: #404040;
  font-weight: 400;
}

.title {
  font-size: 2.8rem;
  fill: #4F4F4F;
  font-weight: 300;
}

.subtitle {
  font-size: 1.4rem;
  fill: #AAAAAA;
  font-weight: 300;
}

.credit {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.axis path,
.axis tick,
.axis line {
  fill: none;
  stroke: none;
}

text {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.legendTitle {
  font-size: 1.6rem;
  fill: #4F4F4F;
  font-weight: 300;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<div id="trafficAccidents"></div>

And second for that:

{
  '2017-11-10': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0}
  ...
}

var accidents_obj = {
  '2017-11-10': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-11': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-12': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-13': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-14': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-15': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-16': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-17': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-18': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-19': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-20': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-21': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-22': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-23': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-24': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-25': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-26': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-27': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-28': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-29': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-11-30': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-01': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-02': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-03': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-04': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-05': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-06': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
  '2017-12-07': {1: 0, 2: 1, 3: 2, 4: 1, 5: 2, 6: 2, 7: 4, 8: 3, 9: 4, 10: 4, 11: 2, 12: 10, 13: 9, 14: 9, 15: 1, 16: 10, 17: 5, 18: 2, 19: 2, 20: 4, 21: 6, 22: 2, 23: 2, 24: 0},
};

function getAccidents(data) {
 var result = [];

  Object.keys(data).forEach(function(dayName, index) {
    Object.keys(data[dayName]).forEach(function(hour, index) {
      result.push({
        hour: hour,
        day: Object.keys(data).indexOf(dayName) + 1,
        count: data[dayName][hour]
      })
    });
  });

 return result;
}

var accidents = getAccidents(accidents_obj);

var labels = Object.keys(accidents_obj),
  times = d3.range(24);

var margin = {
  top: 170,
  right: 50,
  bottom: 70,
  left: 70
};

var width = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
  gridSize = Math.floor(width / times.length),
  height = gridSize * (labels.length + 2);

//SVG container
var svg = d3.select('#trafficAccidents')
  .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 + ")");

//Reset the overall font size
var newFontSize = width * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");

///////////////////////////////////////////////////////////////////////////
//////////////////////////// Draw Heatmap /////////////////////////////////
///////////////////////////////////////////////////////////////////////////

//Based on the heatmap example of: http://blockbuilder.org/milroc/7014412

var colorScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  }) / 2, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range(["#FFFFDD", "#3E9583", "#1F2D86"])
//.interpolate(d3.interpolateHcl);

var dayLabels = svg.selectAll(".dayLabel")
  .data(labels)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", 0)
  .attr("y", function(d, i) {
    return i * gridSize;
  })
  .style("text-anchor", "end")
  .attr("transform", "translate(-6," + gridSize / 1.5 + ")")
  .attr("class", function(d, i) {
    return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
  });

var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
  .text(function(d) {
    return d;
  })
  .attr("x", function(d, i) {
    return i * gridSize;
  })
  .attr("y", 0)
  .style("text-anchor", "middle")
  .attr("transform", "translate(" + gridSize / 2 + ", -6)")
  .attr("class", function(d, i) {
    return ((i >= 8 && i <= 17) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
  });

var heatMap = svg.selectAll(".hour")
  .data(accidents)
  .enter().append("rect")
  .attr("x", function(d) {
    return (d.hour - 1) * gridSize;
  })
  .attr("y", function(d) {
    return (d.day - 1) * gridSize;
  })
  .attr("class", "hour bordered")
  .attr("width", gridSize)
  .attr("height", gridSize)
  .style("stroke", "white")
  .style("stroke-opacity", 0.6)
  .style("fill", function(d) {
    return colorScale(d.count);
  });

//Append title to the top
svg.append("text")
  .attr("class", "title")
  .attr("x", width / 2)
  .attr("y", -90)
  .style("text-anchor", "middle")
  .text("Number of Traffic accidents per Day & Hour combination");
svg.append("text")
  .attr("class", "subtitle")
  .attr("x", width / 2)
  .attr("y", -60)
  .style("text-anchor", "middle")
  .text("The Netherlands | 2014");

//Append credit at bottom
svg.append("text")
  .attr("class", "credit")
  .attr("x", width / 2)
  .attr("y", gridSize * (labels.length + 1) + 80)
  .style("text-anchor", "middle")
  .text("Based on Miles McCrocklin's Heatmap block");

///////////////////////////////////////////////////////////////////////////
//////////////// Create the gradient for the legend ///////////////////////
///////////////////////////////////////////////////////////////////////////

//Extra scale since the color scale is interpolated
var countScale = d3.scale.linear()
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })])
  .range([0, width])

//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for (var i = 0; i < numStops; i++) {
  countPoint.push(i * countRange[2] / (numStops - 1) + countRange[0]);
} //for i

//Create the gradient
svg.append("defs")
  .append("linearGradient")
  .attr("id", "legend-traffic")
  .attr("x1", "0%").attr("y1", "0%")
  .attr("x2", "100%").attr("y2", "0%")
  .selectAll("stop")
  .data(d3.range(numStops))
  .enter().append("stop")
  .attr("offset", function(d, i) {
    return countScale(countPoint[i]) / width;
  })
  .attr("stop-color", function(d, i) {
    return colorScale(countPoint[i]);
  });

///////////////////////////////////////////////////////////////////////////
////////////////////////// Draw the legend ////////////////////////////////
///////////////////////////////////////////////////////////////////////////

var legendWidth = Math.min(width * 0.8, 400);
//Color Legend container
var legendsvg = svg.append("g")
  .attr("class", "legendWrapper")
  .attr("transform", "translate(" + (width / 2) + "," + (gridSize * labels.length + 40) + ")");

//Draw the Rectangle
legendsvg.append("rect")
  .attr("class", "legendRect")
  .attr("x", -legendWidth / 2)
  .attr("y", 0)
  //.attr("rx", hexRadius*1.25/2)
  .attr("width", legendWidth)
  .attr("height", 10)
  .style("fill", "url(#legend-traffic)");

//Append title
legendsvg.append("text")
  .attr("class", "legendTitle")
  .attr("x", 0)
  .attr("y", -10)
  .style("text-anchor", "middle")
  .text("Number of Accidents");

//Set scale for x-axis
var xScale = d3.scale.linear()
  .range([-legendWidth / 2, legendWidth / 2])
  .domain([0, d3.max(accidents, function(d) {
    return d.count;
  })]);

//Define x-axis
var xAxis = d3.svg.axis()
  .orient("bottom")
  .ticks(5)
  //.tickFormat(formatPercent)
  .scale(xScale);

//Set up X axis
legendsvg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + (10) + ")")
  .call(xAxis);

html {
  font-size: 62.5%;
}

body {
  font-size: 1rem;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  fill: #8C8C8C;
  text-align: center;
}

.timeLabel,
.dayLabel {
  font-size: 1.6rem;
  fill: #AAAAAA;
  font-weight: 300;
}

text.axis-workweek,
text.axis-worktime {
  fill: #404040;
  font-weight: 400;
}

.title {
  font-size: 2.8rem;
  fill: #4F4F4F;
  font-weight: 300;
}

.subtitle {
  font-size: 1.4rem;
  fill: #AAAAAA;
  font-weight: 300;
}

.credit {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.axis path,
.axis tick,
.axis line {
  fill: none;
  stroke: none;
}

text {
  font-size: 1.2rem;
  fill: #AAAAAA;
  font-weight: 400;
}

.legendTitle {
  font-size: 1.6rem;
  fill: #4F4F4F;
  font-weight: 300;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<div id="trafficAccidents"></div>

The code for this two examples the same, only different keys of the initial data object.


问:
PHP PDO login code - repeats error, not able to login [ correct username and password is entered]
I am struggling to get the login code to run successfully.  It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered.  Am I missing something somewhere, please help.</p>

```<code>    <?php
//Check login details
    session_start();
    //get user input from the form
    if (isset($_POST['Submit'])) {
        $username = checkData($_POST['username']);
        $password = checkData($_POST['password']);

        require ('config.php'); //database connection
        global $dbselect;

        $qry = 'SELECT username, password
                FROM users
                WHERE username = :username AND password = :password
                LIMIT 1';
        $statement = $dbselect->prepare($qry);
        $statement->bindValue(':username', $username);
        $statement->bindValue(':password', $password);
        $statement->execute();
        $login = $statement->fetch(PDO::FETCH_ASSOC);
        if (count($login) > 0 && password_verify($password, $login['password'])) {
            $_SESSION['username'] = $login['username'];
            header('location:home.html');
        } else {
            echo "Username or Password incorrect. Please try again.";
        }
        $statement->closeCursor();
    }

    //validate data
    function checkData($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>
</code>```

答:
/**
     * You might need to save a hashed copy of the password at the point of
     * user creation, so that you can password_verify the input password against the hashed
     * copy returned from the DB.
     * something like this :
     * $hashed     = password_hash($password, PASSWORD_BCRYPT);
     * NOTE : I've changed you code to an extent, pls adapt.
     */</p>

```<code>//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
    $username   = checkData($username);
    $password   = checkData($password);

    $dbname     = "testo";
    $servername = "localhost";
    $conn       = new PDO("mysql:host=$servername;dbname=$dbname", "root", "");
    $parr       = array($username,$password);

    $qry = 'SELECT username, password, phashed
    FROM users
    WHERE username = ? AND password = ?
    LIMIT 1';

    $stmt       = $conn->prepare($qry);
    $Qres       = $stmt->execute($parr);
    $login      = ($Qres) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();

    if (count($login) > 0 && password_verify($password, $login[0]['phashed'])) {
        $_SESSION['username'] = $login[0]['username'];
        header('location:home.html');
    } else {
        echo "Username or Password incorrect. Please try again.";
    }
    $conn = null;
}

//validate data
function checkData($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
</code>```

Body:
I am struggling to get the login code to run successfully.  It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered.  Am I missing something somewhere, please help.

    <?php
//Check login details
    session_start();
    //get user input from the form
    if (isset($_POST['Submit'])) {
        $username = checkData($_POST['username']);
        $password = checkData($_POST['password']);

        require ('config.php'); //database connection
        global $dbselect;

        $qry = 'SELECT username, password
                FROM users
                WHERE username = :username AND password = :password
                LIMIT 1';
        $statement = $dbselect->prepare($qry);
        $statement->bindValue(':username', $username);
        $statement->bindValue(':password', $password);
        $statement->execute();
        $login = $statement->fetch(PDO::FETCH_ASSOC);
        if (count($login) > 0 && password_verify($password, $login['password'])) {
            $_SESSION['username'] = $login['username'];
            header('location:home.html');
        } else {
            echo "Username or Password incorrect. Please try again.";
        }
        $statement->closeCursor();
    }

    //validate data
    function checkData($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>

Body:
/**
     * You might need to save a hashed copy of the password at the point of
     * user creation, so that you can password_verify the input password against the hashed
     * copy returned from the DB.
     * something like this :
     * $hashed     = password_hash($password, PASSWORD_BCRYPT);
     * NOTE : I've changed you code to an extent, pls adapt.
     */

//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
    $username   = checkData($username);
    $password   = checkData($password);

    $dbname     = "testo";
    $servername = "localhost";
    $conn       = new PDO("mysql:host=$servername;dbname=$dbname", "root", "");
    $parr       = array($username,$password);

    $qry = 'SELECT username, password, phashed
    FROM users
    WHERE username = ? AND password = ?
    LIMIT 1';

    $stmt       = $conn->prepare($qry);
    $Qres       = $stmt->execute($parr);
    $login      = ($Qres) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();

    if (count($login) > 0 && password_verify($password, $login[0]['phashed'])) {
        $_SESSION['username'] = $login[0]['username'];
        header('location:home.html');
    } else {
        echo "Username or Password incorrect. Please try again.";
    }
    $conn = null;
}

//validate data
function checkData($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}


问:
PHP Singleton Acting Funny
I have the following code:

```<code>$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "```";
print_r(self::$extensions);
```

<p>Each getInstance() method looks like this:</p>

```public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}
```

<p>Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:</p>

```stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)
```

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

答:
Since self is resolving to MySQL_Extension, I'm assuming that each class has this method (rather than being defined in Extension_Abstract.  However, where is self::$_instance defined?  My instinct is that it's defined on Extension_Abstract.  Simply re-define it in each class (protected static $_instance = null;).

Also, instead of self, if you're using 5.3+ you should use static since it enables you to inherit and use late-static-binding to determine the class.

If that doesn't help, post more code (the class definitions would help)...

Title: PHP Singleton Acting Funny

Body:
I have the following code:

$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "
";
print_r(self::$extensions);

Each getInstance() method looks like this:

public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}

Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:

stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!


问:
Facebook Audience network upgrade with cocoapods does not upgrade to version 4.23
When i try to update the SDK via cocoapods it updates only up to version 4.20.1.
Does anyone know if there is a different cocoa pods line instead of " pod 'FBAudienceNetwork'"  or else how can i update the SDK version?
Thanks</p>

答:
The solution was very simple. Instead of running in Terminal the

pod install

i should have used

pod update

this solved the problem.


问:
Writing a txt file to mySQL database
I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message

java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1

I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.

```<code>                try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
                FileReader file1 = new FileReader("resources/Test.txt");
                BufferedReader buffer1 = new BufferedReader(file1);
                String read;
                while ((read = buffer1.readLine()) != null) {
                    String[] row = read.split(",");
                    String fName = row[0];
                    String sName = row[1];
                    String DOB = row[2];
                    String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";

                    ps = con.prepareStatement(insert);

                    ps.executeUpdate();
                    ps.close();
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
</code>```

答:
As mentioned in the comments, don't quote the column names.

The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.

```<code>Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
</code>```

Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.

```<code>try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
    ps.setString(0, fName);
    ps.setString(1, sName);
    ps.setString(2, DOB);
    ps.execute();
} catch (SQLException ex) {
    System.out.println("SQLException: " + ex.getMessage());
}
</code>```

Title: Writing a txt file to mySQL database

Body:
I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message

java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1

I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.

                try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
                FileReader file1 = new FileReader("resources/Test.txt");
                BufferedReader buffer1 = new BufferedReader(file1);
                String read;
                while ((read = buffer1.readLine()) != null) {
                    String[] row = read.split(",");
                    String fName = row[0];
                    String sName = row[1];
                    String DOB = row[2];
                    String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";

                    ps = con.prepareStatement(insert);

                    ps.executeUpdate();
                    ps.close();
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }

Body:
As mentioned in the comments, don't quote the column names.

The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.

Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");

Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.

try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
    ps.setString(0, fName);
    ps.setString(1, sName);
    ps.setString(2, DOB);
    ps.execute();
} catch (SQLException ex) {
    System.out.println("SQLException: " + ex.getMessage());
}


问:
Bash - Get time difference from ffmpeg - Audio and Video merge
I am building an an application using ffmpeg. In which I need to subtract start time of two files(there are only two files as input). following is my code.

```<code>#!/bin/bash
mkvarray=()
mkvarray_name=()
for video_name in *.mkv; do
output=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
mkvarray+=($output)
mkvarray_name+=("$video_name")
done

arraylength=${#mkvarray[@]}
for (( i=0; i<${arraylength}; i++ ));
do
  echo ${mkvarray_name[$i-1]} "------>  " ${mkvarray[$i-1]}
done

max_number=0
if [[ ${mkvarray[0]} < ${mkvarray[1]} ]]; then
  echo "first-------------"

  max_number = ${mkvarray[0]} - ${mkvarray[1]}
  echo "first " $max_number
else
   echo "second-------------"
   max_number = ${mkvarray[0]} - ${mkvarray[1]}
   echo "second " $max_number
fi

echo $max_number
</code>```

OUTPUT

$ ./ffmpeg_updated.bash RTda01986c816052106c00f417387a83ff.mkv ------>
  2.040000 cc.mkv ------>   2.040000 RT4bafb05e1b36885c75d7d67a16f5e3b2.mkv ------>   4.086000
  first------------- ./ffmpeg_updated.bash: line 24: max_number: command
  not found first  0 0

from this I understood that, floating point arithmetic is not possible. So Is there any suggestion to proceed from this. I am pretty much new to bash. Or is there any alternative way to get things done in ffmpeg?

答:
UPDATE
a better answer can be found in the following link
Merge Conference Video and Audio call output using hstack ffmpeg

As mentioned in the linked question. There is no way to do floating point arithmetic via bash directly. we have to use bc.
Updated code is given below.

VIDEO MERGER

```<code>    #!/bin/bash
    echo "VIDEO MERGER"
    echo "------------"
    echo "VIDEO MERGER: started"
    mkvarray=()
    mkvarray_name=()
    #ASSIGN VIDEO START TIME TO VARIBALES
    for video_name in *.mkv; do
    start_time=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
    mkvarray+=($start_time)
    mkvarray_name+=("$video_name")
    done
    #PRINT START TIME OF VIDEO FILES (FOR DEBUG)
    #arraylength=${#mkvarray[@]}
    #for (( i=0; i<${arraylength}; i++ ));
    #do
    #  echo $i ${mkvarray_name[$i]} "------>  " ${mkvarray[$i]}
    #done

    #echo "----->" ${mkvarray_name[0]} ${mkvarray[0]}
    #echo "----->" ${mkvarray_name[1]} ${mkvarray[1]}

    #GETTING THE START TIME
    RESULT=$(echo "scale=5; (${mkvarray[0]} - ${mkvarray[1]})" | tr -d $'\r' | bc -l)
    updated_result=0
    #check which file is
    if (( $(echo "$RESULT < 0" |bc -l) )); then
    updated_result=$(echo "$RESULT * -1" |bc -l)
    else
    updated_result=$RESULT
    fi

    #IDENTIFY THE FIRST FILE AND SECOND FILE IN ORDER OF START TIME
    if (( $(echo "(${mkvarray[0]} > ${mkvarray[1]})" | tr -d $'\r' |bc -l) )); then #do
    second_file=${mkvarray_name[0]}
    first_file=${mkvarray_name[1]}
    echo "FIRST FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
    echo "SECOND FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
    else
    second_file=${mkvarray_name[1]}
    first_file=${mkvarray_name[0]}
    echo "FIRST FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
    echo "SECOND FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
    fi
    echo "TIME DIFERENCE :" $updated_result

    ffmpeg -i $first_file -itsoffset $updated_result -i $second_file -filter_complex "[0]pad=iw*2:ih[int]; [int][1]overlay=W/2:0[vid]" -map [vid] -c:v libvpx -crf 23 -quality good -cpu-used 3 -an output_video.webm
    echo "VIDEO MERGER: finished"
</code>```

```<code> AUDIO MERGER
</code>```

```<code>#!/bin/bash
echo "AUDIO MERGER"
echo "------------"
echo "AUDIO MERGER : started"
mkvarray=()
mkvarray_name=()
#ASSIGN VIDEO START TIME TO VARIBALES
for video_name in *.mka; do
start_time=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
mkvarray+=($start_time)
mkvarray_name+=("$video_name")
done
#PRINT START TIME OF VIDEO FILES (FOR DEBUG)
#arraylength=${#mkvarray[@]}
#for (( i=0; i<${arraylength}; i++ ));
#do
#  echo $i ${mkvarray_name[$i]} "------>  " ${mkvarray[$i]}
#done

#echo "----->" ${mkvarray_name[0]} ${mkvarray[0]}
#echo "----->" ${mkvarray_name[1]} ${mkvarray[1]}

#GETTING THE START TIME
RESULT=$(echo "scale=5; (${mkvarray[0]} - ${mkvarray[1]})" | tr -d $'\r' | bc -l)
updated_result=0
#check which file is
if (( $(echo "$RESULT < 0" |bc -l) )); then
updated_result=$(echo "$RESULT * -1 * 1000" |bc -l)
else
updated_result=$(echo "$RESULT * 1000" |bc -l)
fi

#IDENTIFY THE FIRST FILE AND SECOND FILE IN ORDER OF START TIME
if (( $(echo "(${mkvarray[0]} > ${mkvarray[1]})" | tr -d $'\r' |bc -l) )); then #do
second_file=${mkvarray_name[0]}
first_file=${mkvarray_name[1]}
echo "FIRST FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
echo "SECOND FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
else
second_file=${mkvarray_name[1]}
first_file=${mkvarray_name[0]}
echo "FIRST FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
echo "SECOND FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
fi
echo "TIME DIFERENCE :" $updated_result

ffmpeg -i $first_file -i $second_file -filter_complex "[1]adelay="$updated_result"|"$updated_result"[d];[0][d]amix=inputs=2" -strict -2 output_audio.webm
echo "AUDIO MERGER : finished"
</code>```

```<code>MERGE AUDIO & VIDEO
</code>```

```<code>#!/bin/bash
echo "AUDIO/VIDEO OUTPUT MERGER"
echo "-------------------------"
echo "AUDIO/VIDEO OUTPUT MERGER : started merging audio and video"
ffmpeg -i output_video.webm -i output_audio.webm -c:v copy -c:a copy full.webm
echo "AUDIO/VIDEO OUTPUT MERGER : finished merging audio and video"
</code>```

Body:
I am building an an application using ffmpeg. In which I need to subtract start time of two files(there are only two files as input). following is my code.

#!/bin/bash
mkvarray=()
mkvarray_name=()
for video_name in *.mkv; do
output=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
mkvarray+=($output)
mkvarray_name+=("$video_name")
done

arraylength=${#mkvarray[@]}
for (( i=0; i<${arraylength}; i++ ));
do
  echo ${mkvarray_name[$i-1]} "------>  " ${mkvarray[$i-1]}
done

max_number=0
if [[ ${mkvarray[0]} < ${mkvarray[1]} ]]; then
  echo "first-------------"

  max_number = ${mkvarray[0]} - ${mkvarray[1]}
  echo "first " $max_number
else
   echo "second-------------"
   max_number = ${mkvarray[0]} - ${mkvarray[1]}
   echo "second " $max_number
fi

echo $max_number

OUTPUT

$ ./ffmpeg_updated.bash RTda01986c816052106c00f417387a83ff.mkv ------>
  2.040000 cc.mkv ------>   2.040000 RT4bafb05e1b36885c75d7d67a16f5e3b2.mkv ------>   4.086000
  first------------- ./ffmpeg_updated.bash: line 24: max_number: command
  not found first  0 0

from this I understood that, floating point arithmetic is not possible. So Is there any suggestion to proceed from this. I am pretty much new to bash. Or is there any alternative way to get things done in ffmpeg?

Body:
UPDATE
a better answer can be found in the following link
Merge Conference Video and Audio call output using hstack ffmpeg

As mentioned in the linked question. There is no way to do floating point arithmetic via bash directly. we have to use bc.
Updated code is given below.

VIDEO MERGER

    #!/bin/bash
    echo "VIDEO MERGER"
    echo "------------"
    echo "VIDEO MERGER: started"
    mkvarray=()
    mkvarray_name=()
    #ASSIGN VIDEO START TIME TO VARIBALES
    for video_name in *.mkv; do
    start_time=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
    mkvarray+=($start_time)
    mkvarray_name+=("$video_name")
    done
    #PRINT START TIME OF VIDEO FILES (FOR DEBUG)
    #arraylength=${#mkvarray[@]}
    #for (( i=0; i<${arraylength}; i++ ));
    #do
    #  echo $i ${mkvarray_name[$i]} "------>  " ${mkvarray[$i]}
    #done

    #echo "----->" ${mkvarray_name[0]} ${mkvarray[0]}
    #echo "----->" ${mkvarray_name[1]} ${mkvarray[1]}

    #GETTING THE START TIME
    RESULT=$(echo "scale=5; (${mkvarray[0]} - ${mkvarray[1]})" | tr -d $'\r' | bc -l)
    updated_result=0
    #check which file is
    if (( $(echo "$RESULT < 0" |bc -l) )); then
    updated_result=$(echo "$RESULT * -1" |bc -l)
    else
    updated_result=$RESULT
    fi

    #IDENTIFY THE FIRST FILE AND SECOND FILE IN ORDER OF START TIME
    if (( $(echo "(${mkvarray[0]} > ${mkvarray[1]})" | tr -d $'\r' |bc -l) )); then #do
    second_file=${mkvarray_name[0]}
    first_file=${mkvarray_name[1]}
    echo "FIRST FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
    echo "SECOND FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
    else
    second_file=${mkvarray_name[1]}
    first_file=${mkvarray_name[0]}
    echo "FIRST FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
    echo "SECOND FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
    fi
    echo "TIME DIFERENCE :" $updated_result

    ffmpeg -i $first_file -itsoffset $updated_result -i $second_file -filter_complex "[0]pad=iw*2:ih[int]; [int][1]overlay=W/2:0[vid]" -map [vid] -c:v libvpx -crf 23 -quality good -cpu-used 3 -an output_video.webm
    echo "VIDEO MERGER: finished"

 AUDIO MERGER

#!/bin/bash
echo "AUDIO MERGER"
echo "------------"
echo "AUDIO MERGER : started"
mkvarray=()
mkvarray_name=()
#ASSIGN VIDEO START TIME TO VARIBALES
for video_name in *.mka; do
start_time=$(ffprobe -v error -show_entries format=start_time -of default=noprint_wrappers=1:nokey=1 "$video_name")
mkvarray+=($start_time)
mkvarray_name+=("$video_name")
done
#PRINT START TIME OF VIDEO FILES (FOR DEBUG)
#arraylength=${#mkvarray[@]}
#for (( i=0; i<${arraylength}; i++ ));
#do
#  echo $i ${mkvarray_name[$i]} "------>  " ${mkvarray[$i]}
#done

#echo "----->" ${mkvarray_name[0]} ${mkvarray[0]}
#echo "----->" ${mkvarray_name[1]} ${mkvarray[1]}

#GETTING THE START TIME
RESULT=$(echo "scale=5; (${mkvarray[0]} - ${mkvarray[1]})" | tr -d $'\r' | bc -l)
updated_result=0
#check which file is
if (( $(echo "$RESULT < 0" |bc -l) )); then
updated_result=$(echo "$RESULT * -1 * 1000" |bc -l)
else
updated_result=$(echo "$RESULT * 1000" |bc -l)
fi

#IDENTIFY THE FIRST FILE AND SECOND FILE IN ORDER OF START TIME
if (( $(echo "(${mkvarray[0]} > ${mkvarray[1]})" | tr -d $'\r' |bc -l) )); then #do
second_file=${mkvarray_name[0]}
first_file=${mkvarray_name[1]}
echo "FIRST FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
echo "SECOND FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
else
second_file=${mkvarray_name[1]}
first_file=${mkvarray_name[0]}
echo "FIRST FILE : " ${mkvarray_name[0]} ", TIME :" ${mkvarray[0]}
echo "SECOND FILE : " ${mkvarray_name[1]} ", TIME :" ${mkvarray[1]}
fi
echo "TIME DIFERENCE :" $updated_result

ffmpeg -i $first_file -i $second_file -filter_complex "[1]adelay="$updated_result"|"$updated_result"[d];[0][d]amix=inputs=2" -strict -2 output_audio.webm
echo "AUDIO MERGER : finished"

MERGE AUDIO & VIDEO

#!/bin/bash
echo "AUDIO/VIDEO OUTPUT MERGER"
echo "-------------------------"
echo "AUDIO/VIDEO OUTPUT MERGER : started merging audio and video"
ffmpeg -i output_video.webm -i output_audio.webm -c:v copy -c:a copy full.webm
echo "AUDIO/VIDEO OUTPUT MERGER : finished merging audio and video"


问:
Sorting each row and select the top three values from a dataframe
I have a dataframe which looks something like :

```<code>device_id   s2  s41 s47 s14
30          0   0   0   0.003
125         0   0   0   0
32          0   0   0   0
45          0   0   0   0
</code>```

The objective is to get the 3 highest s's from each row and if there is a match then select the maximum index. For example, for the first row, there is a match between s2, s41 and s47 so s47 will be selected along with s41. So the selection from row 1 would be s14, s47 and s41. There are more than 2 million records and more than 250 s's and hence I need an efficient way of doing this. I have tried with iterrows and then sorting each row but it is slow and takes more than an hour for all the data.

The end objective would be to search for the s's ( s14, s47 , s41) in a dictionary where these values are the keys and getting the appropriate values from there.

Can someone please help me in doing this efficiently.
Thanks

Body:
I have a dataframe which looks something like :

device_id   s2  s41 s47 s14
30          0   0   0   0.003
125         0   0   0   0
32          0   0   0   0
45          0   0   0   0

The objective is to get the 3 highest s's from each row and if there is a match then select the maximum index. For example, for the first row, there is a match between s2, s41 and s47 so s47 will be selected along with s41. So the selection from row 1 would be s14, s47 and s41. There are more than 2 million records and more than 250 s's and hence I need an efficient way of doing this. I have tried with iterrows and then sorting each row but it is slow and takes more than an hour for all the data.

The end objective would be to search for the s's ( s14, s47 , s41) in a dictionary where these values are the keys and getting the appropriate values from there.

Can someone please help me in doing this efficiently.
Thanks

Body:
I would use heapq's nlargest:

In [11]: df
Out[11]:
   device_id  s2  s41  s47    s14
0         30   0    0    0  0.003
1        125   0    0    0  0.000
2         32   0    0    0  0.000
3         45   0    0    0  0.000

In [12]: nlargest(3, df.columns[1:], key=lambda x: int(x[1:]))
Out[12]: ['s47', 's41', 's14']

In [13]: df[["device_id"] + nlargest(3, df.columns[1:], key=lambda x: int(x[1:]))]
Out[13]:
   device_id  s47  s41    s14
0         30    0    0  0.003
1        125    0    0  0.000
2         32    0    0  0.000
3         45    0    0  0.000

Note: If device_id is the index it's a little easier:

In [21]: df1
Out[21]:
           s2  s41  s47    s14
device_id
30          0    0    0  0.003
125         0    0    0  0.000
32          0    0    0  0.000
45          0    0    0  0.000

In [22]: df1[nlargest(3, df1.columns, key=lambda x: int(x[1:]))]
Out[22]:
           s47  s41    s14
device_id
30           0    0  0.003
125          0    0  0.000
32           0    0  0.000
45           0    0  0.000


问:
Remove failed database
By accident I have deleted MDF and LDF files from my database directory. Now, each time I start SSMS I have error:

Failed to retrieve data for this request.

Unable to open the physical file "C:\Program Files\Microsoft SQL
  Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\LearnCSharp.mdf". Operating
  system error 2: "2(The system cannot find the file specified.)".
  (Microsoft SQL Server, Error: 5120)

For help, click:
  http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=10.00.2531&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476

How to remove database from system in such situation?

答:
```<code>use master
go
drop database [LearnCSharp]
go
</code>```

Title: Remove failed database


问:
convert array into proper JSON format for android using PHP
I am using Codeigniter to fetch rows. Please go through the below code.

```<code>//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}
</code>```

From the above code, the output is

```<code>{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}
</code>```

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

```<code>[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]
</code>```

答:
I think you can modify your function</p>

```<code>public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return array();
}

//Controller

$all_favourites = $this->select->selectData();

// if(!empty($all_favourites)) {
//    foreach($all_favourites as $favourites)
//        echo json_encode($favourites);
// }
echo json_encode($all_favourites);
</code>```

Body:
I am using Codeigniter to fetch rows. Please go through the below code.

//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

From the above code, the output is

{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]

Body:
I think you can modify your function

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return array();
}

//Controller

$all_favourites = $this->select->selectData();

// if(!empty($all_favourites)) {
//    foreach($all_favourites as $favourites)
//        echo json_encode($favourites);
// }
echo json_encode($all_favourites);


问:
I am new to Python and getting this error while creating new Python 2 notebook. The Error is "Permission denied: Untitled.ipynb".
I am learning python and Installed Anaconda and Trying to generate new python 2 notebook using jupyter notebook. I am using windows OS.</p>

答: check If your "Untitled.ipynb” is open or in use somewhere in system.If yes close it.</p>


答:
Is $_instance in the base class?

If so, then you've got a singleton for the entire hierarchy, not each specific subclass.

Title: PHP Singleton Acting Funny


问:
TypeScript FormGroup include dropdown
I have an role class like as:
roles:

```<code>export class Role{
    id:number;
    roleName:string;
    description:string;

}
</code>```

and assign role:

```<code>import {Role} from './roles';
    export class AssignRole{
        isActive:number;
        userRole:Role= new Role();

    }
</code>```

on ts file, I declare form:

```<code>this.userForm = new FormGroup({
      userName: new FormControl('', Validators.required,),
      firstName: new FormControl('', Validators.required),
      roles: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),
      address: new FormControl('', [ Validators.required,])
    });
</code>```

In html, I want to create the roles dopdownlist

```<code><div class="form-group">
                      <label>Roles</label>
                      <select  class="form-control" id="roles">
                         <option formControlName="roles">

                         </option>

                     </select>
                    </div>
</code>```

and input data to roles field:

```<code>this.route.params.switchMap((params: Params) => this.userService.getAssignRole(+params['id'])).subscribe(
        assignRole => {
          this.userForm.patchValue({
            roles:assignRole.userRole.roleName
          });
        }, error => {
          console.log(error);
        }
      );
</code>```

the error message is displayed: ERROR Error: No value accessor for form control with name: 'roles'

Please advice me.

答:
You need to change your HTML so formControlName is inside the <select> tag.
Then I think you would need a default value, so you don't have a blank field.

Here is an example to select the gender :

In your HTML :

```<code><select class=form-control formControlName="gender" required>
    <option value="F">F</option>
    <option value="M">M</option>
</select>
</code>```

In your app.component.ts, you set the default value :

```<code>this.form= fb.group({
    gender: new FormControl('F'),
    ...
});
</code>```

Title: TypeScript FormGroup include dropdown

Body:
I have an role class like as:
roles:

export class Role{
    id:number;
    roleName:string;
    description:string;

}

and assign role:

import {Role} from './roles';
    export class AssignRole{
        isActive:number;
        userRole:Role= new Role();

    }

on ts file, I declare form:

this.userForm = new FormGroup({
      userName: new FormControl('', Validators.required,),
      firstName: new FormControl('', Validators.required),
      roles: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),
      address: new FormControl('', [ Validators.required,])
    });

In html, I want to create the roles dopdownlist

                      Roles
                      <select  class="form-control" id="roles">
                         <option formControlName="roles">

                         </option>

                     </select>

and input data to roles field:

this.route.params.switchMap((params: Params) => this.userService.getAssignRole(+params['id'])).subscribe(
        assignRole => {
          this.userForm.patchValue({
            roles:assignRole.userRole.roleName
          });
        }, error => {
          console.log(error);
        }
      );

the error message is displayed: ERROR Error: No value accessor for form control with name: 'roles'

Please advice me.

Body:
You need to change your HTML so formControlName is inside the <select> tag.
Then I think you would need a default value, so you don't have a blank field.

Here is an example to select the gender :

In your HTML :

<select class=form-control formControlName="gender" required>
    <option value="F">F</option>
    <option value="M">M</option>
</select>

In your app.component.ts, you set the default value :

this.form= fb.group({
    gender: new FormControl('F'),
    ...
});


问:
How to filtering "character" like Excel in R
・This is the table , name: x

```<code>==================================================================
 # A tibble: 6 x 10
     ID   blood  age  hair_color name height weight distance expiry
    <dbl> <chr> <dbl>    <chr>  <chr>  <dbl>  <dbl>    <dbl>  <dbl>
1     1     P    60     yellow  john    999    128      110    120
2     2     N    52      black   tom    999    180      156    160
3     3     P   100      white   tom    999    190      140    999
4     4     N    84     yellow   tom    112    136      126    122
5     5     P    56      brown   tom     64    230      150    130
6     6     P   105      green   dan    999    142      150    999
===================================================================

.Expected Image:
 ===================================================================
      ID   blood age  hair_color     name height weight distance expiry
    <dbl> <chr> <dbl>     <chr>     <chr>  <dbl>  <dbl>    <dbl>  <dbl>
1     1     P    60       yellow    john    999    128      110    120
2     4     N    84       yellow    tom     112    136      126    122
===================================================================
</code>```

.Backgound:Beginner

Moverover, how to

1.filtering data with "contain" function?
 -like: extract data in column:hair_color ,contain "ye"

2.filtering data with multi conditions?
 -like: in column:hair_color ,contain "ye"
        and
        in column:name ,start with "to"

Simply imaging how to do something exactly like working in Excel,
Thanks in advance.

答:
In interactive mode, you could use subset:

1)

```<code>subset(x, grepl("ye", hair_color, fixed=TRUE))
</code>```

2)

```<code>subset(x, grepl("ye", hair_color, fixed=TRUE) & grepl("^to", name))
</code>```

In the second example the caret ^ means "start with" in regular expressions.

So in short, the simple text filtering functions known from excel can be achieved and much extended with grepl. A short course on regular expressions helps to unleash its real power.

Body:
・This is the table , name: x

==================================================================
 # A tibble: 6 x 10
     ID   blood  age  hair_color name height weight distance expiry
    <dbl> <chr> <dbl>    <chr>  <chr>  <dbl>  <dbl>    <dbl>  <dbl>
1     1     P    60     yellow  john    999    128      110    120
2     2     N    52      black   tom    999    180      156    160
3     3     P   100      white   tom    999    190      140    999
4     4     N    84     yellow   tom    112    136      126    122
5     5     P    56      brown   tom     64    230      150    130
6     6     P   105      green   dan    999    142      150    999
===================================================================

.Expected Image:
 ===================================================================
      ID   blood age  hair_color     name height weight distance expiry
    <dbl> <chr> <dbl>     <chr>     <chr>  <dbl>  <dbl>    <dbl>  <dbl>
1     1     P    60       yellow    john    999    128      110    120
2     4     N    84       yellow    tom     112    136      126    122
===================================================================

.Backgound:Beginner

Moverover, how to

1.filtering data with "contain" function?
 -like: extract data in column:hair_color ,contain "ye"

2.filtering data with multi conditions?
 -like: in column:hair_color ,contain "ye"
        and
        in column:name ,start with "to"

Simply imaging how to do something exactly like working in Excel,
Thanks in advance.

Body:
In interactive mode, you could use subset:

1)

subset(x, grepl("ye", hair_color, fixed=TRUE))

2)

subset(x, grepl("ye", hair_color, fixed=TRUE) & grepl("^to", name))

In the second example the caret ^ means "start with" in regular expressions.

So in short, the simple text filtering functions known from excel can be achieved and much extended with grepl. A short course on regular expressions helps to unleash its real power.


问:
What is the binary data around the plist in a provisioning profile file?
The structure of a .mobileprovision file looks something like this:

```<code><!-- small binary data -->

<?xml version="1.0" encoding="UTF-8"?>
<!-- plist data -->
</plist>

<!-- large binary data -->
</code>```

I have a few questions around this:

What is this binary data?

Is it useful?

How can I extract the plist from a .mobileprovision file without searching for XML boundaries?

Specifically, I will consider this question as answered (and award the +100 bounty alongwith it) when both Q1 and Q3 above are answered.

答:
The .mobileprovision file is a DER encoded ASN.1,

The plist is one of the values stored in this ASN.1 message.

Body:
The structure of a .mobileprovision file looks something like this:

<?xml version="1.0" encoding="UTF-8"?>

</plist>

I have a few questions around this:

What is this binary data?

Is it useful?

How can I extract the plist from a .mobileprovision file without searching for XML boundaries?

Specifically, I will consider this question as answered (and award the +100 bounty alongwith it) when both Q1 and Q3 above are answered.