text:
Q: VBA - Loop through range, copy to second sheet, save as, repeat I have a list in Sheet2 (e.g. A:A). I want to copy each item into a cell in Sheet1 (e.g."A1"), save as a new workbook and continue through the list in sheet2. I need the loop to end once the list has been complete.
Any help would be greatly appreciated.
Thanks in advance.

A: This will get you started. It's not perfect
Option Explicit
Sub createWorkbooks()
    Dim r As Range
    Dim i As Integer
    Dim lastRow As Integer
    Dim workbookName As String
    Dim wb As Workbook
    Dim ws As Worksheet

    Application.DisplayAlerts = False       'Overwrite workbooks without alerts
    lastRow = findLastRow("Sheet2", "A:A")  'Get last row of target sheet
    For i = 1 To lastRow
        On Error Resume Next
        ActiveWorkbook.Sheets("Sheet1").Delete  'Remove possible Sheet 1
        On Error GoTo 0
        '*
        '* Create a worksheet template
        '*
        Set ws = ThisWorkbook.Sheets.Add
        ws.Name = "Sheet1"

        Set r = Range("Sheet2!A" & i)
        ws.Range("A1").Value = r.Value      'Copy source cell value to template
        workbookName = r.Value & ".xlsx"    'Set workbook name
        '*
        '* Create a new workbook
        '*
        Set wb = Workbooks.Add
        '*
        '* Copy out newly created template to it
        '*
        ws.Copy Before:=wb.Sheets(1)
        wb.SaveAs workbookName
        wb.Close False
    Next i
    ActiveWorkbook.Sheets("Sheet1").Delete 'Remove last template
    Application.DisplayAlerts = True
End Sub
'*******************************************************
'* Find last used row in a certain sheet
'*
Function findLastRow(Sheetname As String, ColumnName As String) As Integer
    Dim lastRow As Integer
    Dim r As Range
    Dim ws As Worksheet

    Set ws = Worksheets(Sheetname)
    lastRow = ws.UsedRange.Rows.Count
    '*
    '* Search backwards till we find a cell that is not empty
    '*
    Set r = ws.Range(ColumnName).Rows(lastRow)
    While IsEmpty(r)
        Set r = r.Offset(-1, 0)
    Wend
    lastRow = r.Row
    Set ws = Nothing
    findLastRow = lastRow
End Function


text:
Q: Updating force directed graph with D3 I use a function to update nodes in a force directed graph, but I get the desired effect only in the second call. The function is called with a click event in a button.

To create the chart I use:
node = d3.select('#nodes').selectAll('circle')
    .data(data.nodes.slice(0, 5))
    .join('circle')
    .attr('cx', width / 2)
    .attr('cy', height / 2)
    .attr("fill", 'teal')
    .attr('r', d => 2 * d.score);

let simulation = d3.forceSimulation()
    .nodes(data.nodes.slice(0, 5))
    .force('charge', d3.forceManyBody())
    .force('center', d3.forceCenter(width / 2, height / 2))
    .on("tick", () => {
        node
            .attr("cx", d => d.x)
            .attr("cy", d => d.y);
    })

And the function used to update the chart is:
function update() {
    node = d3.select('#nodes').selectAll('circle')
        .data(data.nodes.slice(0, 10), d => d.id);

    // EXIT
    node.exit().remove();

    // UPDATE
    node
        .attr("fill", 'gray');

    // ENTER
    node.enter().append('circle')
        .attr("fill", 'crimson')
        .attr('cx', width / 2)
        .attr('cy', height / 2)
        .attr('r', d => 2 * d.score);

    simulation
        .nodes(data.nodes.slice(0, 10))
        .alpha(1)
        .restart();

}

d3.select('#update').on('click', update)

You can view a working demo here: https://codepen.io/ggojedap/pen/WNRYdZa
My question is, How can I get the new inserted nodes animated with one single click, not two? and what is causing this "delay" problem? Any advice is highly appreciated. Thanks in advance.
Note: A very similar version using the new .join() approach is working OK but I need to really understand the reason this example requires 2 clicks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Turn off 'cloud-based' based mode for visual studio load test This is sort of a part two of the question here
VisualStudio cloud-based load test socket exception 100% of requests - webtest alone works OK
In short, my loadtest fails all requests with a weird socketexception, but only when it is run as a 'cloud based' test.
So, my load test somehow (dunno how) is no longer a 'team services cloud based' unit test, but a regular one - and I see that it runs fine.

However, when I add a new cloud-based test and then click on the 'location' setting in my old test and pick anything (or not pick, doesn't matter), VS connects to my TeamServices account, the test becomes cloud-based and it is launched in a different looking tab, with 100% request fails.

So, the question is - how do I turn off/toggle the 'cloud-based' mode for an existing loadtest?

A: Open the testsettings file in your solution/project, you should be able to change the Test run location from VSTS to local computer:


text:
Q: cannot load such file -- foreman/cli (LoadError)
I got one error message while running following command.I use Proxy.is this a problem with proxy?please help me.Thanks in advance.

C:\Users\rajitha\java-getting-started>foreman
C:/Heroku/ruby-1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `
require': cannot load such file -- foreman/cli (LoadError)
        from C:/Heroku/ruby-1.9.3/lib/ruby/site_ruby/1.9.1/rubygems/custom_requi
re.rb:36:in `require'
        from C:/Heroku/bin/foreman:8:in `<main>'

A: use heroku local instead. It's the replacement for foreman.


text:
Q: MFC: how to create Skinnied Dialog with transparent PNG as backrownd (and instead of window chrome)? So here is a grate small, readable MFC sample. But its background is a solid image; I wonder how to create a transparent PNG as app backround?

A: There are two basic methods to alter the non-client ("chrome") area of windows.
Layered windows, were introduced in Windows XP - and allow varying levels of window effects. The technique here is to add the WS_EX_LAYERED style to a window - which prevents the WM_PAINT (in MFC CWnd::OnPaint) from operating. Instead, layered windows are painted by the application calling UpdateLayeredWindow, providing a DIBSection filled with pre-multiplied 32bpp data.
Windows Vista introduced the Desktop Window Manager, that composes windows before painting them to enable desktop alpha effects. Using the DWM API to get alpha effects is not as customizable as a PNG, but is still quite attractive.
Both techniques run into problems as child window painting is not alpha aware - layered windows simply don't paint child windows so you need to enumerate and paint all child controls to offscreen surfaces manually. DWM windows do paint child controls - but none of the standard windows controls available to native Apps has been modified to be alpha aware.
Ironically, .NET WinForms apps, on the surface appear to simply wrap the standard windows common controls, but actually all the standard controls have been redeveloped for .NET, and they paint correctly when placed in the 'glass' area of windows.


text:
Q: Select only the rows where specific column has highest value I have 4 matrices with random values for example -
      Matrix 1                    Matrix 2             Matrix 3             Matrix 4
    [,1] [,2] [,3]           [,1] [,2] [,3]        [,1] [,2] [,3]        [,1] [,2] [,3]
[1,] 10   21   36        [1,] 10   13  100     [1,] 12   16   12     [1,] 61   12   20
[2,] 15   21   45        [2,] 12   47  10      [2,] 16   51   10     [2,] 21   15   400
[3,] 46   23   102       [3,] 54   50  42      [3,] 17   73   14     [3,] 13   31   12

I want to select only the rows which has the highest value in the 3rd column [,3]  -
Here I want a final matrix as displayed below -
Final Matrix
    [,1] [,2] [,3]
[1,] 10   13  100
[2,] 21   15  400
[3,] 46   23  102

Some suggestions would be helpful using subset() or other functions in R?

A: We can use max.col after placing the matrixes in a list
lst1 <- list(Matrix1, Matrix2, Matrix3, Matrix4)
i1 <-  max.col(sapply(lst1, `[`, ,3))
do.call(rbind, Map(function(m, i) m[i, ], lst1[i1], 1:3))

-output
#     [,1] [,2] [,3]
#[1,]   10   13  100
#[2,]   21   15  400
#[3,]   46   23  102

Or another option is to convert to a 3D array, and use indexing to extract
ar1 <- array(c(Matrix1, Matrix2, Matrix3, Matrix4), dim = c(3, 3, 4))
i1 <- max.col(ar1[, 3, ])
rind <- seq_len(nrow(Matrix1))
array(ar1[as.matrix(cbind(expand.grid(rind, rind), i1))], dim(Matrix1))
#      [,1] [,2] [,3]
#[1,]   10   13  100
#[2,]   21   15  400
#[3,]   46   23  102

data
Matrix1 <- structure(c(10, 15, 46, 21, 21, 23, 36, 45, 102), .Dim = c(3L,
3L))

Matrix2 <- structure(c(10, 12, 54, 13, 47, 50, 100, 10, 42), .Dim = c(3L,
3L))

Matrix3 <- structure(c(12, 16, 17, 16, 51, 73, 12, 10, 14), .Dim = c(3L,
3L))

Matrix4 <- structure(c(61, 21, 13, 12, 15, 31, 20, 400, 12), .Dim = c(3L,
3L))

A: A solution with dplyr:
library(dplyr)
# the data
Matrix1 <- structure(c(10, 15, 46, 21, 21, 23, 36, 45, 102), .Dim = c(3L,3L))
Matrix2 <- structure(c(10, 12, 54, 13, 47, 50, 100, 10, 42), .Dim = c(3L,3L))
Matrix3 <- structure(c(12, 16, 17, 16, 51, 73, 12, 10, 14), .Dim = c(3L,3L))
Matrix4 <- structure(c(61, 21, 13, 12, 15, 31, 20, 400, 12), .Dim = c(3L,3L))

# matrices to tibble
x <- as.tibble(rbind(Matrix1, Matrix2, Matrix3, Matrix4))

# dplyr manipulation
x1 <- x %>%
  dplyr::mutate(group = as.integer(gl(n(), 3, n()))) %>% # create group
  group_by(group) %>%
  dplyr::mutate(Max = max(V1, V2, V3, na.rm = TRUE)) %>% # get max
  filter(Max == V3) %>% # max = max of column3
  ungroup() %>%
  select(-group, -Max)

#tibble to matrix
x1 <- as.matrix(x1)

     V1 V2  V3
[1,] 46 23 102
[2,] 10 13 100
[3,] 21 15 400

A: You may do this with mapply and which.max.
t(mapply(function(x) x[which.max(x[,3]),,drop=F], list(m1, m2, m3)))
#      [,1] [,2] [,3]
# [1,]   46   23  102
# [2,]   10   13  100
# [3,]   17   73   14

Data:
m1 <- structure(c(10L, 15L, 46L, 21L, 21L, 23L, 36L, 45L, 102L), .Dim = c(3L,
3L))

m2 <- structure(c(10L, 12L, 54L, 13L, 47L, 50L, 100L, 10L, 42L), .Dim = c(3L,
3L))

m3 <- structure(c(12L, 16L, 17L, 16L, 51L, 73L, 12L, 10L, 14L), .Dim = c(3L,
3L))

m4 <- structure(c(61L, 21L, 12L, 15L, 20L, 400L), .Dim = 2:3)


text:
Q: QGIS 3.0.3 takes a lot of time to save selected features I'm editing a large .xml layer with over million points and 2GB of data.
I'm trying to save selected features (about 100 000 points).
After an hour of saving, I have just 77 kb of data saved. With this pace, it'd take weeks to have a full file.
Any idea why it takes so long?


text:
Q: Adding a user from index doesn't work using CakePhp I'm using CakePhp 2.3 and am trying to allow a user to create an account from the home page. I'm new to cakephp and so far I've followed implementation described here: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
Now every time I access the index page (localhost) I am redirected to the users/login page. I've played around with changing the components array in the AppsController, but if I don't include the Auth component then when I call the function add in the USerController, then I get a Call to a member function allow() on a non-object error. I'm not sure how to continue. Right now my AppController class looks like this:
class AppController extends Controller {

public $components = array(
'Session',
'Auth' => array(
    'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
    'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
    'authorize' => array('Controller') // Added this line
)
);

 public function beforeFilter() {
    $this->Auth->allow('index', 'view');
 }
}

All I want to do is be able to add a new user row from the index page. Any ideas or other suggested reading? Thanks!!!

A: Configure your home page / by using the router to use the posts/index action.
Router::connect('/', array('controller' => 'posts', 'action' => 'index'));

Also I guess you're not calling the parent::beforeFilter() in your whatever controller is used for the home page. Allowing actions in the AppController is a bad idea because it just opens security issues. One day you need an index  that should not be public and forget about it OR your have to change all allow() calls.
However, why do you have the login in the posts context? That's wrong. User related actions should belong to the right context: Users controller and model.

A: If you add the key 'authorize', I think you should define the function 'isAuthorized' as described here : http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
How looks like your default index page ?
If it's the defaut "home.ctp", displayed by the PagesController, you have to allow 'display' as an allowed action :
$this->Auth->allow('index', 'view', 'display');

HTH

A: go to app->config-> routes.php and change the action to index as @burzum said
and then go to your UsersController or PostsController whatever your controller is call beforeFilter like this
 <?php
  class UsersController extends AppController {
public function beforeFilter() {
    parent::beforeFilter();

 }
 public function index(){

 }


text:
Q: Joining multible rows in csv file to a single row in shp file using ArcGIS I have two tables (one is actually a shapefile and the other one is a comma separated file).
I really need your help with joining the csv file table (which has many rows for one ID number) with the shapefile attribute table, so when I'll identify something in the map, it'll show me all those rows.
I tried joining, I also tried importing these to geodatabase and I tried to change the field type of the csv attribute table (because it didn't let me to join otherwise). But it didn't work, those other two rows went still missing.
My steps doing this with geodatabase files.
First I made a geodatabase:

Then I imported the shapefile and the tabel:

I dragged both of these files to arcgis and joined the tables

And when I searched the ID I know has 3 rows in the original table, I saw that it hasn't added them here in the joined tables (here is only the first row

Related tables
There are none related tables after I've made the join.

But after I made the join and relate also, I could choose to see them in the table.

And I find a way to see the relates also in the indetify box, I had to open that "tree".

A: Esri provides a good resource: Joining the attributes from a table
What you need to do is peform a one-to-many join versus the one-to-one join. The issue you are running into with your data is that you have multiple rows in your table that share the same ID. When you perform a one-to-one join the first entry will be joined and the other rows with the same ID get "dropped". However when you have a one-to-many join then those similar ID are all joined to the same ID in your shapefile. Below provides more details and illustrations.

Joining the attributes from a table
Typically, you'll join a table of data to a layer based on the value of a field that can be found in both tables. The name of the field does not have to be the same, but the data type has to be the same; you join numbers to numbers, strings to strings, and so on. You can perform a join with either the Join Data dialog box, accessed by right-clicking a layer in ArcMap, or the Add Join tool.
One-to-one and many-to-one relationships
When you join tables in ArcMap, you establish a one-to-one or many-to-one relationship between the layer's attribute table and the table containing the information you want to join. The example below illustrates a one-to-one relationship between each county and that county's population change data. In other words, there's one population change for each county.

One-to-many and many-to-many relationships

When using data where a one-to-many or many-to-many relationship exists, you should use a relate or relationship class to establish the relationship between the datasets. However, it is possible to create a join under these circumstances. When you create a join in such a case, there are differences between how tools and other layer-specific settings work depending on the data source. If you are using geodatabase data to create the join, all matching records are returned. If you are using nondatabase data, like shapefiles or dBASE tables, to create the join, only the first matching record is returned.
This means that if you have created a 1:M or M:M join with geodatabase data and you generate a report, you see multiple records in the report, one for each corresponding match. The multiple matches are also seen when using a join field while symbolizing a joined layer, labeling, identifying features, generating a graph, and using either the Find or Hyperlink tool. If you are using the joined layer as input to a geoprocessing tool or in an export operation, the multiple matching records are used.
View table  and can reference this as an alternative as well How To: Create a one-to-many join in ArcMap

Instructions provided describe how to create a table with a one-to-many mapping to another table.


text:
Q: Read data in separed blocks from a socket server c# I have this code:
        void Start(Socket ServerSocket)
    {

       var socketConnected = ServerSocket.Accept();
        var state = new State()
        {
            socket = socketConnected,
            buffer = new byte[2048]
        };

        ServerSocket.BeginReceive(state.buffer, 0, state.bufferSize, SocketFlags.None, ReadCallBack, state);

    }

    void ReadCallBack(IAsyncResult result)
    {
        var state = (State)result.AsyncState;

       int readData = state.socket.EndReceive(result);

        if(readData > 0)
        {
            //Do Work
        }
        state.socket.BeginReceive(state.buffer, 0, state.bufferSize, SocketFlags.None, ReadCallBack, state);
    }

It works perfectly, receiving data from a client.
The problem is that when the client sends two data asynchronous requests. The
server receives data all together in the same array.
I would like know if there is another way of doing it so that the data is separated.


text:
Q: Angular http subscribe blocked by CORS policy I am sending form data to a api which is running in python flask. The form is in angular 11. When using httpclient the api is not accessible.
this.http.post('http://192.168.0.95:5001/login', formData).subscribe(

  (response) => console.log(response),
  (error) => console.log(error)
)

But when i directly submit the form to that api its working.
<form action ="http://192.168.0.95:5001/login">

I have updated the proxy.conf.json file as below
{
    "/": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}

but its not working. Anyone please help with this

A: By default browser will block cross platform request.
You need to configure access on server.
For more details please check this:
https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api


text:
Q: Have a daemon call another application's rake tasks On a server I have a daemon and a Ruby application. We interact with the application through rake tasks, as it has no other interface.
What I'd like to do is have the daemon do its work and then call the application's rake task. So the daemon code would be:
DaemonKit::Cron.scheduler.every('1h') do
  ...
  #calling Daemon logic here
  ...

  `/bin/bash -l -c 'cd /path/to/application && RAILS_ENV=production bundle exec rake notify:daemon_finished'`
end

As far as I can tell, this should work. But I get an error from the application:
rake aborted!
cannot load such file -- active_record/railtie
/path/to/application/application.rb:7:in `require'
/path/to/application/config/application.rb:7:in `<top (required)>'
/path/to/application/Rakefile:5:in `require'
/path/to/application/Rakefile:5:in `<top (required)>'

Any ideas? Thanks.


text:
Q: In python, how to tweak Black formatter, if possible? I know that Black is an opinionated formatter, but I love everything it does except one major thing. When I have a function with multiple arguments, instead of displaying it like this:
def example_function(arg_1: str, arg_2: bool, arg_3: int = 0, arg_4: int = 1, arg_5: float = 0.0):
    pass

I'd rather display it as follows for readability
def example_function(
    arg_1: str,
    arg_2: bool,
    arg_3: int = 0,
    arg_4: int = 1,
    arg_5: float = 0.0
):

Is this achievable with Black or some other formatter? I have this problem several times and it makes me consider not to use Black, either something else or nothing at all. Any ideas or comments?

A: This is due to the default line length for black being longer than you'd like – 88 characters per line.
To decrease the line length, you can use the --line-length flag as documented here:
https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html
For example:
$ black --line-length 80 example.py

Black explains the --line-length setting in more detail here:
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-length

Line length
You probably noticed the peculiar default line length. Black defaults
to 88 characters per line, which happens to be 10% over 80. This
number was found to produce significantly shorter files than sticking
with 80 (the most popular), or even 79 (used by the standard library).
In general, 90-ish seems like the wise choice.
If you're paid by the line of code you write, you can pass
--line-length with a lower number. Black will try to respect that. However, sometimes it won't be able to without breaking other rules.
In those rare cases, auto-formatted code will exceed your allotted
limit.
You can also increase it, but remember that people with sight
disabilities find it harder to work with line lengths exceeding 100
characters. It also adversely affects side-by-side diff review on
typical screen resolutions. Long lines also make it harder to present
code neatly in documentation or talk slides.

Emphasis on the final paragraph.
I'd recommend just keeping the default settings. The beauty of Black is that it chooses for you, and therefor preempts any arguments about which way is "best".

A: This is now possible by adding a trailing comma to your last argument.
In your example you would write instead:
def example_function(
    arg_1: str,
    arg_2: bool,
    arg_3: int = 0,
    arg_4: int = 1,
    arg_5: float = 0.0, # <-- Notice the trailing comma
):

A: When using the Black playground at https://black.now.sh, I found that your function was reformatted exactly like that when the line length was short enough (in particular, at 78 characters).
It might be nice if there were a special configuration option that controlled the line length specifically for function parameter lines.  BUT to seems to me that Black's configuration-free approach means that there is no way to control this with any more tailored option.


text:
Q: mvn --version says permission denied I have extracted the maven binary files to my home directory i.e /home/pranish then ran the following commands to install maven environment variables:
export M2_HOME=/home/pranish/apache-maven-3.3.3

and
export PATH=/home/pranish/apache-maven-3.3.3/bin:${PATH}

Then when I execute mvn --verison command, it gives me an error:
bash: /home/pranish/apache-maven-3.3.3/bin/mvn: Permission denied

How do I solve it?

A: The error message says
bash: /home/pranish/apache-maven-3.3.3/bin/mvn: Permission denied

That means, you have no access/executable rights for the file.
Correct the access rights of your home folder:
sudo chown -R $USER:$USER /home/$USER
chmod +x /home/$USER/apache-maven-3.3.3/bin/mvn

Explanation

*

*sudo
You are probably not the owner for some files, therefore you need sudo rights to change owner

*chown -R
The command to change the owner recursively. All files in your home folder are your files and only your files

*chmod +x
The command to set the executable rights

*$USER:$USER
Per default in Ubuntu the owner and the group are the same in your home folder and $USER is your username. Try this with echo $USER

*/home/pranish
Your home folder, the same as ~ or /home/$USER


text:
Q: How to specify a type parameter so that a generic base class will use the same model class that is used by the DAL method that it calls? I am trying to create a generic base controller that would provide a single point of maintenance of the basic CRUD for a number of similar data base tables in my MVC EF application. My design:
There is a base model class:
public class ModelBaseClass {}

Each database table has a model class. All model classes inherit ModelBaseClass:
public class ModelSomeDatabaseTable : ModelBaseClass {}

Each database table is associated with a data access (DAL) class. The class includes CRUD methods. The DAL class uses the corresponding model class to pass data to the business layer:
public abstract class DalBaseClass
{
    public abstract List<ModelBaseClass> ToList();
}

There is a generic base controller with two type parameters: The first one is for the DAL class associated with the database table. The second one is for the database table's model class:
 public class ControllerBaseClass<T1Dal, T2Model> : Controller
    where T1Dal : DalBaseClass, new()
    where T2Model : ModelBaseClass
{
    T1Dal _dal = new T1Dal();

    public ControllerBaseClass() { }

    //----------------------------------------------------------------------------------------
    // GET: List all entries in the table
    //----------------------------------------------------------------------------------------
    public ActionResult Index()
    {
        List<T2Model> _List = new List<T2Model>();
        _List = _dal.ToList(); //Compiler error: "Cannot implicitly convert type '…<...ModelBaseClass>' to '…<...T2Model>'"
        return View(_List);
    }
}

I have read what seemed to be relevant in the MSDN, as well as quite a number of blogs and responses to questions related to the use of type parameters. In particular, I read several blogs describing the construction of generic base classes that provide a single point of maintenance for the basic CRUD logic. Yet none of them seems to pass both type parameters, one for the DAL class of a certain table, and the other for the model class of the same table.
My problem is related to the second type parameter, the model class. The controller and the DAL class must use the same model when data is transferred between the two. Of course, the identity of the model type will be revealed only at run time. Still, the compiler needs the assurance that the same types are used by the controller and by the DAL, otherwise it raises a "Cannot implicitly convert type '…<...ModelBaseClass>' to '…<...T2Model>'"
BTW, when I replace the type parameter (T2Model) with the explicit name of the model base class (ModelBaseClass), then the compiler is happy.
In the generic base controller (ControllerBaseClass) below, T1Dal is constrained by the DalBaseClass. The DalBaseClass, in turn, has an abstract method, thus the compiler is happy when the generic base controller calls that method. Not only that, but also the generic base controller is aware of the inherited model's type, ModelBaseClass, as declared in the DalBaseClass. Here is the problem: T1Dal is constrained by the models' base class. Therefore, I naively expected that here, again through inheritance, the compiler will appreciate the same model type. However, the compiler does not use this information in the assignment statement
_List = _dal.ToList();

therefore, it raises the said cast error.
How should I fix my code so that the generic base controller will recognize that the type parameter representing the model is the same type as the one used by the DAL?

A: This is an extremely poor design and very inflexible. The chief problem is that you're assuming each controller will only ever work with one entity type. That's actually not a real-world design and is pretty rare that you'd only need to work with just one thing in every controller. It's like you're trying to create a repository, but it's not quite a repository. First, you should simply design your "DAL" class to be generic. EF actually has a generic DbSet accessor that you can utilize, which will make your work much easier. For example:
public class MyDalClass
{
    protected readonly DbContext context;

    public MyDalClass(DbContext context)
    {
        this.context = context;
    }

    public List<TEntity> GetAll<TEntity>()
    {
        return context.Set<TEntity>().ToList();
    }
}

Then, throw away your generic controller and inject your DAL:
public class MyController : Controller
{
    protected readonly MyDalClass dal;

    public MyController(MyDalClass dal)
    {
        this.dal = dal;
    }

    ...
}

Then, in your actions, you can simply do something like:
var foos = dal.GetAll<Foo>();

To inject into your controller, you'll need to utilize a dependency injection container. There's many choices out there. My personal choice is Ninject, as I find it blends power and ease of use pretty well. For example, with Ninject, you'd set this up like:
kernel.Bind<DbContext>().To<ApplicationDbContext>().InRequestScope();
kernel.Bind<MyDalClass>().ToSelf().InRequestScope();

Obviously, with the scope of Stack Overflow, this is an extremely basic example. You probably utilize interfaces and create a much more robust DAL. If you're interested, I have a series of articles that present more advanced scenarios with a similar approach.


text:
Q: Query results taking too long on 200K database, speed up tips? I have a sql statement where I'm joining about 4 tables, each with 200K rows. The query runs, but keeps freezing. When I do a join on 3 tables instead, it returns the rows (takes about 10secs). Any suggestion why? suggestions to speed up?
Thanks!
Code
SELECT *
FROM equipment, tiremap, workreference, tirework
WHERE equipment.tiremap = tiremap.`TireID` AND
      tiremap.`WorkMap` = workreference.`aMap` AND
      workreference.`bMap` = tirework.workmap
LIMIT 5

p.s
and if it helps any, I'm using sql alchemy to generate this code, the sqlalchemy code for this is
query = session.query(equipment, tiremap, workreference, tirework)
query = query.filter(equipment.c.tiremap == tiremap.c.TireID)
query = query.filter(tiremap.c.WorkMap==workreference.c.aMap)
query = query.filter(workreference.c.bMap == tirework.c.workmap)
query = query.limit(5)
query.all()

A: Make sure you have indexes on:

*

*equipment (tiremap)

*tiremap (TireID)

*tiremap (WorkMap)

*workreference (aMap)

*workreference (bMap)

*tirework (workmap)

Edit: I guess I should provide some context to that for completeness.
The SQL optimizer looks at a statement, parses it and then determines an execution plan for it based on the query, the tables referenced and available indexes. If you do SELECT * FROM tab1 then it'll do a full table scan of tab1 because there's no other way to execute that.
If you do SELECT * FROM person WHERE lastname LIKE 'V%' and you have a million records, it will be slow to interrogate every row but if lastname is indexed it's much more efficient.
With a query like yours one of those tables will be the driving table that regardless of indexes may simply be done as a full table scan. There's nothing wrong with this. One table has to drive the query. If there is a WHERE clause (for something other than join conditions) this may change but otherwise it's generally true.
From that driving table, MySQL will then start appending joins to the execution plan. These joins will require indexes on the other side to make this work efficiently.
So with three tables you may have one table that's not indexed but it doesn't matter because it drives the query. With the fourth table, there may be two unindexed tables and that's now a problem because for each row in one MySQL will have to do a full table scan of the other.
So basically you create an index on every foreign key and join column so MySQL can use what's available to make the best execution plan for the query you give it.
Lastly, most tools will tell you about the database schema. PHPMyAdmin is a popular one for hosted databases. Personally I actually like a desktop app for this kind of thing. Navicat Lite is a decent free tool for this.

A: You are doing a natural join of 4 tables. Also, in your "WHERE" statement, there are no special conditions.
The database engine will do the following thing :
It will first do a recursive product of all the data in each table.
Consider the following rows in tables A, B and C:
A = rowA1
    rowA2
    rowA3;
B = rowB1
    rowB2
    rowB3;
C = rowC1
    rowC2
    rowC3;

Basically, if you do a natural join of those 3 tables, the engine will have in memory:
rowA1 - rowB1 - rowC1
rowA1 - rowB1 - rowC2
rowA1 - rowB1 - rowC3
rowA1 - rowB2 - rowC1
rowA1 - rowB2 - rowC2
rowA1 - rowB2 - rowC3
rowA1 - rowB3 - rowC1
rowA1 - rowB3 - rowC2
rowA1 - rowB3 - rowC3
...
...
...
rowA3 - rowB3 - rowC1
rowA3 - rowB3 - rowC2
rowA3 - rowB3 - rowC3

In total, 27 rows are put in memory. However, we only want 3 rows :
rowA1 - rowB1 - rowC1
rowA2 - rowB2 - rowC2
rowA3 - rowB3 - rowC3

If your database engine doesn't do optimization by itself, a natural join of 3 table is very expensive. For 4 tables, it is unconceivable, even for a limited number of rows.
Now, how can we get something better ?
First, by looking at the code, we know that we only need 5 values. Also, in database optimization, it is said that you should make the SELECT the earliest possible.
Here is some untested code that should help you. You may have to modify it, depending on what DB engine you are using :
SELECT *
FROM (SELECT * FROM equipment LIMIT 5) e, tiremap, workreference, tirework
WHERE e.tiremap = tiremap.TireID AND
      tiremap.WorkMap = workreference.`aMap` AND
      workreference.`bMap` = tirework.workmap

Just by doing this, it should feel like we had only 3 tables, and not 4. Still, this is not really what you want. If one row of "equipment" is not referenced in the other tables, you will get less than 5 rows at the end. However, this an example to show you that we might not really need all the rows from all the tables.
Now, what I think you want could be this :
SELECT * FROM equipment
INNER JOIN tiremap ON equipment.tiremap = tiremap.TireID
INNER JOIN workreference ON tiremap.WorkMap = workreference.aMap
INNER JOIN tirework ON workreference.bMap = tirework.workmap
LIMIT 5

You might have a problem here : if your engine is not that good (mySQL, sorry), it can take a long time.
If you really want to do the optimization yourself :
SELECT * FROM tirework,
   (SELECT * FROM workreference,
       (SELECT * FROM tiremap,
           (SELECT * FROM equipment) e
        WHERE e.tiremap = tiremap.TireID) t
    WHERE t.WorkMap = workreference.aMap) w
WHERE w.bMap = tirework.workmap
LIMIT 5

And voilà ! Even if your engine optimizer is nonexistent, that query shouldn't take too long. Instead of making a big product of everything, your engine will do one product at a time and get the bad rows out before joining it with a new table.
Try it.

A: It could be that the 4th table you are joining to is much larger than the others. It could also be that the column you are joining on doesn't have an index on it.

A: Most SQL database have some variation of "EXPLAIN PLAN" or "EXPLAIN" that you can use to see how it's parsing the query.  Look for full table scans as a place where you need indexes.


text:
Q: how can i find the derivative of $\frac{9e^{6x}}{7x-3}$? $$\frac{9e^{6x}}{7x-3}$$

*

*how do i find the derivative of $9e^{6x}$? I know how to apply the quotient rule after that.

A: It looks like you've already figured it out, but for to elaborate for general cases if you have two functions $f(y)$ and $g(x)$ and you want to take the derivative of their composition, $f(g(x))$ you use the chain rule.
$$\frac{df}{dx}=\frac{df}{dg}\cdot\frac{dg}{dx} $$
in your case $f(y) = 9e^y$ and $g(x)= 6x.$
Giving:
$$\frac{df}{dx}= 9e^{6x}\cdot g'(x)= 9e^{6x}\cdot6$$

A: $\frac{d}{dx}(9e^{6x}) = 9\cdot6e^{6x} = 54e^{6x}$ by the chain rule.


text:
Q: Apple Mach-O Linker Error - Undefined Symbols for architecture arm64 I have an issue while Running my unity project on xcode. I get over 78 Apple Mach-O Linker Errors. I have implemented a bunch of Plugins as well. However I have included all the frameworks that are required for those plugins to run.Now I am not sure why I keep getting these issues. I have attached an image of some of the Mach-o linking errors im getting. Im trying to deploy the build for iPhone 6 running 8.2 and it Xcode 6.2.
http://i.stack.imgur.com/eZoY8.png
Thanks


text:
Q: How to annotate function arguments hidden in *args? I am testing mypy in one of my projects to see if I will like or not. I know only the basics so far. Here is a little problem I am unable to solve.
I need a function with positional-only parameters. In Python 3.8+:
def func(self, arg: int, /, **data):

(This allows to use self=something and arg=something in the data, if you're curious why.)
To make it work also in Python 3.7 I had to write:
def func(*args, **data):
    self, arg = args

And it works fine, but seems to confuse the mypy, it complains about parameter types in calls of this func.
How can I annotatate, that arg[1] is an int?

Update:
I had some partial success with typing.overload.
A single @overload generates this error:
"Single overload definition, multiple required"
and when I write it twice:
"Overloaded function signature 2 will never be matched"
but the calls to that method are now checked OK.


text:
Q: Nesterov accelerated gradient descent in neural networks I have a simple gradient descent algorithm implemented in MATLAB which uses a simple momentum term to help get out of local minima.
        % Update weights with momentum
        dw1 = alpha(n)*dJdW_1 + mtm*dw1; % input->hidden layer
        dw2 = alpha(n)*dJdW_2 + mtm*dw2; % hidden->output layer
        Wt1 = Wt1 - dw1;
        Wt2 = Wt2 - dw2;

I have been looking at implementing the Nesterov accelerated gradient descent method to improve this algorithm and have been following the tutorial here to do so.
        % Update with Nesterov accelerated descent
        dw1_prev = dw1;
        dw2_prev = dw2;
        dw1 = alpha(n)*dJdW_1 - mtm*dw1;
        dw2 = alpha(n)*dJdW_2 - mtm*dw2;
        Wt1 = Wt1 - (1+mtm)*dw1 - mtm*dw1_prev;
        Wt2 = Wt2 - (1+mtm)*dw2 - mtm*dw2_prev;

However, this appears to converge more slowly than the simple momentum method. Could this be down to the data I am testing with or have I made a mistake in the implementation?

A: I think that I have located the bug in my implementation. This method now does indeed converge faster and I believe the method to be correct for any future readers.
    % Update with Nesterov accelerated descent
    dw1_prev = dw1;
    dw2_prev = dw2;
    dw1 = alpha(n)*dJdW_1 + mtm*dw1;
    dw2 = alpha(n)*dJdW_2 + mtm*dw2;
    Wt1 = Wt1 - (1+mtm)*dw1 - mtm*dw1_prev;
    Wt2 = Wt2 - (1+mtm)*dw2 - mtm*dw2_prev;


text:
Q: Tables related by a combination of two fields Please help design my query. I do not know SQL and have little need or time to learn it.
I want to create a report based on data in TableA and TableB. The combination of two fields in TableA is related to the same combination in TableB. Here's the details:
TableA: MarketData -
Fields:
   Marketplace,
   ProdID,
   MktID
TableB: ProductData -
Fields:
   Marketplace,
   ProdID,
   Title
Marketplace + ProdID is the lookup value.
Desired output:
   Marketplace,   ProdID,   MktID,   Title
All help is appreciated.

A: we are here to HELP solve problems. Not to do the entire job.
Why do you not at least try to provide anything to start with?
Nevertheless, I guess what your looking for looks something like this:
SELECT
    a.Marketplace,
    a.ProdID,
    a.MktID,
    b.Title
FROM
    TableA a
        INNER JOIN
    TableB b ON a.Marketplace = b.Marketplace
        AND a.ProdID = b.ProdID

What is done here is an INNER JOIN of two tables based on two join conditions (columns Marketplace and ProdID being equal).
The combinations of those columns should be unique for this to work as you intend it to.


text:
Q: Field is member of a type which is serializable but is of type which is not serializable I'm developing a C# library with .NET Framework 4.7.
I want to convert the class ProductionOrderXmlFile into a XML file:
[Serializable]
public class Level
{
    [XmlElement("Id")]
    public byte Id { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("CodeType")]
    public byte CodeType { get; set; }
    [XmlElement("CodeSourceType")]
    public byte CodeSourceType { get; set; }
    [XmlElement("HelperCodeType")]
    public byte HelperCodeType { get; set; }
    [XmlElement("HelperCodeSourceType")]
    public byte HelperCodeSourceType { get; set; }
    [XmlElement("PkgRatio")]
    public int PkgRatio { get; set; }
}

[Serializable]
public class VarData
{
    [XmlElement("VariableDataId")]
    public string VariableDataId { get; set; }
    [XmlElement("LevelId")]
    public byte LevelId { get; set; }
    [XmlElement("Value")]
    public string Value { get; set; }
}

/// <summary>
/// Class to load a production order from a xml file.
/// </summary>
[Serializable, XmlRoot("root")]
public class ProductionOrderXmlFile
{
    [XmlElement("ProductionOrderName")]
    public string ProductionOrderName { get; set; }
    [XmlElement("NumItems")]
    public int NumItems { get; set; }
    [XmlElement("ProductCode")]
    public string ProductCode { get; set; }
    [XmlElement("Reduction")]
    public float Reduction { get; set; }
    [XmlArray("Levels")]
    [XmlArrayItem("Level")]
    public List<Level> Levels { get; set; }
    [XmlArray("VariableDatas")]
    [XmlArrayItem("VariableData")]
    public List<VarData> VariableData { get; set; }
}

But in fields public List<Level> Levels { get; set; } and public List<VarData> VariableData { get; set; } I get the warning:
Warning   CA2235  Field Levels is a member of type ProductionOrderXmlFile which is serializable but is of type System.Collections.Generic.List which is not serializable
And:
Warning   CA2235  Field VariableData is a member of type ProductionOrderXmlFile which is serializable but is of type System.Collections.Generic.List which is not serializable
What do I need to do to avoid those warnings?

A: Lose the [Serializable]. Just throw it away - all of them. XmlSerializer doesn't care about it, and you don't need it. It isn't helping you, and is causing this false-positive warning.
[Serializable] relates essentially just to BinaryFormatter, which usually isn't a good choice.


text:
Q: Synchronized statements and separate unsynchronized methods On the Java documentation online I found the following example:
public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

They state:

Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.

Does someone understand what they mean?
The source can be found here.

A: The article first introduces synchronized methods - so up to this point, the reader may believe that the unit of granularity of synchronization is a single method.
And indeed, if synchronized blocks/statements didn't exist, the example above could only be accomplished as:
public void addName(String name) {
    doSyncAdd(name);
    nameList.add(name);
}

private synchronized void doSyncAdd(String name) {
    lastName = name;
    nameCount++;
}

So, synchronized statements mean you can keep related code that needs to be synchronized inline.  Rather than having to declare a separate method, which both pollutes the namespace and fragments the flow of the code.  (Well, factoring out methods is good in moderation but it's nicer to have the choice.)

A: It means that your code snippet can be rewritten as
public void addName(String name) {
    setName(name)
    nameList.add(name);
}

private synchronized void setName(String name) {
    lastName = name;
    nameCount++;
}

i.e. as synchronized(this) is the same as a synchronized instance (non-static) method the code in the synchronized block can be moved to a synchronized method and called from the unsynchronized method. The effect will be the same.

A: It's trying to depict the need of Synchronized statements compared to Synchronized methods.
If you want to have synchronized updation of lastName and nameCount but not the nameList.add() then  Synchronized statements is better option. Otherwise you would end up creating one synchronized method to update lastName and nameCount and another unsynchronized method to add the name in the list.
Hope it clarifies.


text:
Q: Eclipse Juno with PyDev deletes my django files I was trying to set up the Eclipse on a new computer, and thought I might as well try Juno instead of Indigo as I was using before.
However, attempting to import my PyDev/Django files was troublesome, and I ended up creating a new Django project and copying my source files in.
However, when I hit Refresh, Eclipse deletes a bunch of files including urls.py!
I've given up for now - back to Notepad++ - but does anyone have any ideas as to what might be causing this?

A: I must say that'd be the first time I heard that PyDev was deleting .py files... (it does have an option to remove orphaned .pyc files which you can disable on window > preferences > pydev > builders > how to handle .pyc/$py.class deletion).
Are you sure that it's really deleting those files in the filesystem? Can you reproduce that? (if so, please provide the steps to do so, because I've tried many things here and haven't been able to duplicate that behavior). It'd be nice if you check if it really removes the files in the filesystem (i.e.: it's possible that for some reason it's only filtering those in the PyDev package explorer?)

A: I just lost 3 hours of work using pydev and eclipse, without using django. So this is not django specific.


text:
Q: WPF How to programmatically highlight (not select) items in ComboBox dropdown I have a dropdownlist combobox that uses an ItemTemplate to display information. When the dropdown of the combo is open, I want the user to be able to type things that I will search the data for. Then I'd like to highlight the item (and potentially scroll it into view), but NOT select it (selection in this case is expensive and should only occur when the user presses Enter once he's found the right entry).
Essentially this is how a vanilla combobox behaves and I want to do this for my templated one that searches differently.
I've have an AttachedProperty that does the searching correctly, but I can't figure how to set the highlighted item (IsHighlighted is read-only).
This is not a cosmetic issue only, since Enter should select the highlighted item.
Any ideas?

A: If you can add a dependency property to the object in the list you are displaying that holds a bool value for the "ShowHighlighted" state, you could then add a trigger to your ItemTemplate that changes the Background Brush based upon the value of ShowHighlighted.


text:
Q: Inlining functions from object files I want to inline some functions of which I don't have the code. They are present in an object file. Is there a way to do it with gcc?
In other words, I want to perform inlining of those functions while linking my own code files with the object file that contain those functions.

A: Starting with version 4.5, GCC supports the -flto switch which enables Link Time Optimization (LTO).  LTO can inline functions from separate object files.
There's a catch though.  Because of the way that -flto works, it'll only be of use for object files that were compiled using that switch.  As I understand it, GCC implements LTO by placing a intermediate form of the source code into the object file - if that intermediate code isn't in the object file, the code in that object file won't be 'inlined'.
See Can the linker inline functions? for some additional details.

A: What you want to do is just the contrary of inlining. Inlining means that you have the source and you want the compiler to generate code as if that source was defined in place of the caller.
What with some effort perhaps could be done would be to extract the object code and place it inside the newly generated object code for your functions. But this makes not much sense: the only advantage of inlining is that the optimizer can work across the boundaries of functions. E.g to avoid spill of registers, do constant propagation or eliminate dead code. All this would be nearly impossible when you only have the object.


text:
Q: D3.js. Grouping data in bar chart using d3.nest() I am just learning d3.js and my javascript level is basic.
Thanks for the help, much appreciated.
Total number of clicks pr. Campaign.
I have a csv file with colums: "Campaign" and "Clicked".
"Clicked" column consist of values: Clicked / No Click.
I want to display total Clicked per Campaign. I don't care about No Click.
I have made a function to count clicked and store the count in each data member. I use d.count to set y domain.
The y axis and x axis are displayed correct.
But the values in the bars does not show.
I assume these two lines of code are incorrect:
.attr("y", f
unction(d) { return y(d.key); })
.attr("height"
, function(d) { return height - y(d.key); });

In the console I get this error:
d3.v4.min

.js:2 Error:  attribute height: Expected length, "NaN".
  d3.v4.min.j
s:2 Error:  attribute height: Expected length, "NaN"

As I have two values for column Clicked: "Clicked" and "No Click", I assume I have to exclude value "No Click" in my d3.nest() function?
How do I display the values of Clicked per Campaign? What am I missing?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>barChart</title>
</head>
<style> /* set the CSS */

.bar { fill: steelblue; }

</style>
<body>

<!-- load the d3.js library -->
<script src="d3.v4.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<!--<script src="d3.min.js"></script>-->

<script>

// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleBand()
          .range([0, width])
          .padding(0.1);
var y = d3.scaleLinear()
          .range([height, 0]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");

// get the data
    d3.csv("EmailMarketingCampaign_Data.csv")
    .row(function(d){ return {Campaign: (d.Campaign), Clicked: (d.Clicked)}; })
    .get(function(error,data){
    console.log(data[0]);

 // format all data from strings
  data.forEach(function(d) {
    d.data = +d.data;
  });

// Array [ Object, Object ] Key: Clicked, Key: No Clicked
     var nested_data = d3.nest()
     .key(function(d) { return d.Clicked; })
    .rollup(function(values) {
     return values.length;
     })
     .entries(data);
     console.log(nested_data);

// count all clicked to set range for y axis

      var countObj = {};

        // count Clicked
        data.forEach(function(d) {
        var Clicked = d.Clicked;
        if(countObj[Clicked] === undefined) {
        countObj[Clicked] = 0;
        } else {
        countObj[Clicked] = countObj[Clicked] + 1;
        }
        });
        // now store the count in each data member
        data.forEach(function(d) {
        var Clicked = d.Clicked;
        d.count = countObj[Clicked];
        });
        console.log(countObj);

  // Scale the range of the data in the domains
  x.domain(data.map(function(d) { return d.Campaign; }));
  y.domain([0, d3.max(data, function(d) { return d.count; })]);

  // append the rectangles for the bar chart
  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")

      .attr("class", "bar")
      .attr("x", function(d) { return x(d.Campaign); })
      .attr("width", x.bandwidth())

      .attr("y", function(d) { return y(d.key); })
      .attr("height", function(d) { return height - y(d.key); });

  // add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // add the y Axis
  svg.append("g")
      .call(d3.axisLeft(y));

});

</script>
</body>

</html>

EmailMarketingCampaign_Data.csv
Ca

mpaign,Click_Date,Start,End,Clicked,clickedFlag,Customer
  ID,weekDay,Age,Country,Demographic,Gender JAN
  SALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,10,Sun,30,UK,Adult,Male
  JAN
  SALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,11,Mon,26,UK,Adult,Female
  JAN
  SALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,12,Tue,59,UK,Adult,Male
  JAN
  SALES,02/01/2013,30/12/2012,29/01/2013,Clicked,1,13,Wed,3,UK,Child,Male
  JAN
  SALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,14,Thu,59,Germany,Adult,Female
  JAN SALES,04/01/2013,30/12/2012,29/01/2013,No
  Click,0,15,Fri,39,UK,Adult,Male JAN
  SALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,16,Sat,19,UK,Adult,Male
  JAN SALES,07/01/2013,30/12/2012,29/01/2013,No
  Click,0,18,Mon,25,UK,Adult,Male JAN
  SALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,19,Tue,6,UK,Child,Male
  JAN
  SALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,20,Wed,55,Germany,Adult,Female
  JAN
  SALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,21,Thu,19,UK,Adult,Male
  JAN SALES,11/01/2013,30/12/2012,29/01/2013,No
  Click,0,22,Fri,32,UK,Adult,Male JAN
  SALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,23,Sat,18,UK,Adult,Female
  JAN
  SALES,14/01/2013,30/12/2012,29/01/2013,Clicked,1,25,Mon,7,UK,Child,Male
  JAN
  SALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,32,Sun,59,France,Adult,Female
  JAN
  SALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,33,Mon,28,France,Adult,Male
  JAN
  SALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,34,Tue,31,UK,Adult,Male
  JAN SALES,02/01/2013,30/12/2012,29/01/2013,No
  Click,0,35,Wed,3,France,Child,Female JAN
  SALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,36,Thu,38,France,Adult,Male
  JAN
  SALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,37,Fri,50,France,Adult,Male
  JAN
  SALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,38,Sat,57,France,Adult,Female
  JAN
  SALES,06/01/2013,30/12/2012,29/01/2013,Clicked,1,39,Sun,38,France,Adult,Male
  JAN
  SALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,40,Mon,31,UK,Adult,Male
  JAN SALES,08/01/2013,30/12/2012,29/01/2013,No
  Click,0,41,Tue,33,France,Adult,Female JAN
  SALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,42,Wed,34,France,Adult,Male
  JAN
  SALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,43,Thu,59,France,Adult,Male
  JAN SALES,11/01/2013,30/12/2012,29/01/2013,No
  Click,0,44,Fri,13,France,Teen,Female JAN
  SALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,45,Sat,2,France,Child,Male
  JAN
  SALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,46,Sun,39,UK,Adult,Male
  JAN
  SALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,54,Sun,18,France,Adult,Male
  JAN
  SALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,55,Tue,13,France,Teen,Male
  JAN
  SALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,56,Fri,50,France,Adult,Female
  JAN SALES,11/01/2013,30/12/2012,29/01/2013,No
  Click,0,57,Fri,19,France,Adult,Male JAN
  SALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,58,Thu,22,USA,Adult,Male
  JAN
  SALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,59,Fri,11,USA,Child,Female
  JAN SALES,05/01/2013,30/12/2012,29/01/2013,No
  Click,0,60,Sat,56,USA,Adult,Male JAN
  SALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,61,Fri,7,USA,Child,Male
  JAN
  SALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,62,Mon,9,USA,Child,Female
  JAN
  SALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,63,Tue,43,France,Adult,Male
  JAN
  SALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,64,Wed,2,France,Child,Male
  JAN
  SALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,66,Fri,32,USA,Adult,Male
  JAN
  SALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,67,Sat,4,USA,Child,Male
  JAN
  SALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,68,Sun,47,USA,Adult,Female
  JAN SALES,14/01/2013,30/12/2012,29/01/2013,No
  Click,0,69,Mon,49,USA,Adult,Male Unknown,01/02/2013,,,No
  Click,0,2,Fri,33,France,Adult,Female
  Unknown,01/03/2013,,,Clicked,1,3,Fri,17,Germany,Teen,Male
  Unknown,06/03/2013,,,Clicked,1,17,Wed,1,UK,Child,Female
  Unknown,13/02/2013,,,Clicked,1,24,Wed,5,UK,Child,Male
  Unknown,14/03/2013,,,Clicked,1,47,Thu,22,France,Adult,Female
  Unknown,10/04/2013,,,Clicked,1,65,Wed,11,USA,Child,Female
  XMAS,28/12/2012,23/12/2012,29/12/2012,Clicked,1,1,Fri,24,UK,Adult,Male
  XMAS,24/12/2012,23/12/2012,29/12/2012,Clicked,1,4,Mon,18,UK,Adult,Male
  XMAS,25/12/2012,23/12/2012,29/12/2012,Clicked,1,5,Tue,19,UK,Adult,Female
  XMAS,26/12/2012,23/12/2012,29/12/2012,No
  Click,0,6,Wed,58,UK,Adult,Male
  XMAS,27/12/2012,23/12/2012,29/12/2012,Clicked,1,7,Thu,16,Germany,Teen,Male
  XMAS,28/12/2012,23/12/2012,29/12/2012,Clicked,1,8,Fri,26,UK,Adult,Female
  XMAS,29/12/2012,23/12/2012,29/12/2012,No
  Click,0,9,Sat,37,UK,Adult,Male
  XMAS,24/12/2012,23/12/2012,29/12/2012,Clicked,1,26,Mon,19,Germany,Adult,Female
  XMAS,25/12/2012,23/12/2012,29/12/2012,Clicked,1,27,Tue,43,UK,Adult,Male
  XMAS,26/12/2012,23/12/2012,29/12/2012,No
  Click,0,28,Wed,20,UK,Adult,Male
  XMAS,27/12/2012,23/12/2012,29/12/2012,Clicked,1,29,Thu,19,France,Adult,Female
  XMAS,28/12/2012,23/12/2012,29/12/2012,Clicked,1,30,Fri,58,France,Adult,Male
  XMAS,29/12/2012,23/12/2012,29/12/2012,No
  Click,0,31,Sat,7,France,Child,Male
  XMAS,24/12/2012,23/12/2012,29/12/2012,No
  Click,0,48,Mon,3,France,Child,Male
  XMAS,25/12/2012,23/12/2012,29/12/2012,Clicked,1,49,Tue,25,France,Adult,Male
  XMAS,26/12/2012,23/12/2012,29/12/2012,Clicked,1,50,Wed,18,France,Adult,Female
  XMAS,27/12/2012,23/12/2012,29/12/2012,No
  Click,0,51,Thu,5,France,Child,Male
  XMAS,28/12/2012,23/12/2012,29/12/2012,Clicked,1,52,Fri,1,UK,Child,Male
  XMAS,29/12/2012,23/12/2012,29/12/2012,Clicked,1,53,Sat,0,France,Child,Female

screenshot

A: You need to use two level grouping in your nested_data and then use just the "Clicked" group for the scales calculations and the data binding.

var dataString = "Campaign,Click_Date,Start,End,Clicked,clickedFlag,Customer ID,weekDay,Age,Country,Demographic,Gender \nEXTORTION,30/12/2012,30/12/2012,29/01/2013,Clicked,1,10,Sun,30,UK,Adult,Male \nSALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,11,Mon,26,UK,Adult,Female \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,12,Tue,59,UK,Adult,Male \nSALES,02/01/2013,30/12/2012,29/01/2013,Clicked,1,13,Wed,3,UK,Child,Male \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,14,Thu,59,Germany,Adult,Female \nSALES,04/01/2013,30/12/2012,29/01/2013,No Click,0,15,Fri,39,UK,Adult,Male \nSALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,16,Sat,19,UK,Adult,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,No Click,0,18,Mon,25,UK,Adult,Male \nSALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,19,Tue,6,UK,Child,Male \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,20,Wed,55,Germany,Adult,Female \nSALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,21,Thu,19,UK,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,22,Fri,32,UK,Adult,Male \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,23,Sat,18,UK,Adult,Female \nSALES,14/01/2013,30/12/2012,29/01/2013,Clicked,1,25,Mon,7,UK,Child,Male \nSALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,32,Sun,59,France,Adult,Female \nSALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,33,Mon,28,France,Adult,Male \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,34,Tue,31,UK,Adult,Male \nSALES,02/01/2013,30/12/2012,29/01/2013,No Click,0,35,Wed,3,France,Child,Female \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,36,Thu,38,France,Adult,Male \nSALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,37,Fri,50,France,Adult,Male \nSALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,38,Sat,57,France,Adult,Female \nSALES,06/01/2013,30/12/2012,29/01/2013,Clicked,1,39,Sun,38,France,Adult,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,40,Mon,31,UK,Adult,Male \nSALES,08/01/2013,30/12/2012,29/01/2013,No Click,0,41,Tue,33,France,Adult,Female \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,42,Wed,34,France,Adult,Male \nSALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,43,Thu,59,France,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,44,Fri,13,France,Teen,Female \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,45,Sat,2,France,Child,Male \nSALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,46,Sun,39,UK,Adult,Male \nSALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,54,Sun,18,France,Adult,Male \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,55,Tue,13,France,Teen,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,56,Fri,50,France,Adult,Female \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,57,Fri,19,France,Adult,Male \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,58,Thu,22,USA,Adult,Male \nSALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,59,Fri,11,USA,Child,Female \nSALES,05/01/2013,30/12/2012,29/01/2013,No Click,0,60,Sat,56,USA,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,61,Fri,7,USA,Child,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,62,Mon,9,USA,Child,Female \nSALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,63,Tue,43,France,Adult,Male \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,64,Wed,2,France,Child,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,66,Fri,32,USA,Adult,Male \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,67,Sat,4,USA,Child,Male \nSALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,68,Sun,47,USA,Adult,Female \nSALES,14/01/2013,30/12/2012,29/01/2013,No Click,0,69,Mon,49,USA,Adult,Male"
// set the dimensions and margins of the graph
var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 300 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleBand()
  .range([0, width])
  .padding(0.1);
var y = d3.scaleLinear()
  .range([height, 0]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");

// get the data
var data = d3.csvParse(dataString);

//console.log(data[0]);

// format all data from strings
data.forEach(function(d) {
  d.data = +d.data;
});

// Array [ Object, Object ] Key: Clicked, Key: No Clicked
var nested_data = d3.nest()
  .key(function(d) {
    return d.Clicked;
  })
  .key(function(d) {
    return d.Campaign
  })
  .rollup(function(values) {
    return values.length;
  })
  .entries(data);

var clicked_data = nested_data.find(d => d.key == "Clicked").values

// Scale the range of the data in the domains
x.domain(clicked_data.map(function(d) {
  return d.key;
}));
y.domain([0, d3.max(clicked_data, function(d) {
  return d.value;
})]);

// append the rectangles for the bar chart
svg.selectAll(".bar")
  .data(clicked_data)
  .enter().append("rect")

  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.key);
  })
  .attr("width", x.bandwidth())

  .attr("y", function(d) {
    return y(d.value);
  })
  .attr("height", function(d) {
    return height - y(d.value);
  });

// add the x Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// add the y Axis
svg.append("g")
  .call(d3.axisLeft(y));
<script src="https://d3js.org/d3.v4.min.js"></script>

A: I can see I had a lot of missing links.
I have now modified my code according to your suggestions.
It works. Thank you very much, I would not have been able to solve this myself.
I am trying to use the same nested_data to display the clicked_data in a line (d3.line generator) with x-axis as "Click_Date" AND y-axis "Clicked" values,
categorized by the 3 campaigns: Jan, Xmas and Undefined.
So I am using d3.line() and path.
I get this error in the console.log: Error:  attribute d: Expected number, "MNaN,0Z".
And when I "console.log", I can see that clicked_data is being read like this: [Object]0: Objectlength: 1__proto__: Array(0)concat: function concat()constructor: function Array()
Here is the code. I assume I have to work on this bit here:

svg.append("path")
            .data([clicked_data])
            .attr("class", "line")
            .attr("d", valueline);

// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");

// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

// define the line
var valueline = d3.line()
    .x(function(d) { return x(d.key); })
    .y(function(d) { return y(d.value); });
console.log(valueline);

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");

// Get the data
d3.csv("EmailMarketingCampaign_Data.csv", function(error, data) {
  if (error) throw error;

/*  function convert(d) {
  return {
    date: new Date(d.Click_Date),
    value: +d.value         // convert string to number
  };
} */

  // format the data
  data.forEach(function(d) {
      d.Click_Date = parseTime(d.Click_Date);
      d.value = +d.value;
  });

    /* Two level grouping in nested_data: Clicked and Campaign */

var nested_data = d3.nest()
  .key(function(d) {
    return d.Clicked;
  })
  .key(function(d) {
    return d.Click_Date
  })
  .rollup(function(values) {
    return values.length;
  })
  .entries(data);

/* Get values from key "Clicked" and put in clicked_date */

var clicked_data = nested_data.find(d => d.key == "Clicked").values

console.log(clicked_data);

  // Scale the range of the data
  x.domain(d3.extent(clicked_data, function(d) { return d.key; }));
  y.domain([0, d3.max(clicked_data, function(d) { return d.value; })]);

  // Add the valueline path.
  svg.append("path")
      .data([clicked_data])
      .attr("class", "line")
      .attr("d", valueline);

  // Add the X Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // Add the Y Axis
  svg.append("g")
      .call(d3.axisLeft(y));

});

var dataString = "Campaign,Click_Date,Start,End,Clicked,clickedFlag,Customer ID,weekDay,Age,Country,Demographic,Gender \nEXTORTION,30/12/2012,30/12/2012,29/01/2013,Clicked,1,10,Sun,30,UK,Adult,Male \nSALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,11,Mon,26,UK,Adult,Female \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,12,Tue,59,UK,Adult,Male \nSALES,02/01/2013,30/12/2012,29/01/2013,Clicked,1,13,Wed,3,UK,Child,Male \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,14,Thu,59,Germany,Adult,Female \nSALES,04/01/2013,30/12/2012,29/01/2013,No Click,0,15,Fri,39,UK,Adult,Male \nSALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,16,Sat,19,UK,Adult,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,No Click,0,18,Mon,25,UK,Adult,Male \nSALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,19,Tue,6,UK,Child,Male \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,20,Wed,55,Germany,Adult,Female \nSALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,21,Thu,19,UK,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,22,Fri,32,UK,Adult,Male \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,23,Sat,18,UK,Adult,Female \nSALES,14/01/2013,30/12/2012,29/01/2013,Clicked,1,25,Mon,7,UK,Child,Male \nSALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,32,Sun,59,France,Adult,Female \nSALES,31/12/2012,30/12/2012,29/01/2013,Clicked,1,33,Mon,28,France,Adult,Male \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,34,Tue,31,UK,Adult,Male \nSALES,02/01/2013,30/12/2012,29/01/2013,No Click,0,35,Wed,3,France,Child,Female \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,36,Thu,38,France,Adult,Male \nSALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,37,Fri,50,France,Adult,Male \nSALES,05/01/2013,30/12/2012,29/01/2013,Clicked,1,38,Sat,57,France,Adult,Female \nSALES,06/01/2013,30/12/2012,29/01/2013,Clicked,1,39,Sun,38,France,Adult,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,40,Mon,31,UK,Adult,Male \nSALES,08/01/2013,30/12/2012,29/01/2013,No Click,0,41,Tue,33,France,Adult,Female \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,42,Wed,34,France,Adult,Male \nSALES,10/01/2013,30/12/2012,29/01/2013,Clicked,1,43,Thu,59,France,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,44,Fri,13,France,Teen,Female \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,45,Sat,2,France,Child,Male \nSALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,46,Sun,39,UK,Adult,Male \nSALES,30/12/2012,30/12/2012,29/01/2013,Clicked,1,54,Sun,18,France,Adult,Male \nSALES,01/01/2013,30/12/2012,29/01/2013,Clicked,1,55,Tue,13,France,Teen,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,56,Fri,50,France,Adult,Female \nSALES,11/01/2013,30/12/2012,29/01/2013,No Click,0,57,Fri,19,France,Adult,Male \nSALES,03/01/2013,30/12/2012,29/01/2013,Clicked,1,58,Thu,22,USA,Adult,Male \nSALES,04/01/2013,30/12/2012,29/01/2013,Clicked,1,59,Fri,11,USA,Child,Female \nSALES,05/01/2013,30/12/2012,29/01/2013,No Click,0,60,Sat,56,USA,Adult,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,61,Fri,7,USA,Child,Male \nSALES,07/01/2013,30/12/2012,29/01/2013,Clicked,1,62,Mon,9,USA,Child,Female \nSALES,08/01/2013,30/12/2012,29/01/2013,Clicked,1,63,Tue,43,France,Adult,Male \nSALES,09/01/2013,30/12/2012,29/01/2013,Clicked,1,64,Wed,2,France,Child,Male \nSALES,11/01/2013,30/12/2012,29/01/2013,Clicked,1,66,Fri,32,USA,Adult,Male \nSALES,12/01/2013,30/12/2012,29/01/2013,Clicked,1,67,Sat,4,USA,Child,Male \nSALES,13/01/2013,30/12/2012,29/01/2013,Clicked,1,68,Sun,47,USA,Adult,Female \nSALES,14/01/2013,30/12/2012,29/01/2013,No Click,0,69,Mon,49,USA,Adult,Male"
// set the dimensions and margins of the graph
var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 300 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleBand()
  .range([0, width])
  .padding(0.1);
var y = d3.scaleLinear()
  .range([height, 0]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");

// get the data
var data = d3.csvParse(dataString);

//console.log(data[0]);

// format all data from strings
data.forEach(function(d) {
  d.data = +d.data;
});

// Array [ Object, Object ] Key: Clicked, Key: No Clicked
var nested_data = d3.nest()
  .key(function(d) {
    return d.Clicked;
  })
  .key(function(d) {
    return d.Campaign
  })
  .rollup(function(values) {
    return values.length;
  })
  .entries(data);

var clicked_data = nested_data.find(d => d.key == "Clicked").values

// Scale the range of the data in the domains
x.domain(clicked_data.map(function(d) {
  return d.key;
}));
y.domain([0, d3.max(clicked_data, function(d) {
  return d.value;
})]);

// append the rectangles for the bar chart
svg.selectAll(".bar")
  .data(clicked_data)
  .enter().append("rect")

  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.key);
  })
  .attr("width", x.bandwidth())

  .attr("y", function(d) {
    return y(d.value);
  })
  .attr("height", function(d) {
    return height - y(d.value);
  });

// add the x Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// add the y Axis
svg.append("g")
  .call(d3.axisLeft(y));
<script src="https://d3js.org/d3.v4.min.js"></script>


text:
Q: determinating the signature of a bilinear form As as part of my course in Lie groups,
I need some help to determine the signature of the form $B(x,y) = $$ \sum_{i=1}^{n}\ x_iy_{n+1-i}$
More than anything, I would like to understand how to determine a signature of such forms, rather than the plain answer.
thanks in advance!

A: The associated quadratic form has a slightly different nature depending on the parity of $n$. For $n$ odd, it is $x_1x_n+x_2x_{n-1}+\ldots+x_{{n+1\over 2}}^2$, while for $n$ even there is no pure square term.
The summands $x_ix_j$ with $i\not=j$ are "hyperbolic pairs", and have signatures $(1,-1)$. The pure square term, for $n$ odd, has signature $(1,0)$. Add them up.
(There are many supporting exercises one could do here... in the direction of "geometric algebra", and Sylvester's Inertia Theorem, but I don't know your context.)


text:
Q: HierarchyID on Recursive Data I have a table in my database which has two columns:
HID: a hierarchyid
Name: a string
In my application I have a Node class that just has those two properties.  I import the data into Node instantations and save them all with:
Dim Nodes As New List(Of Node)

I know that works because I've reviewed the data.
I have a wpf window that only has a Treeview on it.  In my code behind I set the context of my window:
DataContext = Nodes

and now I want to populate the Treeview with this data.  That is where I come up short.  I have:
<Window.Resources>
    <HierarchicalDataTemplate
        x:Key="MyTemplate"
        ItemsSource="{Binding}">
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>
</Window.Resources>
<TreeView
    ItemsSource ="{Binding Path=Name}"
    ItemTemplate="{Binding Path=MyTemplate}">
</TreeView>

which does not work.  Where am I going wrong?
EDIT1: I changed ItemsSource in the HierarchicalDataTemplate to:
ItemsSource="{Binding Path=HID}"

and set the ItemTemplate of the Treeview itself to:
ItemsSource ="{Binding}"

which seems intuitively right but creates errors saying HID is not a property of my Node class.  Huh?
Edit2: Here is some sample data:
/ John
/1/ Jim
/2/ Mary
/1/1/ Sam
/1/1/1/ Nancy
/2/1/ Sharon
/2/1/1/ Joe
/2/1/1/1/ Henry
/2/1/1/1/ Ellen
/2/1/1/1/1/ Bart

================================
Edit 2
I have rewritten my processing of the data from the database so that the items in the tree have child items in the format necessary for the Treeview control.  I have also changed my XAML to the following:
<Window.Resources>
    <HierarchicalDataTemplate
        x:Key="ChildTemplate">
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate
        x:Key="ParentTemplate"
        ItemsSource="{Binding Path=ChildNodes}"
        ItemTemplate="{StaticResource ChildTemplate}">
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>
</Window.Resources>
<TreeView
    ItemsSource="{Binding}"
    ItemTemplate="{StaticResource ParentTemplate}">
</TreeView>.

In my treeview I see the rootnode and only the first level below that.  There are several levels below the first level that are not presented.  What am I doing wrong?
======================
Edit 3:
I only have one class:
PersonID: Long
ParentID: Long
PersonName: String
Children: List (of Person)
I have traced the creation of all the items by watching them being created from my post processing of the data out of my database.  The various instances of the classes are being populated correctly.
Using the data I originally posted, for example, John is one instance and he has two "children", Jim and Mary
=================================
Edit 4:
Forget the data from my database and all the code that I use to process the data.  I stripped all that away and replaced it with the following procedure in which I just manually define 3 nodes:
Private Sub Window1_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim RootNode As New Node With {.ID = 1, .ParentID = 0, .Name = "Root"}
    Dim node2 As New Node With {.ID = 2, .ParentID = 1, .Name = "son1 of Root"}
    Dim node3 As New Node With {.ID = 3, .ParentID = 2, .Name = "son1 of son1"}
    node2.ChildNodes.Add(node3)   'Make node3 a child of node2
    RootNode.ChildNodes.Add(node2)   'Make node2 a child of the root node
    Nodes.Add(RootNode)   'Add the root node to the list of nodes
    DataContext = Nodes   'Make that list my data context
End Sub

I am using the definition of my Person class in Edit 3.  Here I just define the Root Node and two other nodes.  I add node3 as a child to node 2 then I add node 2 as a child to the root node and finally I add the root node to the Nodes List, which is then set as the datacontext for the Treeview.  That's it.
Using the datatemplate shown in Edit 2, I should have this in my tree view:
Root
    son1 of Root
        son1 of son1

but I don't.  Node 2 does not expand to show Node 3.  In other words, I just see this:
Root
    son1 of Root

Needless to say, I have no idea what is wrong.

A: You should bind the ItemsSource property of the TreeView to the List(Of Node). Try this:
<TreeView ItemsSource="{Binding}">
    <TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" />
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

It should populate the TreeView with the root nodes.
For any hierarchical data to be displayed, you need to add a ChildNodes property to the Node class and populate this one of each node with the corresponding child nodes. Then it would make sense to use an HierarchicalDataTemplate:
<HierarchicalDataTemplate ItemsSource="{Binding ChildNodes}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

Edit:
This should work just fine:
Public Class Node
    Public Property Id As Integer
    Public Property Name As String
    Public Property ParentId As Integer
    Public Property ChildNodes As List(Of Node) = New List(Of Node)
End Class

Private Sub Window1_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim Nodes = New List(Of Node)
    Dim RootNode As New Node With {.Id = 1, .ParentId = 0, .Name = "Root"}
    Dim node2 As New Node With {.ID = 2, .ParentID = 1, .Name = "son1 of Root"}
    Dim node3 As New Node With {.ID = 3, .ParentID = 2, .Name = "son1 of son1"}
    node2.ChildNodes.Add(node3)   'Make node3 a child of node2
    RootNode.ChildNodes.Add(node2)   'Make node2 a child of the root node
    Nodes.Add(RootNode)   'Add the root node to the list of nodes
    DataContext = Nodes   'Make that list my data context
End Sub

<TreeView ItemsSource="{Binding}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding ChildNodes}">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>


text:
Q: Directory mirroring over network I need a software or any other way to backup my home directory instantly so that if my data is lost I have another copy over the network.
I have a NAS on my local network and I want to have an exact copy of my machine home directory  over there
I don't want a SYNC behavior. What I need is a MIRROR

A: A simple script using rsync tool could solve your problem. The script is:
#!/bin/sh
while true
do rsync [source-folder] [destination-machine:folder]
sleep 5
done

If you want a real-time backup then you can just remove sleep 5  or make it as acomment #sleep 5
To make it autostarted with your user, You can make a launcher  then add this launcher to the startup Applications in order to autostart.
Moreover, you can find many other backup tools and other syncronization tools that help you but i just found this script easy to use

A: As outlined in the previous answers, rsync is the most efficient way for copying files over a network. This however requires you to manually initiate the mirroring process. If you want this to happen automatically like a one-way dropbox you can use lsyncd:
    sudo apt-get install lsyncd
    lsyncd -rsyncssh /home nashostname backup/dir/

A: Ubuntu 12.04 has a desktop backup application that serves that purpose.
You can search for "backup" in ubuntu dash and set the destination folder in "Storage" tab:

You may choose FTP, SSH, WebDAV, Windows Share (Samba) or a local folder.
Programs in question are deja-dup and duplicity.
Note: Sorry, this answer seems a bit off-topic since you need a mirrored folder readily available (is this the case?) and deja-dup creates compressed archives. Note that deja-dup allows you to restore specific files from backups (right-click on any file/folder and select "Revert to previous version").

A: Duplicity is very good and can use rsync as a backend. What I like most about it is the ability to configure filters, so if there are huge files  or files of certain extension you don't want backed up in that directory it's easy to make those adjustments. Note that deja-dup uses duplicity as it's backend and is a real easy way to get started, even creates sensible exclusion filters by default.
I recommend to cron this nightly. Start with a full backup once a week and then do an incremental nightly. See http://www.rsync.net/resources/howto/duplicity.html
for good examples.
If you want true real time mirroring then DRBD is the way to go but it's not without risk or complexity. You must create a "block stack" in which drbd is backed by your data store and mount that. It has several protocols that trade off between data integrity and speed e.g. sync vs async. It also has the complexity of "split brain" where if the source and/or target have moved forward and are not talking to each other, DRBD has to figure out which one is the one source of truth, makes that the primary and forces the secondary to resync to that, get  it wrong and you've lost your data.
So you have to ask yourself, do you really need a down instant a block IO is written mirror, and all the complexity and risk that goes with it, or will a periodic rsync (every 5m etc) be good enough?
Finally, data integrity is best down with a layered approached. Ideally your primary and secondary would both be backed by RAID 1 or similar then you would setup your sync with using the options provided that have a large spread in terms of trade offs between easy of use, data integrity, complexity, and risk.


text:
Q: Where does authorization code go in C# PayPal REST API Winforms app? I'm trying to access PayPal's API to submit invoices to clients through a C#.NET Winforms app, but I am terribly confused. Another user posted this code as a solution to connect:
public class PayPalClient
{
    public async Task RequestPayPalToken()
    {
        // Discussion about SSL secure channel
        // http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        try
        {
            // ClientId of your Paypal app API
            string APIClientId = "**_[your_API_Client_Id]_**";

            // secret key of you Paypal app API
            string APISecret = "**_[your_API_secret]_**";

            using (var client = new System.Net.Http.HttpClient())
            {
                var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);

                client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;

                var requestParams = new List<KeyValuePair<string, string>>
                            {
                                new KeyValuePair<string, string>("grant_type", "client_credentials")
                            };

                var content = new FormUrlEncodedContent(requestParams);
                var webresponse = await client.PostAsync(url, content);
                var jsonString = await webresponse.Content.ReadAsStringAsync();

                // response will deserialized using Jsonconver
                var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
            }
        }
        catch (System.Exception ex)
        {
            //TODO: Log connection error
        }
    }
}

public class PayPalTokenModel
{
    public string scope { get; set; }
    public string nonce { get; set; }
    public string access_token { get; set; }
    public string token_type { get; set; }
    public string app_id { get; set; }
    public int expires_in { get; set; }
}

I'm afraid this is at least one step ahead of me as I can't figure out where in my project it is appropriate to paste the code. Let's just say you created a brand new C# Winforms app. Without getting into the specifics of creating an invoice, etc. What code would I need to support the PayPal API and where in the project does it go? I know I need to get authorization for the app from PayPal, but I'm having trouble finding a good "Getting Started" guide for C# and PayPal. I've created a REST API app on PayPal, so I do have a client ID and "secret" to pass for Oauth authorization - I just can't find a place to do that.
Thanks in advance. I have some C#.net programming experience, but honestly my programming experience mostly goes back to VB6 so I kind of need the big picture explanation. Thanks for your patience!!

A: Sorry for posting an answer here but I currently do not have enough reputation to post comment. However if you are still looking for a general idea on how to get this done then I can provide a brief example. Since you are using WinForms and PayPal's API, I am assuming you have setup your App.Config file already?
Example-
  <!-- PayPal SDK settings -->
  <paypal>
    <settings>
      <add name="mode" value="sandbox" />
      <add name="clientId" value="insert_clientid_key_here" />
      <add name="clientSecret" value="Insert_client_secret_key_here" />
    </settings>
  </paypal>

Once this has been addressed then you can make your way over to your form and input what you are going to use. Example:
using System;
using System.Windows.Forms;
using PayPal.Api;
using System.Collections.Generic;

Now that is completed you can create a button to make the API Call.
Example:
        private void button1_Click_1(object sender, EventArgs e)
        {

            // Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);

// Make an API call
var payment = Payment.Create(apiContext, new Payment
{
    intent = "sale",
    payer = new Payer
    {
        payment_method = "paypal"
    },
    transactions = new List<Transaction>
    {
        new Transaction
        {
            description = "Transaction description.",
            invoice_number = "001",
            amount = new Amount
            {
                currency = "USD",
                total = "100.00",
                details = new Details
                {
                    tax = "15",
                    shipping = "10",
                    subtotal = "75"
                }
            },
            item_list = new ItemList
            {
                items = new List<Item>
                {
                    new Item
                    {
                        name = "Item Name",
                        currency = "USD",
                        price = "15",
                        quantity = "5",
                        sku = "sku"
                    }

                }
            }
        }
    },
    redirect_urls = new RedirectUrls
    {
        return_url = "http://x.com/return",
        cancel_url = "http://x.com/cancel"
    }

});
            MessageBox.Show("API Request Sent to Paypal");

        }

Once completed, test it out and you should have a sandbox call waiting for you.


text:
Q: Silverlight 3 scroll textblock in code i need to scroll the textblock text. For example, the textblock contains 700 words. These words are populated to the textblock from code behind as it could be a different 700 words depending on some "stuff". There is a textbox on this form as well. The user types the words in the textblock into the textbox. As they type i keep track of which word from the textblock they are on. However, not all the words in the textblock will fit in the textblock viewing area, so i need to scroll the textblock from code behind. How do i go about doing this.
I"m using silverlight 3.
Thanks shannon
might be useful to put some code in...
Here is the scrollviewer and text block
            <ScrollViewer x:Name="svSourceText" Width="591" MaxHeight="202" VerticalScrollBarVisibility="Auto">

                <TextBlock Height="202" Width="591"  TextWrapping="Wrap"
                x:Name="txtSource" FontSize="12" FontFamily="Fonts/Fonts.zip#Consolas" LineHeight="21.333"
                           />

        </ScrollViewer>

for starters.. when i add text into the txtSource, the scroll viewer doesn't change it's scroll bar to be the height needed.

A: Put the TextBlock in a scrollviewer. Capture the event when the user enters text into your TextBox. Check that it's valid for the word currently being captured and then scroll the TextBlock.
Here is an example. I'm just scrolling every time the user presses the space bar, you'd want to verify the validity of the word being entered.
XAML:
    <Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="25" />
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>

    <TextBox Name="txtInput" KeyUp="TextBox_KeyUp" Width="200" Grid.Row="0" />

    <ScrollViewer Name="scrollViewer" Grid.Row="1" MaxHeight="25" MaxWidth="250" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Hidden">
        <TextBlock>
            One
            <LineBreak />
            Two
            <LineBreak />
            Three
            <LineBreak />
            Four
            <LineBreak />
            Five
        </TextBlock>

    </ScrollViewer>

</Grid>

And the code for the event 'KeyUp':
        private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key.ToString().ToLower() == "space")
        {
            scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + 15);
        }
    }

A: Just a thought, have you considered using the AutoCompleteBox control?
You could bind its ItemsSource to an ObservableCollection<string> that contains all the current words and can have words added or removed as necessary.
As the user types in the TextBox area of the AutoComplete the set of matching words appear in a drop down.
Perhaps you are doing something else but I thought just post this in case it turns out you trying to re-invent the wheel.


text:
Q: Getting infinite loop because the number is too big to handle https://www.freecodecamp.org/learn/coding-interview-prep/project-euler/problem-5-smallest-multiple
I am solving Project Euler and this is the solution I came up with for the 5th question. It passes the first 5 test cases but fails at the last one. smallestMult(20)
I believe it is happening because the number gets too big when n>=17. (it is working in the codesnippet here without a problem)

function smallestMult(n) {
  let num = n
  let count = n

  while(true){
    num = num + n
    for(let i = n; i>0; i--){
      if(num%i==0){
        count = count - 1
      }
      if(count==0){
        return num
      }
    }
    count = n
  }
}
console.log(smallestMult(20));

Any idea on how to improve?

A: Your solution works however is less efficient. You can try this method:

function smallestMult(n) {
  let index = 1;
  let lcm= 1;
  // Loop until the last number
  while(index != n+1){
    // Get lcm of index and previous lcm
    lcm = findLcm(lcm,index)
    // Increment Index
    index++
  }
  return lcm
}

function findLcm(n1,n2){
let hcf;
// looping from 1 to number1 and number2 to find HCF
for (let i = 1; i <= n1 && i <= n2; i++) {
    // check if is factor of both integers
    if( n1 % i == 0 && n2 % i == 0) {
        hcf = i;
    }
}
// find LCM
let lcm = (n1 * n2) / hcf;
return lcm
}

console.log(smallestMult(24))
console.log(smallestMult(17))
console.log(smallestMult(29))


text:
Q: Where would be the best place to host my simple Flask API? I have a Flask API which has no database but just a json file that stores the data. At the moment I have put it on an EC2 and opened a port so someone can put in the IP address and port and have access to the API that way. The problem with this is that I get a mixed content error since the site it uses is HTTPS and the API is HTTP. I want to put the API behind HTTPS on a proper platform but I'm not sure where to start.
Is there a platform that I can host the API python file and the json file behind an HTTPS?

A: All of them? EC2 allows HTTPS (per @tawfikboujeh's comment). I don't actually know a hosting platform that would allow HTTP but not HTTPS.
There are some options in how you accomplish this:

*

*Use a self-signed certificate. This will give you HTTPS but all the modern browsers will give a nasty warning to all your visitors.

*Purchase a signed certification for you IP address from a CA. Just hope you don't have to change your IP address.

*Purchase a domain and use Let's Encrypt to generate a signed certificate for you.

Option 3 would be the most robust solution, but it does carry the cost of a domain (maybe $10/year).

A: Google App Engine is perfect for this.  SSL cert is free, and you would be in their free tier.
https://cloud.google.com/free


text:
Q: Count of dataframe column above a threshold I have a dataframe where I want to find the count of all ID above a threshold. For example
  index  DEVICE_ID DIFF
   0         12     3
   1         12     4
   2         12     5
   3         12     3
   4         13     2
   5         13     4
   6         13     1
   7         14     3
   8         14     6

If 'Diff' is greater than or equals to 4, give me the count of the IDs starting from that index for each unqiue ID, so the above dataframe will result in:
  {12:3, 13:2, 14:1} - For ID 12, the diff column is 4 on index 1 so we count the amount of 12's from and including index 1 till 3

Sorry for the badly worded question.

A: Compare column by Series.ge (>=) first, then grouping by df['DEVICE_ID'] and use cumsum, compare by Series.gt and aggregate sum for count True values:
s = df['DIFF'].ge(4).groupby(df['DEVICE_ID']).cumsum().gt(0).astype(int)

out = s.groupby(df['DEVICE_ID']).sum().to_dict()
print (out)
{12: 3, 13: 2, 14: 1}

Detail:
print (df['DIFF'].ge(4).groupby(df['DEVICE_ID']).cumsum())
index
0    0.0
1    1.0
2    2.0
3    2.0
4    0.0
5    1.0
6    1.0
7    0.0
8    1.0
Name: DIFF, dtype: float64

Another solution with index by DEVICE_ID, then gro by index with level=0 and last use only sum per index (level=0):
out = (df.set_index(['DEVICE_ID'])['DIFF']
         .ge(4)
         .groupby(level=0)
         .cumsum()
         .gt(0)
         .astype(int)
         .sum(level=0)
         .to_dict())

A: Using cumprod
s=df.DIFF.lt(4).astype(int).groupby(df['DEVICE_ID']).cumprod()
s=(1-s).groupby(df['DEVICE_ID']).sum()
s
DEVICE_ID
12    3
13    2
14    1
Name: DIFF, dtype: int32

A: Using df.shift()
df['T_F']=(df.DIFF>=4)
df[df.T_F != df.T_F.shift(1)].groupby('DEVICE_ID')['DEVICE_ID'].count().to_dict()

{12: 3, 13: 2, 14: 1}


text:
Q: Facebook/ Twitter with dotnetopenauth? I've pretty much got OpenID working using the DotNetOpenAuth library. Now I would like users to be able to use Facebook and Twitter to login.
This requires OAuth so I am looking for a tutorial on how to use DotNetOpenAuth OAuth.
I'm having trouble trying to find some simple tutorials on how to do this.
Can anyone please help?

A: At the time of me answering this question, DotNetOpenAuth has a public Community Tech Preview (CTP) which is available to download.

*

*Download that source code. Should be a .7z file. You can use 7-Zip to unzip the code if you don't already have it (it's free).

*Open up the samples source code solution in Visual Studio. I'm using VS2010 but I think there's also a VS2008 solution file.

*Now, open up the web.config file for the OAuthClient project.

*Next, edit the following settings :-
<!-- Facebook sign-up: http://developers.facebook.com/setup/ -->
<add key="facebookAppID" value="------"/>
<add key="facebookAppSecret" value="------------"/>
You can get these values from your application on Facebook.

*Debug/Run the OAuthClient Web Application. This will start an instance of Cassini/Visual Studio Developer Server and a web browser should open:

Voilà! you can now connect to Facebook to log in.
If you get errors, then you need to make sure that:

*

*You've manually changed the Facebook app settings in your web.config file.

*You've correctly setup your app settings in the Facebook developer website.


text:
Q: html table cell with fixed size compressed in div The css file is as follows:
   #table_container {
        border-collapse: collapse;
        border-spacing: 0;
        padding: 0;
        overflow: scroll;
        white-space: nowrap;
    }
    table, tr,td{
       border: 2px solid blue;
       border-collapse: collapse;
    }

    td {
        height: 30px;
        width: 30px;
        text-align: center;
        background-color: white;
        color: black;
    }

You can refer to the following link:
https://jsfiddle.net/xuvtge5n/
I set the table cell to a fixed size 30px * 30px
However, when the dimension of table increase to a large size, like 60*60, the cell will be compressed together and become a rectangle. The length displayed should be 30px but the width is not.
I set the overflow property to scroll or auto but it does not help.
I want the table can be scrolled inside the div vertically and horizontally and display the table cell like a square without compressing together.
Please tell if anything missing.

A: Set table width 100% and layout as fixed
table {
    table-layout: fixed;
    width: 100%;
}

https://jsfiddle.net/xuvtge5n/2/