问:
Dockerizing Django application: ModuleNotFoundError: No module named 'X"
I've been trying to follow this guide to Dockerize a project:

Deploy and Run Django in Dokcer Container

This is the base file structure:

```<code>WFMBCM
|-WFMBCM
| |-__init__.py
| |-__pycache__
| |-setting.py
| |-url.py
| |-wsgi.py
|
|-WFMBCM_App
|-WFMBCM_db
|-manage.py
|-Dockerfile
|-requirements.txt
|-runWFMBCM.sh
</code>```

Dockerfile:

```<code>FROM python:3.7
ADD WFMBCM /usr/src/app
ADD WFMBCM_App /usr/src/app
ADD WFMBCM_db /usr/src/app
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
</code>```

requirements.txt:

```<code>Django==2.2.1
gunicorn==19.9.0
</code>```

runWFMBCM.sh:

```<code>cd /home/admin/WFMBCM
echo -e "\033[0;34mGo to WFMBCM directory.\n \033[0;37m"
echo -e "\033[0;34mRemove old WFMBCM container\n \033[0;37m"
docker rm -v wfmbcm_container
echo -e "\033[0;34m\nBuild WFMBCM Docker image.\n \033[0;37m"
sudo docker build -t wfmbcm .
echo -e "\033[0;34m\nRun WFMBCM Docker image.\n \033[0;37m"
sudo docker run --name wfmbcm_container -p 8000:8000 -i -t wfmbcm
echo -e "\033[0;34m\n\nWFMBCM run-script ended!.\n \033[0;37m"
</code>```

When I run runWFMBCM.sh I get the following output:

```<code>Go to WFMBCM directory.

Remove old WFMBCM container

Error response from daemon: No such container: wfmbcm_container

Build WFMBCM Docker image.

Sending build context to Docker daemon  265.2kB
Step 1/10 : FROM python:3.7
 ---> cc971a68c3e4
Step 2/10 : ADD WFMBCM /usr/src/app
 ---> Using cache
 ---> 302346d017e2
Step 3/10 : ADD WFMBCM_App /usr/src/app
 ---> Using cache
 ---> 18bc8eb69946
Step 4/10 : ADD WFMBCM_db /usr/src/app
 ---> Using cache
 ---> 0835393b22dc
Step 5/10 : ADD manage.py /usr/src/app
 ---> Using cache
 ---> 3ef5477e4b26
Step 6/10 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 2edb019a8257
Step 7/10 : COPY requirements.txt ./
 ---> Using cache
 ---> df3ac922b7a0
Step 8/10 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Using cache
 ---> ba6cf54e7dcc
Step 9/10 : EXPOSE 8000
 ---> Using cache
 ---> 94f3f4fb38c0
Step 10/10 : CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
 ---> Using cache
 ---> db6cf2149949
Successfully built db6cf2149949
Successfully tagged wfmbcm:latest

Run WFMBCM Docker image.

[2019-05-26 09:59:36 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-05-26 09:59:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2019-05-26 09:59:36 +0000] [1] [INFO] Using worker: sync
[2019-05-26 09:59:36 +0000] [9] [INFO] Booting worker with pid: 9
[2019-05-26 09:59:36 +0000] [10] [INFO] Booting worker with pid: 10
[2019-05-26 09:59:36 +0000] [9] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [9] [INFO] Worker exiting (pid: 9)
[2019-05-26 09:59:36 +0000] [11] [INFO] Booting worker with pid: 11
[2019-05-26 09:59:36 +0000] [10] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [10] [INFO] Worker exiting (pid: 10)
[2019-05-26 09:59:36 +0000] [11] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [11] [INFO] Worker exiting (pid: 11)
[2019-05-26 09:59:37 +0000] [1] [INFO] Shutting down: Master
[2019-05-26 09:59:37 +0000] [1] [INFO] Reason: Worker failed to boot.

WFMBCM run-script ended!.
</code>```

Why can't it find wfmbcm module? I've been staring crazy and googling without success and looking at different stack overflow questions.

答:
I can't find any python module named wfmbcm, so I assume that it's an app in your project.

If you are on a case sensitive file system, then your file layout shows all caps for some folders and that might be (part of) the issue.

Does this project run outside of docker?

If it does, then I think that your best bet is to start the docker container and then manually install the entire app inside the container, updating the dockerfile with the steps as you go.

Every time you test a new change, make sure that you build with the --no-cache option or you may not be testing what you think you are.

Body:
I've been trying to follow this guide to Dockerize a project:

Deploy and Run Django in Dokcer Container

This is the base file structure:

WFMBCM
|-WFMBCM
| |-__init__.py
| |-__pycache__
| |-setting.py
| |-url.py
| |-wsgi.py
|
|-WFMBCM_App
|-WFMBCM_db
|-manage.py
|-Dockerfile
|-requirements.txt
|-runWFMBCM.sh

Dockerfile:

FROM python:3.7
ADD WFMBCM /usr/src/app
ADD WFMBCM_App /usr/src/app
ADD WFMBCM_db /usr/src/app
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3

requirements.txt:

Django==2.2.1
gunicorn==19.9.0

runWFMBCM.sh:

cd /home/admin/WFMBCM
echo -e "\033[0;34mGo to WFMBCM directory.\n \033[0;37m"
echo -e "\033[0;34mRemove old WFMBCM container\n \033[0;37m"
docker rm -v wfmbcm_container
echo -e "\033[0;34m\nBuild WFMBCM Docker image.\n \033[0;37m"
sudo docker build -t wfmbcm .
echo -e "\033[0;34m\nRun WFMBCM Docker image.\n \033[0;37m"
sudo docker run --name wfmbcm_container -p 8000:8000 -i -t wfmbcm
echo -e "\033[0;34m\n\nWFMBCM run-script ended!.\n \033[0;37m"

When I run runWFMBCM.sh I get the following output:

Go to WFMBCM directory.

Remove old WFMBCM container

Error response from daemon: No such container: wfmbcm_container

Build WFMBCM Docker image.

Sending build context to Docker daemon  265.2kB
Step 1/10 : FROM python:3.7
 ---> cc971a68c3e4
Step 2/10 : ADD WFMBCM /usr/src/app
 ---> Using cache
 ---> 302346d017e2
Step 3/10 : ADD WFMBCM_App /usr/src/app
 ---> Using cache
 ---> 18bc8eb69946
Step 4/10 : ADD WFMBCM_db /usr/src/app
 ---> Using cache
 ---> 0835393b22dc
Step 5/10 : ADD manage.py /usr/src/app
 ---> Using cache
 ---> 3ef5477e4b26
Step 6/10 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 2edb019a8257
Step 7/10 : COPY requirements.txt ./
 ---> Using cache
 ---> df3ac922b7a0
Step 8/10 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Using cache
 ---> ba6cf54e7dcc
Step 9/10 : EXPOSE 8000
 ---> Using cache
 ---> 94f3f4fb38c0
Step 10/10 : CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
 ---> Using cache
 ---> db6cf2149949
Successfully built db6cf2149949
Successfully tagged wfmbcm:latest

Run WFMBCM Docker image.

[2019-05-26 09:59:36 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-05-26 09:59:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2019-05-26 09:59:36 +0000] [1] [INFO] Using worker: sync
[2019-05-26 09:59:36 +0000] [9] [INFO] Booting worker with pid: 9
[2019-05-26 09:59:36 +0000] [10] [INFO] Booting worker with pid: 10
[2019-05-26 09:59:36 +0000] [9] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [9] [INFO] Worker exiting (pid: 9)
[2019-05-26 09:59:36 +0000] [11] [INFO] Booting worker with pid: 11
[2019-05-26 09:59:36 +0000] [10] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [10] [INFO] Worker exiting (pid: 10)
[2019-05-26 09:59:36 +0000] [11] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [11] [INFO] Worker exiting (pid: 11)
[2019-05-26 09:59:37 +0000] [1] [INFO] Shutting down: Master
[2019-05-26 09:59:37 +0000] [1] [INFO] Reason: Worker failed to boot.

WFMBCM run-script ended!.

Why can't it find wfmbcm module? I've been staring crazy and googling without success and looking at different stack overflow questions.


来源: stackexchange

问:
Dynamically update values of a chartjs chart
I created an basic bar chart using chartjs and it works fine. Now I want to update the values on a time based interval. My problem is that after I created the chart, I do not know how to update its values correctly...

My code:

```<code>var ctx = $("#myChart").get(0).getContext("2d");

var dts = [
    {
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,1)",
        data: [0, 0, 0, 0, 0]
    }
];

var data = {
    labels: ["Core#1", "Core#2", "Core#3", "Core#4", "Total"],
    datasets: dts
};

var chart = new Chart(ctx);
chart.Bar(data);

//test code
setInterval( function () {
    data.datasets[0].data = [random(), random(), random(), random(), random()];
    chart.Bar(data);

},2000);
</code>```

in the test code, I am updating the values with datasets[0].data- is this the right way to do it? The problem with this is that everytime I call chart.Bar(), the values are reset to 0 then animated to the random value (like I am recreating the chart). This way, all animations are always from 0 to value which looks strange. I would expect that if I update a value from 50 to 10 the bar would go down to 10 from 50 and not setted to 0 then animated to 10.

I did not found anything in the docs about this... am I doing something wrong or this is impossible with this library?

答:
Showing realtime update chartJS

```<code>function add_data(chart, label, data)
      {
        var today = new Date();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        myLineChart.data.datasets[0].data.push(Math.random() * 100);
        myLineChart.data.datasets[1].data.push(Math.random() * 100);
        myLineChart.data.labels.push(time)
        myLineChart.update();
      }
      setInterval(add_data, 10000); //milisecond
</code>```

full code , you can download in description link

ContentLicense: CC BY-SA 3.0

Body:
I created an basic bar chart using chartjs and it works fine. Now I want to update the values on a time based interval. My problem is that after I created the chart, I do not know how to update its values correctly...

My code:

var ctx = $("#myChart").get(0).getContext("2d");

var dts = [
    {
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,1)",
        data: [0, 0, 0, 0, 0]
    }
];

var data = {
    labels: ["Core#1", "Core#2", "Core#3", "Core#4", "Total"],
    datasets: dts
};

var chart = new Chart(ctx);
chart.Bar(data);

//test code
setInterval( function () {
    data.datasets[0].data = [random(), random(), random(), random(), random()];
    chart.Bar(data);

},2000);

in the test code, I am updating the values with datasets[0].data- is this the right way to do it? The problem with this is that everytime I call chart.Bar(), the values are reset to 0 then animated to the random value (like I am recreating the chart). This way, all animations are always from 0 to value which looks strange. I would expect that if I update a value from 50 to 10 the bar would go down to 10 from 50 and not setted to 0 then animated to 10.

I did not found anything in the docs about this... am I doing something wrong or this is impossible with this library?

Body:
Showing realtime update chartJS

function add_data(chart, label, data)
      {
        var today = new Date();
        var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        myLineChart.data.datasets[0].data.push(Math.random() * 100);
        myLineChart.data.datasets[1].data.push(Math.random() * 100);
        myLineChart.data.labels.push(time)
        myLineChart.update();
      }
      setInterval(add_data, 10000); //milisecond

full code , you can download in description link

ContentLicense: CC BY-SA 4.0


问:
How to push data to client's server
We have a system in place which collects data from multiple sensors and stores the data into the database, we have a website where our customers can log in and view their data.

Now one of our customers wants to display the data from our server into their web site.
I created a web service and gave them access to collect the data from the our database and import it into their website, but they are requesting us to push the data to their server.
I am not sure how this can be done! Can anyone help me with this?

Thanks

答:
I did the same thing that you're trying to do a year ago. Apart from viewing the data at the client's side, I also displayed an almost real-time graph where the graph would be updated after a specific interval of time set by you (I set it as 1 second). The real-time data transmission thing was handled by PubNub framework. You can go through my implementation on GitHub below.

RealTime Arduino Sensor Data Visualization

Title: How to push data to client's server


问:
Elastic Search sub string match
I have elastic search node containing index like this :

```<code>"_index" : "barivara",
       "_type" : "_doc",
       "_id" : "3",
       "_score" : 1.0,
       "_source" : {
         "area" : "Mirpur",
         "address" : "house:5; MIrpur",
         "description" : "home",
         "price" : 400,
         "number of members" : 5,
         "building amenities" : "5",
         "number of bed" : 7,
         "number of bath" : 2,
         "rentaltype" : "flat",
         "fttext" : "Mirpur 7 bedroom 2 bathroom flat 10 members"
       }
     }
</code>```

I added the text field for full text search, but when I am searching "3 bedroom Mirpur"

The index containing 7 bedroom also appears.

Heres my query/

```<code>GET /barivara/_search
{
  "query": {
    "bool": {
      "must": {
        "match": {
          "fttext": {
            "query":                "bedroom:3 Mirpur",
            "minimum_should_match": "100%"
          }
        }
      }
    }
  }
}
</code>```

can someone help me? I am a noob in elastic search.

答:
You need to give more info on what type of analyser you have configured, and what is the schema of your document, assuming they are standard, here is my take.

The query is converted to tokens based on analyzer

Then based on internal inverted index, it finds out which all documents match them

Then based on relevance score, order them and return the results.

So, in your case, input "bedroom:3 Mirpur" is broken down in 3 words "bedroom", "3" and "Mirpur" and is search against all the documents inside field "fttext" in the index, and return the results.

So in you case, "7 bedroom" documents will also appear as 2 out of 3 terms are matched for those document but such document will be placed below the "3 bedroom" documents

NOTE : Assuming fttext is type of "text" and not "keyword" in your schema. Keyword as not analyzed during indexing and are stored as "whole word(s)". So "contains" does not work on them, exact search do.

Title: Elastic Search sub string match

Body:
I have elastic search node containing index like this :

"_index" : "barivara",
       "_type" : "_doc",
       "_id" : "3",
       "_score" : 1.0,
       "_source" : {
         "area" : "Mirpur",
         "address" : "house:5; MIrpur",
         "description" : "home",
         "price" : 400,
         "number of members" : 5,
         "building amenities" : "5",
         "number of bed" : 7,
         "number of bath" : 2,
         "rentaltype" : "flat",
         "fttext" : "Mirpur 7 bedroom 2 bathroom flat 10 members"
       }
     }

I added the text field for full text search, but when I am searching "3 bedroom Mirpur"

The index containing 7 bedroom also appears.

Heres my query/

GET /barivara/_search
{
  "query": {
    "bool": {
      "must": {
        "match": {
          "fttext": {
            "query":                "bedroom:3 Mirpur",
            "minimum_should_match": "100%"
          }
        }
      }
    }
  }
}

can someone help me? I am a noob in elastic search.


问:
How to show Snackbar above FloatingActionBar (fab) placed on Bottom App Bar (Material design)
I was trying out the new material Bottom App bar. In design guidelines it's told "Inset a snackbar or toast above a bottom app bar and FAB" but I'm not sure to how to do it. Can anyone help me. Below are the codes that I'm using:

MainActivity

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show());
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.bottomappbar.BottomAppBar
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorAccent"
        app:fabAlignmentMode="end" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/bar"
        app:layout_anchorGravity="bottom" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

styles.xml

```<code><style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.MaterialComponents.Light" />
</code>```

gradle

```<code>android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "..."
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }
    buildToolsVersion = '28.0.2'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
</code>```

The problem is that whenever I click the fab button the snackbar appears above the bottom app bar and also pushes the fab above. Below is the image for the problem.

答:
Please use the setAnchorView() Method :-</p>

```<code>Snackbar.make(CoordinatorLayoutView, "your text", Snackbar.LENGTH_SHORT)
                        .setAnchorView(BottomAppBarView or FabButtonView).show();
</code>```

Body:
I was trying out the new material Bottom App bar. In design guidelines it's told "Inset a snackbar or toast above a bottom app bar and FAB" but I'm not sure to how to do it. Can anyone help me. Below are the codes that I'm using:

MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show());
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

    <com.google.android.material.bottomappbar.BottomAppBar
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/colorAccent"
        app:fabAlignmentMode="end" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/bar"
        app:layout_anchorGravity="bottom" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

styles.xml

Body:
Please use the setAnchorView() Method :-

Snackbar.make(CoordinatorLayoutView, "your text", Snackbar.LENGTH_SHORT)
                        .setAnchorView(BottomAppBarView or FabButtonView).show();


问:
How to get xml node value based on attribute value c# , asp.net?
how to get xmlnode value based on attribute value in C#.

```<code><Products>
  <Error>0</Error>
  <Product link="OWN">
    <ProductCode>CA</ProductCode>
    <ProductType>Account</ProductType>
    <ProductSubtype>Current Account</ProductSubtype>
    <ProductDescriptionEng>Current Account</ProductDescriptionEng>
    <ProductNumber>1234567</ProductNumber>
    <ProductCurrency></ProductCurrency>
    <ProductCurrencyCode>01</ProductCurrencyCode>
    <ProductBalance>899293.003</ProductBalance>
    <LoanRef></LoanRef>
    <OldLoanRef></OldLoanRef>
    <ProductStandardID>00010001</ProductStandardID>
    <OldLoanRef></OldLoanRef>
    <ProductStatusCode>00</ProductStatusCode>
    <ProductStatus>OPEN</ProductStatus>
    <ProductCategory>Deposit Account</ProductCategory>
  </Product>
</Product>
</code>```

in the above example i would like to get value of Product Link "OWN" based on passing attribute value (1234567)  1234567.

I have tried following code but it doesn't return value "OWN" from 'Product link" node.

```<code>string _accountsXml = GetProducts();
                _xmlDoc.LoadXml(_accountsXml);
                _productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[../ProductNumber = '{0}']", prodNumber));
</code>```

答:
Try this

```<code>_productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber));
</code>```

or

```<code>var xDoc = XDocument.Load(_accountsXml);
var productLinkType = xDoc.XPathSelectElement(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber)).Element("Product").Attribute("link").Value;
</code>```

The closing tag in your example is Product it should be Products

Body:
how to get xmlnode value based on attribute value in C#.

<Products>
  <Error>0</Error>
  <Product link="OWN">
    <ProductCode>CA</ProductCode>
    <ProductType>Account</ProductType>
    <ProductSubtype>Current Account</ProductSubtype>
    <ProductDescriptionEng>Current Account</ProductDescriptionEng>
    <ProductNumber>1234567</ProductNumber>
    <ProductCurrency></ProductCurrency>
    <ProductCurrencyCode>01</ProductCurrencyCode>
    <ProductBalance>899293.003</ProductBalance>
    <LoanRef></LoanRef>
    <OldLoanRef></OldLoanRef>
    <ProductStandardID>00010001</ProductStandardID>
    <OldLoanRef></OldLoanRef>
    <ProductStatusCode>00</ProductStatusCode>
    <ProductStatus>OPEN</ProductStatus>
    <ProductCategory>Deposit Account</ProductCategory>
  </Product>
</Product>

in the above example i would like to get value of Product Link "OWN" based on passing attribute value (1234567)  1234567.

I have tried following code but it doesn't return value "OWN" from 'Product link" node.

string _accountsXml = GetProducts();
                _xmlDoc.LoadXml(_accountsXml);
                _productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[../ProductNumber = '{0}']", prodNumber));

Body:
Try this

_productLinkType = _xmlDoc.SelectSingleNode(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber));

or

var xDoc = XDocument.Load(_accountsXml);
var productLinkType = xDoc.XPathSelectElement(string.Format("//Products[..//ProductNumber = '{0}']", prodNumber)).Element("Product").Attribute("link").Value;

The closing tag in your example is Product it should be Products


问:
Deny code execution IIS7 with web.config
I want to block users run specific extensions in an upload folder (/assets/public/) of a web application. Users can upload image files which are also re-sized during the upload. But for more security I want to deny scripts like aspx, asp, php...

I have current code which blocks every extension but I want to allow extensions like .jpg:

```<code><location path="assets/public">
    <system.web>
        <authorization>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</code>```

Also users do not have FTP access and application is pre-compiled.

答:
Here is how I solved this with global.asax and routing. Just added these rules:</p>

```<code>routes.MapPageRoute("any", "assets/public/{file}.{ext}", "~/e/404.aspx");
routes.MapPageRoute("any-sub","assets/public/{sub}/{file}.{ext}","~/e/404.aspx");

routes.Ignore("{any}.jpg");
routes.Ignore("{any}.png");
routes.Ignore("{any}.gif");
routes.Ignore("{any}.pdf");
</code>```

Body:
I want to block users run specific extensions in an upload folder (/assets/public/) of a web application. Users can upload image files which are also re-sized during the upload. But for more security I want to deny scripts like aspx, asp, php...

I have current code which blocks every extension but I want to allow extensions like .jpg:

<location path="assets/public">
    <system.web>
        <authorization>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

Also users do not have FTP access and application is pre-compiled.

Body:
Here is how I solved this with global.asax and routing. Just added these rules:

routes.MapPageRoute("any", "assets/public/{file}.{ext}", "~/e/404.aspx");
routes.MapPageRoute("any-sub","assets/public/{sub}/{file}.{ext}","~/e/404.aspx");

routes.Ignore("{any}.jpg");
routes.Ignore("{any}.png");
routes.Ignore("{any}.gif");
routes.Ignore("{any}.pdf");


问:
how to turn a list of strings in a list of objects?
I have a list of strings from an external text file. Each string is like this: name job location. What is the fastest way to turn each string into an object, creating a list of objects?

The objects are like this:

class Person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location
```

答:
I suggest reading the file line by line.
For each line you split it into the sub strings which are then name, job and location.
You can create a people object from these and push it into a list.</p>


问:
How can I compare two string format times?
I have a collection called "project" which is having a field expected time and actual time both are in string format

```<code>{
    "_id" : ObjectId("5ce7455d77af2d1143f84d49"),
    "project_name" : "p1",
    "expected" : "0:11:30",
    "actual" : "7:30:00",
}
</code>```

How can I compare two string format times using mongodb?
I want to find if actual time is more than expected

答:
You can use $split with $toInt (MongoDB 4.0 or newer) to convert your string values to a number of seconds and then use $expr to compare both fields:</p>

```<code>db.col.aggregate([
    {
        $addFields: {
            expected: {
                $let: {
                    vars: {
                        parts: {
                            $split: [ "$expected", ":" ]
                        }
                    },
                    in: {
                        $sum: [
                            { $toInt: { $arrayElemAt: [ "$$parts", 2 ] } },
                            { $multiply: [ 60, { $toInt: { $arrayElemAt: [ "$$parts", 1 ] } }  ] },
                            { $multiply: [ 3600, { $toInt: { $arrayElemAt: [ "$$parts", 0 ] } }  ] }
                        ]
                    }
                }
            },
            actual: {
                $let: {
                    vars: {
                        parts: {
                            $split: [ "$actual", ":" ]
                        }
                    },
                    in: {
                        $sum: [
                            { $toInt: { $arrayElemAt: [ "$$parts", 2 ] } },
                            { $multiply: [ 60, { $toInt: { $arrayElemAt: [ "$$parts", 1 ] } }  ] },
                            { $multiply: [ 3600, { $toInt: { $arrayElemAt: [ "$$parts", 0 ] } }  ] }
                        ]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: { $gt: [ "$expected", "$actual" ] }
        }
    }
])
</code>```

Body:
I have a collection called "project" which is having a field expected time and actual time both are in string format

{
    "_id" : ObjectId("5ce7455d77af2d1143f84d49"),
    "project_name" : "p1",
    "expected" : "0:11:30",
    "actual" : "7:30:00",
}

How can I compare two string format times using mongodb?
I want to find if actual time is more than expected

Body:
You can use $split with $toInt (MongoDB 4.0 or newer) to convert your string values to a number of seconds and then use $expr to compare both fields:

db.col.aggregate([
    {
        $addFields: {
            expected: {
                $let: {
                    vars: {
                        parts: {
                            $split: [ "$expected", ":" ]
                        }
                    },
                    in: {
                        $sum: [
                            { $toInt: { $arrayElemAt: [ "$$parts", 2 ] } },
                            { $multiply: [ 60, { $toInt: { $arrayElemAt: [ "$$parts", 1 ] } }  ] },
                            { $multiply: [ 3600, { $toInt: { $arrayElemAt: [ "$$parts", 0 ] } }  ] }
                        ]
                    }
                }
            },
            actual: {
                $let: {
                    vars: {
                        parts: {
                            $split: [ "$actual", ":" ]
                        }
                    },
                    in: {
                        $sum: [
                            { $toInt: { $arrayElemAt: [ "$$parts", 2 ] } },
                            { $multiply: [ 60, { $toInt: { $arrayElemAt: [ "$$parts", 1 ] } }  ] },
                            { $multiply: [ 3600, { $toInt: { $arrayElemAt: [ "$$parts", 0 ] } }  ] }
                        ]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: { $gt: [ "$expected", "$actual" ] }
        }
    }
])


问:
How to make a Map of Map using Collectors
I'm blocked in using Java Functional Programing for Map building.
In my use case, that is just an example, I would like to build a Map<Integer, Map<Integer, List<Person>>> starting from a List<Person> .

The first step is easy : I build a first Map<Integer, List<person>>.

Then I want to add a new grouping level so it will produce a new Map : Map<Integer, Map<Integer, List<person>>>.

The point is : how to correctly use all Collectors capabilities (groupingBy, mapping, maybe something else) to add a new grouping level ?
All my tries failed : compiler always tells me that all my provided functions do not fit with what it expects.

Here is the code, briefly :

First a Person class and then a method to quicly build a List :

```<code>public class Person {

  private long id;
  private String firstName;
  private String lastName;
  private Date birthDate;
  private int alea;
  ...
</code>```

This method (located in a DataBuilder class) just builds a list of Person to provide datas to the Main class :

```<code>public List<Person> getPersons() {

        List<Person> persons = new ArrayList<>();
        Supplier<Person> person = Person::new;

        for (int cpt = 0; cpt < 10; cpt++) {
            Person p = person.get();
            p.setId(cpt);
            p.setFirstName("fn" + cpt);
            p.setLastName("ln" + cpt);
            p.setBirthDate(new Date(119, cpt, 10 + cpt));
            p.setAlea(cpt % 2);
            persons.add(p);
        }

        return persons;

    }
</code>```

In the Main, building the first level of Map is not a problem :

```<code>public static void main(String[] args) {

    DataBuilder db = new DataBuilder();

    List<Person> persons = db.getPersons();

    Map<Integer, List<Person>> mapAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())));

        mapAleaPerson.forEach((k,v) -> System.out.printf("%n%s contains %s%n", k, v));
</code>```

Result is OK in the console :

```<code>0 contains [Person [id=0, firstName=fn0, lastName=ln0, alea=0], Person [id=2, firstName=fn2, lastName=ln2, alea=0], Person [id=4, firstName=fn4, lastName=ln4, alea=0], Person [id=6, firstName=fn6, lastName=ln6, alea=0], Person [id=8, firstName=fn8, lastName=ln8, alea=0]]

1 contains [Person [id=1, firstName=fn1, lastName=ln1, alea=1], Person [id=3, firstName=fn3, lastName=ln3, alea=1], Person [id=5, firstName=fn5, lastName=ln5, alea=1], Person [id=7, firstName=fn7, lastName=ln7, alea=1], Person [id=9, firstName=fn9, lastName=ln9, alea=1]]
</code>```

Now I would like to add an new grouping level. I've chosen BirthDate's year, that is another property of a Person object.

Basically, I tried somthing like this :

```<code>Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.toMap(Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));
</code>```

Casting doesn't help :

```<code>@SuppressWarnings("unchecked")
        Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.toMap((Function<Integer, List<Person>>) Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));
</code>```

I also tried with Collectors.mapping instead of Collectors.toMap :

```<code>Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.mapping((Function<Integer, List<Person>>) Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));
</code>```

Each time the compiler returns error because of uncompliant Function type.

The only way I've found to add the new grouping level was with old Java code and external loop adding and grouping datas in a Map of Map.

It's desapointing to embed FP in old Java!!

Have someone any idea of doing all of that with pure FP ?

After @eran answer (that works great), here's what I've done and its result :

```<code>Map<Integer, Map<Integer, List<Person>>> mapByYearThenAleaPerson = persons.stream().collect(
                Collectors.groupingBy(p -> p.getBirthDate().getYear() + 1900, Collectors.groupingBy(Person::getAlea)));

{2018={0=[Person [id=0, firstName=fn0, lastName=ln0, alea=0], Person [id=2, firstName=fn2, lastName=ln2, alea=0], Person [id=4, firstName=fn4, lastName=ln4, alea=0]], 1=[Person [id=1, firstName=fn1, lastName=ln1, alea=1], Person [id=3, firstName=fn3, lastName=ln3, alea=1]]}, 2019={0=[Person [id=6, firstName=fn6, lastName=ln6, alea=0], Person [id=8, firstName=fn8, lastName=ln8, alea=0]], 1=[Person [id=5, firstName=fn5, lastName=ln5, alea=1], Person [id=7, firstName=fn7, lastName=ln7, alea=1], Person [id=9, firstName=fn9, lastName=ln9, alea=1]]}}
</code>```

What is really surprenising, is the simplicity of nested groupingBy statement compared to the way of builging the first Map itself.

Why don't we need to specify mapping and Collectors.toList() anymore ?

答:
Use nested groupingBy:

```<code>Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson =
    persons.stream()
           .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                                          Collectors.groupingBy(Person::getAlea)));
</code>```

Body:
I'm blocked in using Java Functional Programing for Map building.
In my use case, that is just an example, I would like to build a Map<Integer, Map<Integer, List<Person>>> starting from a List<Person> .

The first step is easy : I build a first Map<Integer, List<person>>.

Then I want to add a new grouping level so it will produce a new Map : Map<Integer, Map<Integer, List<person>>>.

The point is : how to correctly use all Collectors capabilities (groupingBy, mapping, maybe something else) to add a new grouping level ?
All my tries failed : compiler always tells me that all my provided functions do not fit with what it expects.

Here is the code, briefly :

First a Person class and then a method to quicly build a List :

public class Person {

  private long id;
  private String firstName;
  private String lastName;
  private Date birthDate;
  private int alea;
  ...

This method (located in a DataBuilder class) just builds a list of Person to provide datas to the Main class :

public List<Person> getPersons() {

        List<Person> persons = new ArrayList<>();
        Supplier<Person> person = Person::new;

        for (int cpt = 0; cpt < 10; cpt++) {
            Person p = person.get();
            p.setId(cpt);
            p.setFirstName("fn" + cpt);
            p.setLastName("ln" + cpt);
            p.setBirthDate(new Date(119, cpt, 10 + cpt));
            p.setAlea(cpt % 2);
            persons.add(p);
        }

        return persons;

    }

In the Main, building the first level of Map is not a problem :

public static void main(String[] args) {

    DataBuilder db = new DataBuilder();

    List<Person> persons = db.getPersons();

    Map<Integer, List<Person>> mapAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())));

        mapAleaPerson.forEach((k,v) -> System.out.printf("%n%s contains %s%n", k, v));

Result is OK in the console :

0 contains [Person [id=0, firstName=fn0, lastName=ln0, alea=0], Person [id=2, firstName=fn2, lastName=ln2, alea=0], Person [id=4, firstName=fn4, lastName=ln4, alea=0], Person [id=6, firstName=fn6, lastName=ln6, alea=0], Person [id=8, firstName=fn8, lastName=ln8, alea=0]]

1 contains [Person [id=1, firstName=fn1, lastName=ln1, alea=1], Person [id=3, firstName=fn3, lastName=ln3, alea=1], Person [id=5, firstName=fn5, lastName=ln5, alea=1], Person [id=7, firstName=fn7, lastName=ln7, alea=1], Person [id=9, firstName=fn9, lastName=ln9, alea=1]]

Now I would like to add an new grouping level. I've chosen BirthDate's year, that is another property of a Person object.

Basically, I tried somthing like this :

Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.toMap(Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));

Casting doesn't help :

@SuppressWarnings("unchecked")
        Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.toMap((Function<Integer, List<Person>>) Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));

I also tried with Collectors.mapping instead of Collectors.toMap :

Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson = persons.stream()
                .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                        Collectors.mapping((Function<Integer, List<Person>>) Collectors.groupingBy(Person::getAlea,
                        Collectors.mapping(p -> p, Collectors.toList())))));

Each time the compiler returns error because of uncompliant Function type.

The only way I've found to add the new grouping level was with old Java code and external loop adding and grouping datas in a Map of Map.

It's desapointing to embed FP in old Java!!

Have someone any idea of doing all of that with pure FP ?

After @eran answer (that works great), here's what I've done and its result :

Map<Integer, Map<Integer, List<Person>>> mapByYearThenAleaPerson = persons.stream().collect(
                Collectors.groupingBy(p -> p.getBirthDate().getYear() + 1900, Collectors.groupingBy(Person::getAlea)));

{2018={0=[Person [id=0, firstName=fn0, lastName=ln0, alea=0], Person [id=2, firstName=fn2, lastName=ln2, alea=0], Person [id=4, firstName=fn4, lastName=ln4, alea=0]], 1=[Person [id=1, firstName=fn1, lastName=ln1, alea=1], Person [id=3, firstName=fn3, lastName=ln3, alea=1]]}, 2019={0=[Person [id=6, firstName=fn6, lastName=ln6, alea=0], Person [id=8, firstName=fn8, lastName=ln8, alea=0]], 1=[Person [id=5, firstName=fn5, lastName=ln5, alea=1], Person [id=7, firstName=fn7, lastName=ln7, alea=1], Person [id=9, firstName=fn9, lastName=ln9, alea=1]]}}

What is really surprenising, is the simplicity of nested groupingBy statement compared to the way of builging the first Map itself.

Why don't we need to specify mapping and Collectors.toList() anymore ?

Body:
Use nested groupingBy:

Map<Integer,Map<Integer,List<Person>>> mapByYearThenAleaPerson =
    persons.stream()
           .collect(Collectors.groupingBy(p -> p.getBirthDate().getYear(),
                                          Collectors.groupingBy(Person::getAlea)));


问:
Leap year calculation
In order to find leap years, why must the year be indivisible by 100 and divisible by 400?

I understand why it must be divisible by 4. Please explain the algorithm.

答:
C# implementation</p>

```<code>public bool LeapYear()
{
     int year = 2016;

     return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
}
</code>```

OwnerDisplayName: Ram

Title: Leap year calculation

Body:
C# implementation

public bool LeapYear()
{
     int year = 2016;

     return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
}


问:
Object is undefined on event listener callback passed as a method in Angular 2
I am new to angular 2 and typescript, in my project I have created tables dynamically and appended to board DIV. I have given addEventLister to the table and passing callback as a method. But whenever an event is triggered the, but the object(this.diamondSet in below code) is giving undefined. I couldn't find what I did wrong

Please help me to find the error, Thanks in advance,

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  board_row: number = 8;
  board_col: number = 8;
  cellNum: number = 0;
  cellCordinates: Object = {};
  diamond_count: number = 8;
  diamondSet: Object = {};
  winCount: number = 0;

  ngOnInit() {
   this.randomGenerators();
    this.initializeBoard();
    }

    initializeBoard() {
    let table = document.createElement("table");
    table.id = "diamond_container";
    for (let i = 0; i < this.board_row; i++) {
        let tr = document.createElement('tr');
        for (let j = 0; j < this.board_col; j++) {
            let td = document.createElement('td');
            this.cellCordinates[this.cellNum] = {
                x: i,
                y: j
            };
            td.className = "cell unknown";
            td.id = `${this.cellNum}`;
            this.cellNum++;
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    document.getElementById("board").appendChild(table);
    document.getElementById("diamond_container").addEventListener("click", this.clickHandler);
}
randomGenerators() {
    while (Object.keys(this.diamondSet).length < this.diamond_count) {
        let randomnumber = Math.ceil(Math.random() * 63)
        this.diamondSet[randomnumber] = randomnumber;
    }
}
clickHandler(e) {
 console.log("handru");
 if (Object.keys(this.diamondSet).length) {
        if (e.target.nodeName == 'TD') {
            this.winCount++;
            console.log("before")
            if (this.diamondSet[e.target.id]) {
                e.target.className = "cell diamond disabled";
                delete this.diamondSet[e.target.id];

            } else {
                var slope = this.hint(e.target.id);
                $('td').removeClass('arrow');
                e.target.className = "cell arrow disabled";
                e.target.style["boxShadow"] = 'none';
                e.target.style["transform"] = "rotate(" + slope + "deg)";
            }
        }
    }
}

minDistance(clicked_id) {
    var distanceMap = {};
    Object.keys(this.diamondSet).map((id) => {
        distanceMap[id] = Math.abs(this.cellCordinates[clicked_id].x - this.cellCordinates[id].x) + Math.abs(this.cellCordinates[clicked_id].y - this.cellCordinates[id].y);
    });
    return Object.keys(distanceMap).sort(function(a, b) {
        return distanceMap[a] - distanceMap[b]
    })[0];
}

hint(clicked_id) {
    let nearestDiamondId = this.minDistance(clicked_id);
    return (Math.atan2((this.cellCordinates[nearestDiamondId].x - this.cellCordinates[clicked_id].x), (this.cellCordinates[nearestDiamondId].y - this.cellCordinates[clicked_id].y))) * 180 / Math.PI;
}
}```
</div>
</div>
</p>

<p><strong>app.component.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" id="container">
  <center>
    <h1>
      Diamond Sweeper
    </h1>
  </center>
  <div class="row">
    <div class="col-xs-12" id="board">
    </div>
  </div>
</div></code>```

答:
Another way is to bind the non-arrow function with your component.

```<code>clickHandlerUnbinded(e)  {
   ... // your function code here
}

clickHandler = this.clickHandlerUnbinded.bind(this); // this -> is your component

document.getElementById("diamond_container").addEventListener("click", this.clickHandler);
</code>```

Now you got a clickHandler with its this context bound to your component.

Using arrow function is more elegant obviously.

Body:
I am new to angular 2 and typescript, in my project I have created tables dynamically and appended to board DIV. I have given addEventLister to the table and passing callback as a method. But whenever an event is triggered the, but the object(this.diamondSet in below code) is giving undefined. I couldn't find what I did wrong

Please help me to find the error, Thanks in advance,

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  board_row: number = 8;
  board_col: number = 8;
  cellNum: number = 0;
  cellCordinates: Object = {};
  diamond_count: number = 8;
  diamondSet: Object = {};
  winCount: number = 0;

  ngOnInit() {
   this.randomGenerators();
    this.initializeBoard();
    }

    initializeBoard() {
    let table = document.createElement("table");
    table.id = "diamond_container";
    for (let i = 0; i < this.board_row; i++) {
        let tr = document.createElement('tr');
        for (let j = 0; j < this.board_col; j++) {
            let td = document.createElement('td');
            this.cellCordinates[this.cellNum] = {
                x: i,
                y: j
            };
            td.className = "cell unknown";
            td.id = `${this.cellNum}`;
            this.cellNum++;
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    document.getElementById("board").appendChild(table);
    document.getElementById("diamond_container").addEventListener("click", this.clickHandler);
}
randomGenerators() {
    while (Object.keys(this.diamondSet).length < this.diamond_count) {
        let randomnumber = Math.ceil(Math.random() * 63)
        this.diamondSet[randomnumber] = randomnumber;
    }
}
clickHandler(e) {
 console.log("handru");
 if (Object.keys(this.diamondSet).length) {
        if (e.target.nodeName == 'TD') {
            this.winCount++;
            console.log("before")
            if (this.diamondSet[e.target.id]) {
                e.target.className = "cell diamond disabled";
                delete this.diamondSet[e.target.id];

            } else {
                var slope = this.hint(e.target.id);
                $('td').removeClass('arrow');
                e.target.className = "cell arrow disabled";
                e.target.style["boxShadow"] = 'none';
                e.target.style["transform"] = "rotate(" + slope + "deg)";
            }
        }
    }
}

minDistance(clicked_id) {
    var distanceMap = {};
    Object.keys(this.diamondSet).map((id) => {
        distanceMap[id] = Math.abs(this.cellCordinates[clicked_id].x - this.cellCordinates[id].x) + Math.abs(this.cellCordinates[clicked_id].y - this.cellCordinates[id].y);
    });
    return Object.keys(distanceMap).sort(function(a, b) {
        return distanceMap[a] - distanceMap[b]
    })[0];
}

hint(clicked_id) {
    let nearestDiamondId = this.minDistance(clicked_id);
    return (Math.atan2((this.cellCordinates[nearestDiamondId].x - this.cellCordinates[clicked_id].x), (this.cellCordinates[nearestDiamondId].y - this.cellCordinates[clicked_id].y))) * 180 / Math.PI;
}
}

app.component.html

      Diamond Sweeper

Body:
Another way is to bind the non-arrow function with your component.

clickHandlerUnbinded(e)  {
   ... // your function code here
}

clickHandler = this.clickHandlerUnbinded.bind(this); // this -> is your component

document.getElementById("diamond_container").addEventListener("click", this.clickHandler);

Now you got a clickHandler with its this context bound to your component.

Using arrow function is more elegant obviously.


问:
Launch firefox with selenium including firefox add-ons
I am using Python 3.x and Selenium, all updated.  Trying to launch firefox with Selenium with my add-ons intact.  Even relevant answer on Stackoverflow I have tried, nothing works.  Any Selenium wizards out there?

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
options = Options
fp = webdriver.FirefoxProfile('<path to my one firefox profile which     includes add-ons at launch')
driver = webdriver.Firefox(executable_path='<path to geckodriver>', firefox_profile=fp)
</code>```

I am expecting Selenium to launch Firefox with my add-ons intact.  Specifically, I want the random user agent switcher add on to function as normal, i.e. change user agent periodically.

答:
It changes your layout a bit. But after struggling with Selenium for quite a while, the following implementation of WebDriver really helped me with setting attributes like options and profile.

```<code>from selenium import webdriver

# tag options field
options = webdriver.FirefoxOptions()
# disable push/popups
options.set_preference("dom.push.enabled", False)

# tag profile option
profile = webdriver.FirefoxProfile()
# what's the profile then (normally imported from separate infos.py)
user_agent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) \
              AppleWebKit/528.18 (KHTML,like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
# adjust profile to reflect user_agent profile
profile.set_preference("general.useragent.override", user_agent)

# set driver with options
driver = webdriver.Firefox(options=options, firefox_profile=profile)
</code>```

Glad to read you were able to find an answer. Hope this was helpful or/and can be of use in the future. Have a great day!

Body:
I am using Python 3.x and Selenium, all updated.  Trying to launch firefox with Selenium with my add-ons intact.  Even relevant answer on Stackoverflow I have tried, nothing works.  Any Selenium wizards out there?

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
options = Options
fp = webdriver.FirefoxProfile('<path to my one firefox profile which     includes add-ons at launch')
driver = webdriver.Firefox(executable_path='<path to geckodriver>', firefox_profile=fp)

I am expecting Selenium to launch Firefox with my add-ons intact.  Specifically, I want the random user agent switcher add on to function as normal, i.e. change user agent periodically.

Body:
It changes your layout a bit. But after struggling with Selenium for quite a while, the following implementation of WebDriver really helped me with setting attributes like options and profile.

from selenium import webdriver

# tag options field
options = webdriver.FirefoxOptions()
# disable push/popups
options.set_preference("dom.push.enabled", False)

# tag profile option
profile = webdriver.FirefoxProfile()
# what's the profile then (normally imported from separate infos.py)
user_agent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) \
              AppleWebKit/528.18 (KHTML,like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
# adjust profile to reflect user_agent profile
profile.set_preference("general.useragent.override", user_agent)

# set driver with options
driver = webdriver.Firefox(options=options, firefox_profile=profile)

Glad to read you were able to find an answer. Hope this was helpful or/and can be of use in the future. Have a great day!


问:
Set a variable to what json_encode() outputs in PHP
json_encode() returns a string...

So shouldn't the following code work?

```<code>class TestClass {
    private $test = json_encode("test");
}
</code>```

PHP outputs

```<code>Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/testuser/public_html/test.php on line 10
</code>```

答:
In PHP you cannot assign an instance variable to the result of a function in the declaration. You should assign it in the constructor. Eg.</p>

```<code>class TestClass {
    private $test;
    public function __construct() {
        $this->test = json_encode("test");
    }
}
</code>```

Body:
json_encode() returns a string...

So shouldn't the following code work?

class TestClass {
    private $test = json_encode("test");
}

PHP outputs

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/testuser/public_html/test.php on line 10

Body:
In PHP you cannot assign an instance variable to the result of a function in the declaration. You should assign it in the constructor. Eg.

class TestClass {
    private $test;
    public function __construct() {
        $this->test = json_encode("test");
    }
}


问:
Why does position of code affect performance in C++?
I am running a test performance, and found out that changing the order of the code makes it faster without compromising the result.

Performance is measured by time execution using chrono library.

```<code>vector< vector<float> > U(matrix_size, vector<float>(matrix_size,14));
vector< vector<float> > L(matrix_size, vector<float>(matrix_size,12));
vector< vector<float> > matrix_positive_definite(matrix_size, vector<float>(matrix_size,23));

for (i = 0; i < matrix_size; ++i) {
   for(j= 0; j < matrix_size; ++j){
//Part II : ________________________________________
    float sum2=0;
    for(k= 0; k <= (i-1); ++k){
      float sum2_temp=L[i][k]*U[k][j];
      sum2+=sum2_temp;
    }
//Part I : _____________________________________________
    float sum1=0;
    for(k= 0; k <= (j-1); ++k){
      float sum1_temp=L[i][k]*U[k][j];
      sum1+=sum1_temp;
    }
//__________________________________________
    if(i>j){
      L[i][j]=(matrix_positive_definite[i][j]-sum1)/U[j][j];
    }
    else{
       U[i][j]=matrix_positive_definite[i][j]-sum2;
    }
   }
}
</code>```

I compile with g++ -O3 (GCC 7.4.0 in Intel i5/Win10).
I changed the order of Part I & Part II and got faster result if Part II executed before Part I. What's going on?

This is the link to the whole program.

答:
Running perf stat -ddd while playing around with the provided program shows that the major difference between the two versions stands mainly in the prefetch.

```<code>part II -> part I   and   part I -> part II (original program)
   73,069,502      L1-dcache-prefetch-misses

part II -> part I   and   part II -> part I (only the efficient version)
   31,719,117      L1-dcache-prefetch-misses

part I -> part II   and   part I -> part II (only the less efficient version)
  114,520,949      L1-dcache-prefetch-misses
</code>```

nb: according to the compiler explorer, part II -> part I is very similar to part I -> part II.

I guess that, on the first iterations over i, part II does almost nothing, but iterations over j make part I access U[k][j] according to a pattern that will ease prefetch for the next iterations over i.

Body:
I am running a test performance, and found out that changing the order of the code makes it faster without compromising the result.

Performance is measured by time execution using chrono library.

vector< vector<float> > U(matrix_size, vector<float>(matrix_size,14));
vector< vector<float> > L(matrix_size, vector<float>(matrix_size,12));
vector< vector<float> > matrix_positive_definite(matrix_size, vector<float>(matrix_size,23));

for (i = 0; i < matrix_size; ++i) {
   for(j= 0; j < matrix_size; ++j){
//Part II : ________________________________________
    float sum2=0;
    for(k= 0; k <= (i-1); ++k){
      float sum2_temp=L[i][k]*U[k][j];
      sum2+=sum2_temp;
    }
//Part I : _____________________________________________
    float sum1=0;
    for(k= 0; k <= (j-1); ++k){
      float sum1_temp=L[i][k]*U[k][j];
      sum1+=sum1_temp;
    }
//__________________________________________
    if(i>j){
      L[i][j]=(matrix_positive_definite[i][j]-sum1)/U[j][j];
    }
    else{
       U[i][j]=matrix_positive_definite[i][j]-sum2;
    }
   }
}

I compile with g++ -O3 (GCC 7.4.0 in Intel i5/Win10).
I changed the order of Part I & Part II and got faster result if Part II executed before Part I. What's going on?

This is the link to the whole program.

Body:
Running perf stat -ddd while playing around with the provided program shows that the major difference between the two versions stands mainly in the prefetch.

part II -> part I   and   part I -> part II (original program)
   73,069,502      L1-dcache-prefetch-misses

part II -> part I   and   part II -> part I (only the efficient version)
   31,719,117      L1-dcache-prefetch-misses

part I -> part II   and   part I -> part II (only the less efficient version)
  114,520,949      L1-dcache-prefetch-misses

nb: according to the compiler explorer, part II -> part I is very similar to part I -> part II.

I guess that, on the first iterations over i, part II does almost nothing, but iterations over j make part I access U[k][j] according to a pattern that will ease prefetch for the next iterations over i.


问:
Django allow only one user session in total
I currently try to implement a policy to my application that only one user session at a time is allowed, if a user trys to log-in from another device the old sessions gets killed.

But for some resone i get the following error and i can't find the mistake myself :( :

RelatedObjectDoesNotExist at / User has no logged_in_user.

My project contains two apps, the actually app and a "accounts" app that contains all informations shown here.

signals.py

```<code># Signals that fires when a user logs in and logs out

from django.contrib.auth import user_logged_in, user_logged_out
from django.dispatch import receiver
from .models import LoggedInUser

@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
    LoggedInUser.objects.get_or_create(user=kwargs.get('user'))

@receiver(user_logged_out)
def on_user_logged_out(sender, **kwargs):
    LoggedInUser.objects.filter(user=kwargs.get('user')).delete()
</code>```

models.py

```<code># Model to store the list of logged in users
class LoggedInUser(models.Model):
    user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.CASCADE)
    session_key = models.CharField(max_length=32, null=True, blank=True)

    def __str__(self):
        return self.user
</code>```

my User Model is at the same at the same location as this sippet

middleware.py

```<code>#Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            stored_session_key = request.user.logged_in_user.session_key

            # if there is a stored_session_key in the database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            if stored_session_key and stored_session_key != request.session.session_key:
                Session.objects.get(session_key=stored_session_key).delete()

            request.user.logged_in_user.session_key = request.session.session_key
            request.user.logged_in_user.save()

        response = self.get_response(request)

        # This is where you add any extra code to be executed for each request/response after
        # the view is called.

        return response
</code>```

UPDATE:

my middleware.py file now looks like:

```<code># Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            session_key = request.session.session_key

            # if there is a stored_session_key  in our database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            try:
                logged_in_user = request.user.logged_in_user
                stored_session_key = logged_in_user.session_key
                # stored_session_key exists so delete it if it's different
                if stored_session_key != session_key:
                    Session.objects.filter(session_key=stored_session_key).delete()
                logged_in_user.session_key = session_key
                logged_in_user.save()
            except LoggedInUser.DoesNotExist:
                LoggedInUser.objects.create(user=request.user, session_key=session_key)

        response = self.get_response(request)

        return response
</code>```

which seems to work fine but if i log in with the same user from two different browsers, I'm still able to do this and i still get two different sessions keys and the session stays open.

If i check at the database while logged in from two diffrent computers to access the application as the same user, the saved session key at the LoggedInUser table simple changes but the application does not act like the key has been revoked from at least the oldest session!?

答:
Actually the error occurs here,

```<code>stored_session_key = request.user.logged_in_user.session_key
</code>```

ie. the related logged_in_user (LoggedInUser object) doesn't exists for the logged in user. So you have to create a a new one.

```<code>session_key = request.session.session_key

try:
    logged_in_user = request.user.logged_in_user
    stored_session_key = logged_in_user.session_key
    # stored_session_key exists so delete it if it's different
    if stored_session_key != session_key:
        Session.objects.filter(session_key=stored_session_key).delete()
    logged_in_user.session_key = session_key
    logged_in_user.save()
except LoggedInUser.DoesNotExist:
    LoggedInUser.objects.create(user=request.user, session_key=session_key)
</code>```

Body:
I currently try to implement a policy to my application that only one user session at a time is allowed, if a user trys to log-in from another device the old sessions gets killed.

But for some resone i get the following error and i can't find the mistake myself :( :

RelatedObjectDoesNotExist at / User has no logged_in_user.

My project contains two apps, the actually app and a "accounts" app that contains all informations shown here.

signals.py

# Signals that fires when a user logs in and logs out

from django.contrib.auth import user_logged_in, user_logged_out
from django.dispatch import receiver
from .models import LoggedInUser

@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
    LoggedInUser.objects.get_or_create(user=kwargs.get('user'))

@receiver(user_logged_out)
def on_user_logged_out(sender, **kwargs):
    LoggedInUser.objects.filter(user=kwargs.get('user')).delete()

models.py

# Model to store the list of logged in users
class LoggedInUser(models.Model):
    user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.CASCADE)
    session_key = models.CharField(max_length=32, null=True, blank=True)

    def __str__(self):
        return self.user

my User Model is at the same at the same location as this sippet

middleware.py

#Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            stored_session_key = request.user.logged_in_user.session_key

            # if there is a stored_session_key in the database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            if stored_session_key and stored_session_key != request.session.session_key:
                Session.objects.get(session_key=stored_session_key).delete()

            request.user.logged_in_user.session_key = request.session.session_key
            request.user.logged_in_user.save()

        response = self.get_response(request)

        # This is where you add any extra code to be executed for each request/response after
        # the view is called.

        return response

UPDATE:

my middleware.py file now looks like:

# Session model stores the session data
from django.contrib.sessions.models import Session
from .models import LoggedInUser

class OneSessionPerUserMiddleware:
    # Called only once when the web server starts
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.user.is_authenticated:
            session_key = request.session.session_key

            # if there is a stored_session_key  in our database and it is
            # different from the current session, delete the stored_session_key
            # session_key with from the Session table
            try:
                logged_in_user = request.user.logged_in_user
                stored_session_key = logged_in_user.session_key
                # stored_session_key exists so delete it if it's different
                if stored_session_key != session_key:
                    Session.objects.filter(session_key=stored_session_key).delete()
                logged_in_user.session_key = session_key
                logged_in_user.save()
            except LoggedInUser.DoesNotExist:
                LoggedInUser.objects.create(user=request.user, session_key=session_key)

        response = self.get_response(request)

        return response

which seems to work fine but if i log in with the same user from two different browsers, I'm still able to do this and i still get two different sessions keys and the session stays open.

If i check at the database while logged in from two diffrent computers to access the application as the same user, the saved session key at the LoggedInUser table simple changes but the application does not act like the key has been revoked from at least the oldest session!?

Body:
Actually the error occurs here,

stored_session_key = request.user.logged_in_user.session_key

ie. the related logged_in_user (LoggedInUser object) doesn't exists for the logged in user. So you have to create a a new one.

session_key = request.session.session_key

try:
    logged_in_user = request.user.logged_in_user
    stored_session_key = logged_in_user.session_key
    # stored_session_key exists so delete it if it's different
    if stored_session_key != session_key:
        Session.objects.filter(session_key=stored_session_key).delete()
    logged_in_user.session_key = session_key
    logged_in_user.save()
except LoggedInUser.DoesNotExist:
    LoggedInUser.objects.create(user=request.user, session_key=session_key)


问:
PowerShell XML Node Value from another file IF other Nodes -match
I have a script that's generating a xml file based on a .csv that's going to act as payload through a webservice (RESTapi).

The payload requires me to generate some GUIDs which is fine as long as I'm generating new ones. In order to successfully update data through the API i need to specify a GUID that already exist on each user in the receiving system.

So the first thing I do is a GET request to the system to export all users.
I then check users in my generated .xml file against the .xml from the GET request.

If users match, I want to extract the GUID that's existing in the export to my generated output. And this is where I'm stuck.

For example I've would match:

```<code><CVs>
  <CV>
    <GUID></GUID>
    <EMPLOYEE>
        <IDENTIFIER>aa</IDENTIFIER>
    </EMPLOYEE>
  </CV>
</CVs>
</code>```

Against:

```<code>    <CV>
        <GUID>800b96cd-56e9-4587-a9db-41c2a4095d04</GUID>
        <EMPLOYEE>
           <USERNAME>aa</USERNAME>
        </EMPLOYEE>
    </CV>
    <CV>
        <GUID>a07ac517-c7d5-4766-89b6-9101260f6f53</GUID>
        <EMPLOYEE>
           <USERNAME>bb</USERNAME>
        </EMPLOYEE>
    </CV>
    <CV>
        <GUID>84d82720-3e06-4802-9206-69f25b2aa46d</GUID>
        <EMPLOYEE>
           <USERNAME>cc</USERNAME>
        </EMPLOYEE>
    </CV>
  </CVs>
</code>```

And since "aa" is a match, I would like this output:

```<code><CVs>
  <CV>
    <GUID>800b96cd-56e9-4587-a9db-41c2a4095d04</GUID>
    <EMPLOYEE>
        <IDENTIFIER>aa</IDENTIFIER>
    </EMPLOYEE>
  </CV>
</CVs>
</code>```

This is my working code for producing everything, except getting that GUID from another .xml if two nodes are matching.

```<code>$docTemplate = @'
  <CV>
    <GUID></GUID>
    <EMPLOYEE>
        <IDENTIFIER>$($cert.Identifier)</IDENTIFIER>
    </EMPLOYEE>
    <PAGE id="8">
  $($certs -join "`n")
    </PAGE>
  </CV>
'@

# Per-certificate template.
$entryTemplate = @'
    <RECORD>
      <GUID></GUID>
      <FIELD id="21">
        <DATA>
          <GUID></GUID>
          <VALUE>$($cert.Certificate)</VALUE>
        </DATA>
      </FIELD>
      <FIELD id="36">
        <DATA><VALUE>$($cert.From)</VALUE></DATA>
      </FIELD>
      <FIELD id="22">$($cert.ExpireDate)
        <DATA><VALUE>$($cert.to)</VALUE></DATA>
      </FIELD>
    </RECORD>
'@

$cvData = Import-Csv demo.csv -Delimiter ';' | Group-Object Identifier -ov grp | ForEach-Object {

  $certs = foreach ($cert in $_.Group) {
    $ExecutionContext.InvokeCommand.ExpandString($entryTemplate)
  }
  $ExecutionContext.InvokeCommand.ExpandString($docTemplate)
}

$rootTemplate = @'
<CVs>
$($cvData -join "`n")
</CVs>
'@
$output = $ExecutionContext.InvokeCommand.ExpandString($rootTemplate) | Set-Content -LiteralPath 'cvoutput.xml'

#Add GUID
$xmlFile = '.\cvoutput.xml'
[xml]$xmlDoc = Get-Content $xmlFile

#Add Record GUID
foreach ($element in $xmlDoc.CVs.CV.PAGE.RECORD)
{
    [string]$element.GUID = New-Guid
}

#Check if Node exists (certifications require a GUID in the Cert Data Node)
foreach ($element in $xmlDoc.CVs.CV.PAGE.RECORD.FIELD | Where-Object  {$_.name -match "Certifications"}) {
  [string]$element.DATA.GUID = New-Guid
}

$xmlDoc.Save('cv-data.xml')

</code>```

答:
Just like @sage-pourpre suggests the:

$Nodes = $XML.SelectNodes('//CV') | Select @{'Name' = 'EmployeeID' ; 'Expression' = { $_.EMPLOYEE.USERNAME } }, GUID

With:

foreach ($emp in $xmlDoc.CVs.CV ) {
  $Guid = $Nodes | Where EmployeeID -eq ($emp.EMPLOYEE.IDENTIFIER) | Select -First 1
  [string]$emp.GUID = $Guid.GUID
}

Solves the problem.

Thank you!

Body:
I have a script that's generating a xml file based on a .csv that's going to act as payload through a webservice (RESTapi).

The payload requires me to generate some GUIDs which is fine as long as I'm generating new ones. In order to successfully update data through the API i need to specify a GUID that already exist on each user in the receiving system.

So the first thing I do is a GET request to the system to export all users.
I then check users in my generated .xml file against the .xml from the GET request.

If users match, I want to extract the GUID that's existing in the export to my generated output. And this is where I'm stuck.

For example I've would match:

<CVs>
  <CV>
    <GUID></GUID>
    <EMPLOYEE>
        <IDENTIFIER>aa</IDENTIFIER>
    </EMPLOYEE>
  </CV>
</CVs>

Against:

    <CV>
        <GUID>800b96cd-56e9-4587-a9db-41c2a4095d04</GUID>
        <EMPLOYEE>
           <USERNAME>aa</USERNAME>
        </EMPLOYEE>
    </CV>
    <CV>
        <GUID>a07ac517-c7d5-4766-89b6-9101260f6f53</GUID>
        <EMPLOYEE>
           <USERNAME>bb</USERNAME>
        </EMPLOYEE>
    </CV>
    <CV>
        <GUID>84d82720-3e06-4802-9206-69f25b2aa46d</GUID>
        <EMPLOYEE>
           <USERNAME>cc</USERNAME>
        </EMPLOYEE>
    </CV>
  </CVs>

And since "aa" is a match, I would like this output:

<CVs>
  <CV>
    <GUID>800b96cd-56e9-4587-a9db-41c2a4095d04</GUID>
    <EMPLOYEE>
        <IDENTIFIER>aa</IDENTIFIER>
    </EMPLOYEE>
  </CV>
</CVs>

This is my working code for producing everything, except getting that GUID from another .xml if two nodes are matching.

$docTemplate = @'
  <CV>
    <GUID></GUID>
    <EMPLOYEE>
        <IDENTIFIER>$($cert.Identifier)</IDENTIFIER>
    </EMPLOYEE>
    <PAGE id="8">
  $($certs -join "`n")
    </PAGE>
  </CV>
'@

# Per-certificate template.
$entryTemplate = @'
    <RECORD>
      <GUID></GUID>
      <FIELD id="21">
        <DATA>
          <GUID></GUID>
          <VALUE>$($cert.Certificate)</VALUE>
        </DATA>
      </FIELD>
      <FIELD id="36">
        <DATA><VALUE>$($cert.From)</VALUE></DATA>
      </FIELD>
      <FIELD id="22">$($cert.ExpireDate)
        <DATA><VALUE>$($cert.to)</VALUE></DATA>
      </FIELD>
    </RECORD>
'@

$cvData = Import-Csv demo.csv -Delimiter ';' | Group-Object Identifier -ov grp | ForEach-Object {

  $certs = foreach ($cert in $_.Group) {
    $ExecutionContext.InvokeCommand.ExpandString($entryTemplate)
  }
  $ExecutionContext.InvokeCommand.ExpandString($docTemplate)
}

$rootTemplate = @'
<CVs>
$($cvData -join "`n")
</CVs>
'@
$output = $ExecutionContext.InvokeCommand.ExpandString($rootTemplate) | Set-Content -LiteralPath 'cvoutput.xml'

#Add GUID
$xmlFile = '.\cvoutput.xml'
[xml]$xmlDoc = Get-Content $xmlFile

#Add Record GUID
foreach ($element in $xmlDoc.CVs.CV.PAGE.RECORD)
{
    [string]$element.GUID = New-Guid
}

#Check if Node exists (certifications require a GUID in the Cert Data Node)
foreach ($element in $xmlDoc.CVs.CV.PAGE.RECORD.FIELD | Where-Object  {$_.name -match "Certifications"}) {
  [string]$element.DATA.GUID = New-Guid
}

$xmlDoc.Save('cv-data.xml')


问:
C# reflection datatype
I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the aspx-page.</p>

```<code>using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...
if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Label).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Button).Text = "Key not found: " + control.ID;
    }
}
</code>```

答:
You can significantly simplify your code by using dynamic.

Since ID is defined in the base class, but Text is defined in all of the concrete classes but not in the base.

```<code>dynamic myControl = control;
try
{
    myControl.Text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    myControl.Text = "Key not found: " + control.ID;
}
</code>```

You can add a guard clause for the types at the beginning:

```<code>if (!(control is RadioButton || control is Label || control is Button)) return;
</code>```

Title: C# reflection datatype

Body:
I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the aspx-page.

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...
if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Label).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as Button).Text = "Key not found: " + control.ID;
    }
}

Body:
You can significantly simplify your code by using dynamic.

Since ID is defined in the base class, but Text is defined in all of the concrete classes but not in the base.

dynamic myControl = control;
try
{
    myControl.Text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (Exception)
{
    myControl.Text = "Key not found: " + control.ID;
}

You can add a guard clause for the types at the beginning:

if (!(control is RadioButton || control is Label || control is Button)) return;


问:
ERROR TypeError: Cannot read property 'list' of undefined
Getting the error as mentioned when I am trying to get the response from API call and display the information in the response object in the template.

ERROR TypeError: Cannot read property 'list' of undefined.

In service.ts, I am making a server call. I am using OpenWeatherMap API.

```<code>getDetails(cityName, countryCd): Observable<any>{
  return this.httpclient.get(`${this.url}${cityName},${countryCd}&APPID=${this.apiKey}`);
}
</code>```

Object format returned by the API:

```<code>{"city":{"id":1851632,"name":"Shuzenji",
 "coord":{"lon":138.933334,"lat":34.966671},
 "country":"JP",
 "cod":"200",
 "message":0.0045,
 "cnt":38,
 "list":[{
    "dt":1406106000,
    "main":{
        "temp":298.77,
        "temp_min":298.77,
        "temp_max":298.774,
        "pressure":1005.93,
        "sea_level":1018.18,
        "grnd_level":1005.93,
        "humidity":87,
        "temp_kf":0.26},
    "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
    "clouds":{"all":88},
    "wind":{"speed":5.71,"deg":229.501},
    "sys":{"pod":"d"},
    "dt_txt":"2014-07-23 09:00:00"}
    ]}
</code>```

In home.component.ts, I am subscribing to the service API call. I am getting the reposnse which is of type 'object'.

I have an array of objects called cities. I am loading the response object from the server as one of the property in each object of the array cities.

```<code>this.cities = this.cityService.getCities().slice();
this.cities.forEach(element => {
  this.weatherService.getDetails(element.cityName, element.countryCd).subscribe(response => {
    element['cityWeather'] = response;});
});
</code>```

In home.component.html, I am iterating this cities array and the using the response data from the API. The data is displayed properly without any issues.
But in the console I am seeing an error for every iteration of cities array -

ERROR TypeError: Cannot read property 'list' of undefined.

```<code><div class="col-md-4" *ngFor="let city of cities; let i = index">

                <span>{{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃</span>

                <span>{{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h</span>

</div>
</code>```

I am relatively new to Angular, need to know what is this error about and how this can be resolved.

答:
You can either use The Angular

safe navigation operator (?.)

```<code>city.cityWeather?.list[0]?.main.temp
city.cityWeather?.list[0]?.wind.speed
</code>```

or you can try using Angular async pipe
https://angular.io/api/common/AsyncPipe

Body:
Getting the error as mentioned when I am trying to get the response from API call and display the information in the response object in the template.

ERROR TypeError: Cannot read property 'list' of undefined.

In service.ts, I am making a server call. I am using OpenWeatherMap API.

getDetails(cityName, countryCd): Observable<any>{
  return this.httpclient.get(`${this.url}${cityName},${countryCd}&APPID=${this.apiKey}`);
}

Object format returned by the API:

{"city":{"id":1851632,"name":"Shuzenji",
 "coord":{"lon":138.933334,"lat":34.966671},
 "country":"JP",
 "cod":"200",
 "message":0.0045,
 "cnt":38,
 "list":[{
    "dt":1406106000,
    "main":{
        "temp":298.77,
        "temp_min":298.77,
        "temp_max":298.774,
        "pressure":1005.93,
        "sea_level":1018.18,
        "grnd_level":1005.93,
        "humidity":87,
        "temp_kf":0.26},
    "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
    "clouds":{"all":88},
    "wind":{"speed":5.71,"deg":229.501},
    "sys":{"pod":"d"},
    "dt_txt":"2014-07-23 09:00:00"}
    ]}

In home.component.ts, I am subscribing to the service API call. I am getting the reposnse which is of type 'object'.

I have an array of objects called cities. I am loading the response object from the server as one of the property in each object of the array cities.

this.cities = this.cityService.getCities().slice();
this.cities.forEach(element => {
  this.weatherService.getDetails(element.cityName, element.countryCd).subscribe(response => {
    element['cityWeather'] = response;});
});

In home.component.html, I am iterating this cities array and the using the response data from the API. The data is displayed properly without any issues.
But in the console I am seeing an error for every iteration of cities array -

ERROR TypeError: Cannot read property 'list' of undefined.

                {{city.cityWeather.list[0].main.temp | kelvinToCelcius}} ℃

                {{city.cityWeather.list[0].wind.speed | mtrPersecToKmPerhr}} km/h

I am relatively new to Angular, need to know what is this error about and how this can be resolved.

Body:
You can either use The Angular

safe navigation operator (?.)

city.cityWeather?.list[0]?.main.temp
city.cityWeather?.list[0]?.wind.speed

or you can try using Angular async pipe
https://angular.io/api/common/AsyncPipe


问:
Merging asp.net application with asp.net mvc
What all care I need to take when merging an existing Asp.Net 3.5 application with Asp.Net MVC 1.0 application?</p>

答: There are some blog posts illustrating how to mix ASP.NET MVC with classic WebForms.</p>


问:
SQL Server Error 5120 - failed to attach .mdf file
While attaching my .mdf file on my SQL Server database I am getting below error message:

Msg 5120, Level 16, State 101, Line 1
  Unable to open the physical file
  "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA'
  Operating system error 5: "5(Access denied.)".

I don't have my .ldf file of associated database. How can I attach my .mdf file without .ldf file? I am using SQL Server 2014.

答:
Put your data file into the folder where you made permissions
https://dbamohsin.wordpress.com/2009/06/03/attaching-database-unable-to-open-physical-file-access-is-denied/</p>


问:
How to round (or perhaps cut) of a float based on some conditions
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work </p>

```<code>import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `
</code>```

答:
You would be much better off working with decimal.Decimal and not with the language's native float type, which is prone to accuracy errors to begin with.

I'd also bet that 0.0044859999999999995 btc is in fact given to you as a very big integer of smaller units (not sure about btc, but for eth those units are called wei).

If that is indeed the case, then you should strive to keep it this way, and do all your math using integers only (i.e., not even Decimal, just plain integers and the // operation wherever needed).

If you insist on doing it with non-integer values, then you could modify your code to this:

```<code>from decimal import Decimal
from decimal import getcontext
from decimal import ROUND_DOWN

getcontext().prec = 100
getcontext().rounding = ROUND_DOWN

num = Decimal('0.0044859999999999995')
numCoins = Decimal(int(num*1000000))/1000000
</code>```

Body:
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work

import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `

Body:
You would be much better off working with decimal.Decimal and not with the language's native float type, which is prone to accuracy errors to begin with.

I'd also bet that 0.0044859999999999995 btc is in fact given to you as a very big integer of smaller units (not sure about btc, but for eth those units are called wei).

If that is indeed the case, then you should strive to keep it this way, and do all your math using integers only (i.e., not even Decimal, just plain integers and the // operation wherever needed).

If you insist on doing it with non-integer values, then you could modify your code to this:

from decimal import Decimal
from decimal import getcontext
from decimal import ROUND_DOWN

getcontext().prec = 100
getcontext().rounding = ROUND_DOWN

num = Decimal('0.0044859999999999995')
numCoins = Decimal(int(num*1000000))/1000000