问:
How does Dask decide whether to rerun a task or not
I'm very new to Dask and trying to build a system to execute a computation graph with dependencies. However I'm very confused by the fact that some tasks are being executed twice although they have a static signature. E.g.:

```<code>Python 3.7.5 (default, Nov 12 2019, 11:34:05)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from dask.distributed import Client
>>> client = Client()
>>> def a():
...   print("a")
...
>>> client.gather(client.submit(a))
a
>>> client.gather(client.submit(a))
a
>>> client.submit(a)
<Future: pending, key: a-a5eb50e9015acdf60b1094aa4e467e00>
a
>>> client.submit(a)
<Future: finished, type: builtins.NoneType, key: a-a5eb50e9015acdf60b1094aa4e467e00>
>>> client.gather(client.submit(a))
>>> client.gather(client.submit(a))
>>>
</code>```

So it looks like a() is executed for each call using client.gather(client.submit(a)), but only until I call client.submit(a) on its own, after which the same Future is reused and the function is no longer called. Why is that?

In my computation graph, this will be a problem when two tasks rely on the same task, which should be executed only once. My current approach to handle such dependencies (recursively) is the following:

```<code>from dask.distributed import Client, worker_client

def x(n):
    dgraph = {
        'a': [],
        'b': ['a'],
        'c': ['b', 'a'],
        'd': ['b', 'c']
        }
    print(n)
    with worker_client() as client:
        client.gather(list(client.submit(x, d) for d in dgraph[n]))

if __name__ == '__main__':
    client = Client()
    result = client.submit(x, 'd')
    client.gather(result)
</code>```

Interestingly, python's output when executing that script is not stable:

```<code>$ python test_dask2.py
d
b
c
a
b
a
a
$ python test_dask2.py
d
b
c
a
distributed.scheduler - CRITICAL - Tried writing to closed comm: {'op': 'lost-data', 'key': 'x-bff0c0d6e4239ae9c5beaed070018a1e'}
distributed.scheduler - CRITICAL - Tried writing to closed comm: {'op': 'lost-data', 'key': 'x-59dc11a9fc2db8a0885e47d3e5891304'}
$
</code>```

Is there a way to ensure that a given task, with given inputs, is executed only once even if I submit it several times? If I understand the documentation properly, that should be the normal behaviour. If the call to print is a side-effect that prevents that, why is it not consistent and how can I e.g. prevent a task that generates an output file from being executed twice?

Also, what's the error at the end, which doesn't always occur?

EDIT:

I think I figured out why some of my tasks were being run several times in the second snippet: the hash value that dask's submit is assigning to tasks for identification seems to sometimes vary even when submitting the same task several times (and even before the task completes and goes out of scope). Setting the key parameter to a fixed value (e.g. the task's name) in submit fixes that problem.

答:
The short answer is: dask keeps a result in memory while something needs it. In these cases, "need" can be either a future in your session or another task that depends on the result.

In a line like client.gather(client.submit(a)), the future generated by submit is forgotten immediately after it is gathered. In a line like client.submit(a), the future generated is stored in the "last result" variable _ of the session, and so remains remembered and the cluster does not clear it.

If you wanted more control, you can assign these variables:

```<code>fut = client.submit(a)  # sets func running, keeps hold of the future
fut2 = client.submit(a)  # uses already existing task to get result
client.gather(fut), fut.result() # get results
del fut2, fut  #  "forget" futures, and have cluster release them
</code>```

Remember to use the dashboard to see the current state of the cluster.

Body:
I'm very new to Dask and trying to build a system to execute a computation graph with dependencies. However I'm very confused by the fact that some tasks are being executed twice although they have a static signature. E.g.:

Python 3.7.5 (default, Nov 12 2019, 11:34:05)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from dask.distributed import Client
>>> client = Client()
>>> def a():
...   print("a")
...
>>> client.gather(client.submit(a))
a
>>> client.gather(client.submit(a))
a
>>> client.submit(a)
<Future: pending, key: a-a5eb50e9015acdf60b1094aa4e467e00>
a
>>> client.submit(a)
<Future: finished, type: builtins.NoneType, key: a-a5eb50e9015acdf60b1094aa4e467e00>
>>> client.gather(client.submit(a))
>>> client.gather(client.submit(a))
>>>

So it looks like a() is executed for each call using client.gather(client.submit(a)), but only until I call client.submit(a) on its own, after which the same Future is reused and the function is no longer called. Why is that?

In my computation graph, this will be a problem when two tasks rely on the same task, which should be executed only once. My current approach to handle such dependencies (recursively) is the following:

from dask.distributed import Client, worker_client

def x(n):
    dgraph = {
        'a': [],
        'b': ['a'],
        'c': ['b', 'a'],
        'd': ['b', 'c']
        }
    print(n)
    with worker_client() as client:
        client.gather(list(client.submit(x, d) for d in dgraph[n]))

if __name__ == '__main__':
    client = Client()
    result = client.submit(x, 'd')
    client.gather(result)

Interestingly, python's output when executing that script is not stable:

$ python test_dask2.py
d
b
c
a
b
a
a
$ python test_dask2.py
d
b
c
a
distributed.scheduler - CRITICAL - Tried writing to closed comm: {'op': 'lost-data', 'key': 'x-bff0c0d6e4239ae9c5beaed070018a1e'}
distributed.scheduler - CRITICAL - Tried writing to closed comm: {'op': 'lost-data', 'key': 'x-59dc11a9fc2db8a0885e47d3e5891304'}
$

Is there a way to ensure that a given task, with given inputs, is executed only once even if I submit it several times? If I understand the documentation properly, that should be the normal behaviour. If the call to print is a side-effect that prevents that, why is it not consistent and how can I e.g. prevent a task that generates an output file from being executed twice?

Also, what's the error at the end, which doesn't always occur?

EDIT:

I think I figured out why some of my tasks were being run several times in the second snippet: the hash value that dask's submit is assigning to tasks for identification seems to sometimes vary even when submitting the same task several times (and even before the task completes and goes out of scope). Setting the key parameter to a fixed value (e.g. the task's name) in submit fixes that problem.

Body:
The short answer is: dask keeps a result in memory while something needs it. In these cases, "need" can be either a future in your session or another task that depends on the result.

In a line like client.gather(client.submit(a)), the future generated by submit is forgotten immediately after it is gathered. In a line like client.submit(a), the future generated is stored in the "last result" variable _ of the session, and so remains remembered and the cluster does not clear it.

If you wanted more control, you can assign these variables:

fut = client.submit(a)  # sets func running, keeps hold of the future
fut2 = client.submit(a)  # uses already existing task to get result
client.gather(fut), fut.result() # get results
del fut2, fut  #  "forget" futures, and have cluster release them

Remember to use the dashboard to see the current state of the cluster.


来源: stackexchange

问:
Scala tuple manuplation
I have a tuple like this

```<code>val numPairs = Set((2, "a"), (3, "b"), (20, "c"))
</code>```

I want it's result to look like

```<code>(2, "a"), (3, "b"), (20, "c")
</code>```

So I tried

```<code>println(numPairs.toString().replace("Set", ""))
</code>```

but results are

```<code>(2, a), (3, b), (20, c)
</code>```

And it is missing "" for the string part of the tuple.

Can someone help please

答:
You can manually format the string version of each tuple with some string interpolation, then join them with mkString

```<code>val numPairs = Set((2, "a"), (3, "b"), (20, "c"))

println(numPairs.map(a => s"""(${a._1}, "${a._2}")""").mkString(", "))
</code>```

outputs

```<code>(2, "a"), (3, "b"), (20, "c")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Scala tuple manuplation

Body:
I have a tuple like this

val numPairs = Set((2, "a"), (3, "b"), (20, "c"))

I want it's result to look like

(2, "a"), (3, "b"), (20, "c")

So I tried

println(numPairs.toString().replace("Set", ""))

but results are

(2, a), (3, b), (20, c)

And it is missing "" for the string part of the tuple.

Can someone help please

Body:
You can manually format the string version of each tuple with some string interpolation, then join them with mkString

val numPairs = Set((2, "a"), (3, "b"), (20, "c"))

println(numPairs.map(a => s"""(${a._1}, "${a._2}")""").mkString(", "))

outputs

(2, "a"), (3, "b"), (20, "c")


问:
Loop isn't iterating over last line of list
I have created a template within a playbook which I want to iterate through with a list of hashes. The output of this I want to add to another var to use in a following module.

The template works and the loop looks like it works, but it never adds the last item in the list. I have recreated it in a test play.

```<code>---
- hosts: localhost
  tasks:
  - name: Init
    set_fact:
      foo: []
      fqdn: "test.com"
      template: []

  - name: portlist
    set_fact:
      portlist:
      - { port: 9091, index: 1 }
      - { port: 9092, index: 2 }
      - { port: 9093, index: 3 }
      - { port: 9094, index: 4 }

  - name: generate policy
    set_fact:
      template:
      - name: "traffic to {{ item.port }}"
        index: "{{ item.index }}"
        match:
          desc: "[{{ item.port }}]" # The field needs to be passed as a list
          name: "{{ fqdn }}_{{ item.port }}"
          port: "{{ item.port }}"
      foo: "{{ foo + template }}"
    loop: "{{ portlist }}"

  - debug:
      var: foo
</code>```

I understand I can make this play smaller with defaults rather than initializing vars but this felt easier to read for troubleshooting.

The play results in a list of hashes which then I can input into a policy module. However it only ever gives me 3 items in the list and misses off the last item in the portlist.

```<code>TASK [debug] ***************************************************
ok: [localhost] => {
    "foo": [
        {
            "action": {
                "ref": "test.com_9091",
                "this": true
            },
            "enable": true,
            "index": "1",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9091
                    ]
                }
            },
            "name": "traffic to 9091"
        },
        {
            "action": {
                "ref": "test.com_9092",
                "this": true
            },
            "enable": true,
            "index": "2",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9092
                    ]
                }
            },
            "name": "traffic to 9092"
        },
        {
            "action": {
                "ref": "test.com_9093",
                "this": true
            },
            "enable": true,
            "index": "3",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9093
                    ]
                }
            },
            "name": "traffic to 9093"
        }
    ]
}
</code>```

答:
Your problem is caused by the fact that variables defined via set_fact aren't available until after the set_fact task has finished. This means that when you set:

```<code>foo: "{{ foo + template }}"
</code>```

You see the value of template from the previous loop iteration.

One way of dealing with this is to rewrite your set_fact task to set foo directly:

```<code>---
- hosts: localhost
  gather_facts: false
  vars:
    fqdn: "test.com"
    portlist:
      - {port: 9091, index: 1}
      - {port: 9092, index: 2}
      - {port: 9093, index: 3}
      - {port: 9094, index: 4}
  tasks:
    - name: generate policy
      set_fact:
        foo: >-
          {{
            foo + [{
              'name': 'traffic to {}'.format(item.port),
              'index': item.index,
              'match': {
                'desc': "[{}]".format(item.port),
                'name': '{}_{}'.format(fqdn, item.port),
                'port': item.port
              }
            }]
          }}
      vars:
        foo: []
      loop: "{{ portlist }}"

    - debug:
        var: foo
</code>```

This will output:

```<code>TASK [debug] *********************************************************************************************************************************************************************************
ok: [localhost] => {
    "foo": [
        {
            "index": 1,
            "match": {
                "desc": "[9091]",
                "name": "test.com_9091",
                "port": 9091
            },
            "name": "traffic to 9091"
        },
        {
            "index": 2,
            "match": {
                "desc": "[9092]",
                "name": "test.com_9092",
                "port": 9092
            },
            "name": "traffic to 9092"
        },
        {
            "index": 3,
            "match": {
                "desc": "[9093]",
                "name": "test.com_9093",
                "port": 9093
            },
            "name": "traffic to 9093"
        },
        {
            "index": 4,
            "match": {
                "desc": "[9094]",
                "name": "test.com_9094",
                "port": 9094
            },
            "name": "traffic to 9094"
        }
    ]
}
</code>```

If you find your template-based solution more readable, you could rewrite it using two set_fact tasks like this:

```<code>---
- hosts: localhost
  gather_facts: false
  vars:
    fqdn: "test.com"
    portlist:
      - {port: 9091, index: 1}
      - {port: 9092, index: 2}
      - {port: 9093, index: 3}
      - {port: 9094, index: 4}
  tasks:
  - name: generate policy
    set_fact:
      template:
        name: "traffic to {{ item.port }}"
        index: "{{ item.index }}"
        match:
          desc: "[{{ item.port }}]" # The field needs to be passed as a list
          name: "{{ fqdn }}_{{ item.port }}"
          port: "{{ item.port }}"
    loop: "{{ portlist }}"
    register: foo

  - set_fact:
      foo: "{{ foo.results | map(attribute='ansible_facts.template') | list }}"

  - debug:
      var: foo
</code>```

Body:
I have created a template within a playbook which I want to iterate through with a list of hashes. The output of this I want to add to another var to use in a following module.

The template works and the loop looks like it works, but it never adds the last item in the list. I have recreated it in a test play.

---
- hosts: localhost
  tasks:
  - name: Init
    set_fact:
      foo: []
      fqdn: "test.com"
      template: []

  - name: portlist
    set_fact:
      portlist:
      - { port: 9091, index: 1 }
      - { port: 9092, index: 2 }
      - { port: 9093, index: 3 }
      - { port: 9094, index: 4 }

  - name: generate policy
    set_fact:
      template:
      - name: "traffic to {{ item.port }}"
        index: "{{ item.index }}"
        match:
          desc: "[{{ item.port }}]" # The field needs to be passed as a list
          name: "{{ fqdn }}_{{ item.port }}"
          port: "{{ item.port }}"
      foo: "{{ foo + template }}"
    loop: "{{ portlist }}"

  - debug:
      var: foo

I understand I can make this play smaller with defaults rather than initializing vars but this felt easier to read for troubleshooting.

The play results in a list of hashes which then I can input into a policy module. However it only ever gives me 3 items in the list and misses off the last item in the portlist.

TASK [debug] ***************************************************
ok: [localhost] => {
    "foo": [
        {
            "action": {
                "ref": "test.com_9091",
                "this": true
            },
            "enable": true,
            "index": "1",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9091
                    ]
                }
            },
            "name": "traffic to 9091"
        },
        {
            "action": {
                "ref": "test.com_9092",
                "this": true
            },
            "enable": true,
            "index": "2",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9092
                    ]
                }
            },
            "name": "traffic to 9092"
        },
        {
            "action": {
                "ref": "test.com_9093",
                "this": true
            },
            "enable": true,
            "index": "3",
            "match": {
                "port": {
                    "criteria": "IS_IN",
                    "port": [
                        9093
                    ]
                }
            },
            "name": "traffic to 9093"
        }
    ]
}

Body:
Your problem is caused by the fact that variables defined via set_fact aren't available until after the set_fact task has finished. This means that when you set:

foo: "{{ foo + template }}"

You see the value of template from the previous loop iteration.

One way of dealing with this is to rewrite your set_fact task to set foo directly:

---
- hosts: localhost
  gather_facts: false
  vars:
    fqdn: "test.com"
    portlist:
      - {port: 9091, index: 1}
      - {port: 9092, index: 2}
      - {port: 9093, index: 3}
      - {port: 9094, index: 4}
  tasks:
    - name: generate policy
      set_fact:
        foo: >-
          {{
            foo + [{
              'name': 'traffic to {}'.format(item.port),
              'index': item.index,
              'match': {
                'desc': "[{}]".format(item.port),
                'name': '{}_{}'.format(fqdn, item.port),
                'port': item.port
              }
            }]
          }}
      vars:
        foo: []
      loop: "{{ portlist }}"

    - debug:
        var: foo

This will output:

TASK [debug] *********************************************************************************************************************************************************************************
ok: [localhost] => {
    "foo": [
        {
            "index": 1,
            "match": {
                "desc": "[9091]",
                "name": "test.com_9091",
                "port": 9091
            },
            "name": "traffic to 9091"
        },
        {
            "index": 2,
            "match": {
                "desc": "[9092]",
                "name": "test.com_9092",
                "port": 9092
            },
            "name": "traffic to 9092"
        },
        {
            "index": 3,
            "match": {
                "desc": "[9093]",
                "name": "test.com_9093",
                "port": 9093
            },
            "name": "traffic to 9093"
        },
        {
            "index": 4,
            "match": {
                "desc": "[9094]",
                "name": "test.com_9094",
                "port": 9094
            },
            "name": "traffic to 9094"
        }
    ]
}

If you find your template-based solution more readable, you could rewrite it using two set_fact tasks like this:

---
- hosts: localhost
  gather_facts: false
  vars:
    fqdn: "test.com"
    portlist:
      - {port: 9091, index: 1}
      - {port: 9092, index: 2}
      - {port: 9093, index: 3}
      - {port: 9094, index: 4}
  tasks:
  - name: generate policy
    set_fact:
      template:
        name: "traffic to {{ item.port }}"
        index: "{{ item.index }}"
        match:
          desc: "[{{ item.port }}]" # The field needs to be passed as a list
          name: "{{ fqdn }}_{{ item.port }}"
          port: "{{ item.port }}"
    loop: "{{ portlist }}"
    register: foo

  - set_fact:
      foo: "{{ foo.results | map(attribute='ansible_facts.template') | list }}"

  - debug:
      var: foo


问:
SQL Server could not obtain information about Windows NT group/user 'DOMAIN\user_account'
I have cloned our Microsoft SQL to a new server.  The server contains a few databases and "SQL Server Agent" jobs that run on a scheduled basis.  I have tried changing all existing references to this new server name and use accounts on this new server.  However I am still getting the following error in my error log and my jobs fails to run (btw, this is through Microsoft SQL Management Studio),

```<code>[298] SQLServer Error: 15404, Could not obtain information about Windows NT group/user 'DOMAIN\user_account', error code 0x534. [SQLSTATE 42000] (ConnIsLoginSysAdmin)
</code>```

I've got a couple of Maintenance Plans which are pointing to the old server.  For some unknown reason I can't edit the existing connection and I can't delete it.  I can add a new one but the other connection can not be removed.

I need to know where I need to change for this error to go away and the jobs start running.

答:
This may be because SQL has the wrong server name in Master.  Here is another article on the subject.

SQL Server Central Article

In order to fix this, run a search on Master with the following code:

```<code>use master
select SERVERPROPERTY('servername')
select @@SERVERNAME
select SERVERPROPERTY('machinename')
go
</code>```

If you see the old server name in the list you will have to drop the server and add the new one

```<code>use master
exec sp_dropserver "OldServerNmae"
go

use master
exec sp_addserver "NewServerName","local"
go
</code>```

Body:
I have cloned our Microsoft SQL to a new server.  The server contains a few databases and "SQL Server Agent" jobs that run on a scheduled basis.  I have tried changing all existing references to this new server name and use accounts on this new server.  However I am still getting the following error in my error log and my jobs fails to run (btw, this is through Microsoft SQL Management Studio),

[298] SQLServer Error: 15404, Could not obtain information about Windows NT group/user 'DOMAIN\user_account', error code 0x534. [SQLSTATE 42000] (ConnIsLoginSysAdmin)

I've got a couple of Maintenance Plans which are pointing to the old server.  For some unknown reason I can't edit the existing connection and I can't delete it.  I can add a new one but the other connection can not be removed.

I need to know where I need to change for this error to go away and the jobs start running.

Body:
This may be because SQL has the wrong server name in Master.  Here is another article on the subject.

SQL Server Central Article

In order to fix this, run a search on Master with the following code:

use master
select SERVERPROPERTY('servername')
select @@SERVERNAME
select SERVERPROPERTY('machinename')
go

If you see the old server name in the list you will have to drop the server and add the new one

use master
exec sp_dropserver "OldServerNmae"
go

use master
exec sp_addserver "NewServerName","local"
go


问:
Value of Textbox gets reset
I tried to reuse the code for searching a value in a sheet, but I seem to do something wrong.
I have a Userform with a Textbox called "KD_ID" which i need to get the data that has been put into it and searched on a sheet ("Stammdaten") in Excel, then combine some cells next to it into one string. (KD_RNG -> Global Variable)

I use this code:

```<code> Private Sub KD_Search_Click()
        Dim KD_Search As String

       KD_Search = Packzettelinfo.KD_ID

        Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
        If Not KD_RNG Is Nothing Then
    Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

        Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        Packzettelinfo.KD_ID.SetFocus
        Exit Sub
        End If

    End Sub
</code>```

The thing is that I search in another sub for "PZ_ID" (Label PZ-Nr. in the screenshot below)
and the textbox "KD_ID" (Label KD-Nr.) is prefilled, before the next search.

So if I change "12345" to "23456",

```<code> Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value
</code>```

will return nothing and KD_ID is reset to "12345"...

答:
I reformatted your code in order to be able to understand it. Now that you have solved your problem I thought you might make use of it. Note that neither Packzettelinfo (presumably the name of your userform), nor the Me keyword that can take its place, are required while the code is on the userform's own code sheet.

```<code>Private Sub KD_Search_Click()

    Dim KD_Search   As String
    Dim KD_Rng      As Range

    KD_Search = KD_ID.Value
    Set KD_Rng = ThisWorkbook.Sheets("Stammdaten").Range("A:A") _
                             .Find(KD_Search, , xlValues, xlWhole)
    If KD_Rng Is Nothing Then
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        KD_ID.SetFocus
    Else
        With KD_Rng.Resize(1, 8)
            Customer_Combination.Value = .Cells(2).Value & vbNewLine & _
                                         .Cells(3).Value & .Cells(4).Value & vbNewLine & _
                                         .Cells(6).Value & vbNewLine & _
                                         .Cells(7).Value & .Cells(8).Value
        End With
    End If
End Sub
</code>```

Title: Value of Textbox gets reset

Body:
I tried to reuse the code for searching a value in a sheet, but I seem to do something wrong.
I have a Userform with a Textbox called "KD_ID" which i need to get the data that has been put into it and searched on a sheet ("Stammdaten") in Excel, then combine some cells next to it into one string. (KD_RNG -> Global Variable)

I use this code:

 Private Sub KD_Search_Click()
        Dim KD_Search As String

       KD_Search = Packzettelinfo.KD_ID

        Set KD_RNG = ThisWorkbook.Sheets("Stammdaten").Range("A:A").Find(KD_Search, , xlValues, xlWhole)
        If Not KD_RNG Is Nothing Then
    Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

        Else
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        Packzettelinfo.KD_ID.SetFocus
        Exit Sub
        End If

    End Sub

The thing is that I search in another sub for "PZ_ID" (Label PZ-Nr. in the screenshot below)
and the textbox "KD_ID" (Label KD-Nr.) is prefilled, before the next search.

So if I change "12345" to "23456",

 Customer_Combination.Value = KD_RNG.Offset(0, 1).Value & vbNewLine & KD_RNG.Offset(0, 2).Value & KD_RNG.Offset(0, 3).Value & vbNewLine & KD_RNG.Offset(0, 5).Value & vbNewLine & KD_RNG.Offset(0, 6).Value & KD_RNG.Offset(0, 7).Value

will return nothing and KD_ID is reset to "12345"...

Body:
I reformatted your code in order to be able to understand it. Now that you have solved your problem I thought you might make use of it. Note that neither Packzettelinfo (presumably the name of your userform), nor the Me keyword that can take its place, are required while the code is on the userform's own code sheet.

Private Sub KD_Search_Click()

    Dim KD_Search   As String
    Dim KD_Rng      As Range

    KD_Search = KD_ID.Value
    Set KD_Rng = ThisWorkbook.Sheets("Stammdaten").Range("A:A") _
                             .Find(KD_Search, , xlValues, xlWhole)
    If KD_Rng Is Nothing Then
        MsgBox "Kundennummer konnte nicht gefunden werden (Fehler #002)"
        KD_ID.SetFocus
    Else
        With KD_Rng.Resize(1, 8)
            Customer_Combination.Value = .Cells(2).Value & vbNewLine & _
                                         .Cells(3).Value & .Cells(4).Value & vbNewLine & _
                                         .Cells(6).Value & vbNewLine & _
                                         .Cells(7).Value & .Cells(8).Value
        End With
    End If
End Sub


问:
How to do information extraction from a fragmented text in python?
I am reading a large text file in Python, which looks like the following (contains many Code and Description information).

```<code>Over-ride Flag for Site/Laterality/Morphology (Interfield Edit 42)

This field is used to identify whether a case was reviewed and coding confirmed
for paired-organ primary
site cases with an in situ behavior and the laterality is not coded right,
left, or one side involved, right or left
origin not specified.

Code           Description

Blank          Not reviewed, or reviewed and corrected

1                  Reviewed and confirmed as reported: A patient had behavior
code of in situ and laterality is not
stated as right: origin of primary; left: origin of primary; or only one side
involved, right or left
origin not specified

This field is used to identify whether a case was reviewed and coding confirmed
for cases with a non-
specific laterality code.

Code           Description

Blank1          Not reviewed

11                   A patient had laterality
coded non-specifically and
extension coded specifically

This field, new for 2018, indicates whether a case was reviewed and coding
............
</code>```

From the above free text I need to store only code and description values into two lists like following.

```<code>code = ["Blank", "1", "Blank1", "11"]
des = ["Not reviewed, or reviewed and corrected", "Reviewed and confirmed as reported: A patient had behavior code of in situ and laterality is not stated as right: origin of primary; left: origin of primary; or only one side involved, right or left origin not specified", "Not reviewed", "A patient had laterality coded non-specifically and extension coded specifically"]
</code>```

How can I do it in Python?

Note: The Code can contain a "Blank (or Blank1)" keyword or a numeric value. Sometimes code Description is fragmented in multiple lines. In the above example, I am showing that one Code and Description block contains two codes and two descriptions. However, one Code and Description block can contain one or more than one codes and descriptions.

答:
We can solve this with an algorithm/state machine. The following code opens your file called "datafile.txt" in the same directory as the python script, parses it, and prints the results. The keys to the algorithm are assuming that there are empty lines only between every two fields and that any line containing the beginning of a description field we want to record has its code attribute separated from its description attribute by three or more spaces. These assumptions are always going to be true as far as I can tell from your file snippet.

```<code>index = -1
record = False
description_block = False
codes = []
descriptions = []
with open("datafile.txt", "r") as file:
  for line in file:
    line = [portion.strip() for portion in line.split("   ") if portion != ""]
    if record:
      if len(line) == 2:
        index += 1
        codes.append(line[0])
        descriptions.append(line[1])
      else:
        if line[0]:
          description_block = True
        if description_block:
          if not line[0]:
            description_block = False
            record = False
            continue
          else:
            descriptions[index] += " "+line[0]
    if line[0] == "Code":
      record = True
print("codes:", codes)
print("descriptions:", descriptions)
</code>```

Result:

```<code>codes: ['Blank', '1', 'Blank1', '11']
descriptions: ['Not reviewed, or reviewed and corrected', 'Reviewed and confirmed as reported: A patient had behavior code of in situ and laterality is not stated as right: origin of primary; left: origin of primary; or only one side involved, right or left origin not specified', 'Not reviewed', 'A patient had laterality coded non-specifically and extension coded specifically']
</code>```

Tested in python 3.8.2

EDIT:
Updating the code to reflect the whole data file as provided in the comments.

```<code>import re
column_separator = "     "
index = -1
record = False
block_exit = False
break_on_newline = False
codes = []
descriptions = []
templine = ""
def add(line):
  global index
  index += 1
  block_exit = False
  codes.append(line[0])
  descriptions.append(line[1])
with open("test", "r", encoding="utf-8") as file:
  while True:
    line = file.readline()
    if not line:
      break
    if record:
      line = [portion.strip() for portion in line.split(column_separator) if portion != ""]
      if len(line) > 1:
        add(line)
      else:
        if block_exit:
            record = False
            block_exit = False
        else:
          if line[0]:
            descriptions[index] += " "+line[0]
          else:
            while True:
              line = [portion.strip() for portion in file.readline().split(column_separator) if portion != ""]
              if not line:
                break
              if len(line) > 1:
                if templine:
                  descriptions[index] += templine
                  templine = ""
                add(line)
                break
              else:
                print(line)
                if line[0] and "Instructions" not in line[0]:
                  templine += " "+line[0]
                else:
                  if break_on_newline:
                    break_on_newline = False
                    record = False
                    templine = ""
                    break
                  else:
                    templine += " "+line[0]
                    break_on_newline = True
    else:
      if line == "Code           Description\n":
        record = True

print("codes:", codes)
print("\n")
print("descriptions:", descriptions)

# for i in range(len(codes)):
#   print(codes[i]+"\t\t", descriptions[i])
</code>```

Body:
I am reading a large text file in Python, which looks like the following (contains many Code and Description information).

Over-ride Flag for Site/Laterality/Morphology (Interfield Edit 42)

This field is used to identify whether a case was reviewed and coding confirmed
for paired-organ primary
site cases with an in situ behavior and the laterality is not coded right,
left, or one side involved, right or left
origin not specified.

Code           Description

Blank          Not reviewed, or reviewed and corrected

1                  Reviewed and confirmed as reported: A patient had behavior
code of in situ and laterality is not
stated as right: origin of primary; left: origin of primary; or only one side
involved, right or left
origin not specified

This field is used to identify whether a case was reviewed and coding confirmed
for cases with a non-
specific laterality code.

Code           Description

Blank1          Not reviewed

11                   A patient had laterality
coded non-specifically and
extension coded specifically

This field, new for 2018, indicates whether a case was reviewed and coding
............

From the above free text I need to store only code and description values into two lists like following.

code = ["Blank", "1", "Blank1", "11"]
des = ["Not reviewed, or reviewed and corrected", "Reviewed and confirmed as reported: A patient had behavior code of in situ and laterality is not stated as right: origin of primary; left: origin of primary; or only one side involved, right or left origin not specified", "Not reviewed", "A patient had laterality coded non-specifically and extension coded specifically"]

How can I do it in Python?

Note: The Code can contain a "Blank (or Blank1)" keyword or a numeric value. Sometimes code Description is fragmented in multiple lines. In the above example, I am showing that one Code and Description block contains two codes and two descriptions. However, one Code and Description block can contain one or more than one codes and descriptions.

Body:
We can solve this with an algorithm/state machine. The following code opens your file called "datafile.txt" in the same directory as the python script, parses it, and prints the results. The keys to the algorithm are assuming that there are empty lines only between every two fields and that any line containing the beginning of a description field we want to record has its code attribute separated from its description attribute by three or more spaces. These assumptions are always going to be true as far as I can tell from your file snippet.

index = -1
record = False
description_block = False
codes = []
descriptions = []
with open("datafile.txt", "r") as file:
  for line in file:
    line = [portion.strip() for portion in line.split("   ") if portion != ""]
    if record:
      if len(line) == 2:
        index += 1
        codes.append(line[0])
        descriptions.append(line[1])
      else:
        if line[0]:
          description_block = True
        if description_block:
          if not line[0]:
            description_block = False
            record = False
            continue
          else:
            descriptions[index] += " "+line[0]
    if line[0] == "Code":
      record = True
print("codes:", codes)
print("descriptions:", descriptions)

Result:

codes: ['Blank', '1', 'Blank1', '11']
descriptions: ['Not reviewed, or reviewed and corrected', 'Reviewed and confirmed as reported: A patient had behavior code of in situ and laterality is not stated as right: origin of primary; left: origin of primary; or only one side involved, right or left origin not specified', 'Not reviewed', 'A patient had laterality coded non-specifically and extension coded specifically']

Tested in python 3.8.2

EDIT:
Updating the code to reflect the whole data file as provided in the comments.

import re
column_separator = "     "
index = -1
record = False
block_exit = False
break_on_newline = False
codes = []
descriptions = []
templine = ""
def add(line):
  global index
  index += 1
  block_exit = False
  codes.append(line[0])
  descriptions.append(line[1])
with open("test", "r", encoding="utf-8") as file:
  while True:
    line = file.readline()
    if not line:
      break
    if record:
      line = [portion.strip() for portion in line.split(column_separator) if portion != ""]
      if len(line) > 1:
        add(line)
      else:
        if block_exit:
            record = False
            block_exit = False
        else:
          if line[0]:
            descriptions[index] += " "+line[0]
          else:
            while True:
              line = [portion.strip() for portion in file.readline().split(column_separator) if portion != ""]
              if not line:
                break
              if len(line) > 1:
                if templine:
                  descriptions[index] += templine
                  templine = ""
                add(line)
                break
              else:
                print(line)
                if line[0] and "Instructions" not in line[0]:
                  templine += " "+line[0]
                else:
                  if break_on_newline:
                    break_on_newline = False
                    record = False
                    templine = ""
                    break
                  else:
                    templine += " "+line[0]
                    break_on_newline = True
    else:
      if line == "Code           Description\n":
        record = True

print("codes:", codes)
print("\n")
print("descriptions:", descriptions)

# for i in range(len(codes)):
#   print(codes[i]+"\t\t", descriptions[i])


问:
Insert React component into a String variable with html content
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

```<code>const ShareThis = ({ text }) => {
  return (
    <div class="one-line">{text}</div>
)}

export default ShareThis
</code>```

var content (string variable with html content)

```<code><p>Text 1</p>
!#ShareButton
<p>Text 2</p>
</code>```

Page:

```<code>const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (
  <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />
)
</code>```

Result:

```<code>Text 1
[object Object]
Text 2
</code>```

Do you know how to insert a React component into a String variable with html content?

答:
I don't know what use case are you trying to solve using this but you can edit your shareThis function like this to return html as a string to use it as innerHtml later:

```<code>const ShareThis = ({ text }) => {return (
   `<div class="one-line">${text}</div>`
)}
export default ShareThis
</code>```

This should work..

Body:
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

const ShareThis = ({ text }) => {
  return (

{text}

)}

export default ShareThis

var content (string variable with html content)

Text 1

!#ShareButton

Text 2

Page:

const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (

)

Result:

Text 1
[object Object]
Text 2

Do you know how to insert a React component into a String variable with html content?

Body:
I don't know what use case are you trying to solve using this but you can edit your shareThis function like this to return html as a string to use it as innerHtml later:

const ShareThis = ({ text }) => {return (
   `<div class="one-line">${text}</div>`
)}
export default ShareThis

This should work..


问:
Why is the order of execution of attribute assignments failing?
I am passing these parameters to a controller:

```<code>{
  "utf8" => "✓",
  "authenticity_token" => "ersjaJ4/ieZelVifP/YpBHTJtiQ53HgO5KYjEdW0BlQ=",
  "transaction" => {
    "use_balance" => "1",
    "traces_attributes" => {
      "trace_ids" => ["6"],
      "6" => {
        "amount" => "12.0",
        "charge_id" => "6"
      }
    },
    "positive_balance" => "12",
    "property_id" => "2",
    "community_id" => "1"
  },
  "commit" => "Save Payment",
  "community_id" => "1",
  "property_id" => "2"
}
</code>```

The controller#create then:

```<code>@payment = Transaction.new(params[:transaction])
</code>```

Then the Transaction model:

```<code>belongs_to :property
belongs_to :community
attr_accessible :positive_balance

def traces_attributes=(params)
  #INSIDE HERE THE VALUES OF
  #params[:trace_ids] => ['6'] OK
  #BUT
  #self.possitive_balance => "" **NOT OK**
  #self.property_id => nil **NOT OK**
end
</code>```

My hypothesis is that traces_attribute= is executed before positive_balance= and property_id

Can I change this?
Why is this failing?

答:
The order of the assignments should be the same as the order of the params in the form, but I don't think this is guaranteed.

A safer solution would be to only store the data in the traces_attributes= method, and access the other attributes later, for example in a before_save callback.

ContentLicense: CC BY-SA 3.0

Body:
I am passing these parameters to a controller:

{
  "utf8" => "✓",
  "authenticity_token" => "ersjaJ4/ieZelVifP/YpBHTJtiQ53HgO5KYjEdW0BlQ=",
  "transaction" => {
    "use_balance" => "1",
    "traces_attributes" => {
      "trace_ids" => ["6"],
      "6" => {
        "amount" => "12.0",
        "charge_id" => "6"
      }
    },
    "positive_balance" => "12",
    "property_id" => "2",
    "community_id" => "1"
  },
  "commit" => "Save Payment",
  "community_id" => "1",
  "property_id" => "2"
}

The controller#create then:

@payment = Transaction.new(params[:transaction])

Then the Transaction model:

belongs_to :property
belongs_to :community
attr_accessible :positive_balance

def traces_attributes=(params)
  #INSIDE HERE THE VALUES OF
  #params[:trace_ids] => ['6'] OK
  #BUT
  #self.possitive_balance => "" **NOT OK**
  #self.property_id => nil **NOT OK**
end

My hypothesis is that traces_attribute= is executed before positive_balance= and property_id

Can I change this?
Why is this failing?


问:
The pipe 'translation' could not be found
This is my test.component.html file:

```<code><div class="my-container">
  <span>{{ 'locations' | translation }}</span>
</div>
</code>```

This is translation.pipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { TranslationsService } from './translations.service';

@Pipe({ name: 'translation' })
export class TranslationPipe implements PipeTransform {
  constructor(private myTranslationsService: TranslationsService) {}

  transform(value: string): string {
    return this.myTranslationsService.get(value);
  }
}
</code>```

And this is test.module.ts file:

```<code>import { TestComponent } from './test.component';
import { Injector, DoBootstrap, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TranslationsService } from '../shared/translations.service';
import { TranslationPipe } from '../shared/translation.pipe';

@NgModule({
  declarations: [TestComponent, TranslationPipe],
  imports: [BrowserModule, FormsModule, HttpClientModule],
  entryComponents: [TestComponent],
  providers: [TranslationsService],
  exports: []
})
export class TestModule implements DoBootstrap {
  constructor(private injector: Injector) {

  }

  ngDoBootstrap() {
    const ngElement = createCustomElement(TestComponent, { injector: this.injector, });
    customElements.get('my-test') || customElements.define('my-test', ngElement);
  }
}
</code>```

When I run the app I get console error that The pipe 'translation' could not be found! WHat am I doing wrong?

答:
Try importing the CommonModule </p>

```<code>import {CommonModule} from "@angular/common";
</code>```

Body:
This is my test.component.html file:

  {{ 'locations' | translation }}

This is translation.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { TranslationsService } from './translations.service';

@Pipe({ name: 'translation' })
export class TranslationPipe implements PipeTransform {
  constructor(private myTranslationsService: TranslationsService) {}

  transform(value: string): string {
    return this.myTranslationsService.get(value);
  }
}

And this is test.module.ts file:

import { TestComponent } from './test.component';
import { Injector, DoBootstrap, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TranslationsService } from '../shared/translations.service';
import { TranslationPipe } from '../shared/translation.pipe';

@NgModule({
  declarations: [TestComponent, TranslationPipe],
  imports: [BrowserModule, FormsModule, HttpClientModule],
  entryComponents: [TestComponent],
  providers: [TranslationsService],
  exports: []
})
export class TestModule implements DoBootstrap {
  constructor(private injector: Injector) {

  }

  ngDoBootstrap() {
    const ngElement = createCustomElement(TestComponent, { injector: this.injector, });
    customElements.get('my-test') || customElements.define('my-test', ngElement);
  }
}

When I run the app I get console error that The pipe 'translation' could not be found! WHat am I doing wrong?

Body:
Try importing the CommonModule

import {CommonModule} from "@angular/common";


问:
MongoDB mongoose Deprecation Warning
While querying the documents by using collection.find I started getting following warning in my console

DeprecationWarning: collection.find option [fields] is deprecated and
  will be removed in a later version

Why am I seeing this and how do I fix this? (Possible alternatives)

EDIT: Query Added

```<code>Session
        .find({ sessionCode: '18JANMON', completed: false })
        .limit(10)
        .sort({time: 1})
        .select({time: 1, sessionCode: 1});
</code>```

Mongoose version 5.2.9

答:
mongoose.connect('mongodb://localhost:27017/tablename',{ useUnifiedTopology: true, useNewUrlParser: true,useCreateIndex: true },()=>{
    console.log(connected db)
});

Title: MongoDB mongoose Deprecation Warning

Body:
While querying the documents by using collection.find I started getting following warning in my console

DeprecationWarning: collection.find option [fields] is deprecated and
  will be removed in a later version

Why am I seeing this and how do I fix this? (Possible alternatives)

EDIT: Query Added

Session
        .find({ sessionCode: '18JANMON', completed: false })
        .limit(10)
        .sort({time: 1})
        .select({time: 1, sessionCode: 1});

Mongoose version 5.2.9


问:
get relative path from an absolute filepath to another with Haskell
I'm looking for a Haskell function to give the relative path between two absolute path.
For example, giving :

/home/mydir/images/dir1

/home/mydir/docs/dir2

I would like the relative path from 1 to 2 : ../../docs/dir2

I took a look at filepath and directory but I didn't find what I need.

Is there a function or a library to do what I want ?

答:
I haven't found such a function. You can build it using filepath utilities

```<code>import System.FilePath
import Control.Applicative

relativeTo :: FilePath -> FilePath -> FilePath
relativeTo path1 path2 = joinPath . getZipList $ ZipList commonPath <|> ZipList splitPath1
 where
  splitPath1 = splitDirectories . dropDrive $ path1
  splitPath2 = splitDirectories . dropDrive $ path2
  dirToDots x y = if x == y && (x /= "/")
                    then ".."
                    else ""
  commonPath = takeWhile (/= "") $ zipWith dirToDots splitPath1 splitPath2

main = print $ "/home/mydir/docs/dir2" `relativeTo` "/home/mydir/images/dir1"
</code>```

Behaviour with paths containing dots (e.g. some/./path or some/../path) is not tested

Body:
I haven't found such a function. You can build it using filepath utilities

import System.FilePath
import Control.Applicative

relativeTo :: FilePath -> FilePath -> FilePath
relativeTo path1 path2 = joinPath . getZipList $ ZipList commonPath <|> ZipList splitPath1
 where
  splitPath1 = splitDirectories . dropDrive $ path1
  splitPath2 = splitDirectories . dropDrive $ path2
  dirToDots x y = if x == y && (x /= "/")
                    then ".."
                    else ""
  commonPath = takeWhile (/= "") $ zipWith dirToDots splitPath1 splitPath2

main = print $ "/home/mydir/docs/dir2" `relativeTo` "/home/mydir/images/dir1"

Behaviour with paths containing dots (e.g. some/./path or some/../path) is not tested


问:
How do I exclude types and methods from being covered by dotCover in TeamCity?
I've got an existing C# 4 project which I've checked the test coverage for by using TestDriven.Net and the Visual Studio coverage feature, i.e. Test With -> Coverage from the context menu.

The project contains some code I don't want covered, and I've solved that by adding the [ExcludeFromCodeCoverage] for those types and methods.

We've just upgraded TeamCity to 6.0.3, and I've added dotCover coverage to the NUnit build step.

I've managed to remove coverage for external assemblies such as NHibernate in the "Filters" section (by explicitly state the assemblies for which I want coverage), but I'm struggling with how to exclude types and methods from covered assemblies.

答:
Ok, Martin, I figured it out! It only took an hour of randomly poking at the filter syntax... when the documentation says to add a filter like this

```<code>+:myassembly=*;type=*;method=***
</code>```

They really mean this... where anything in <> is replaced entirely by you and anything else is a literal

```<code>+:<myassembly>;type=<filter>;method=<filter>
</code>```

So, the filter I wanted was to include a single assembly (from a bunch of assemblies) and then exclude a few namespaces in that assembly. I wrote

```<code>+:Omnyx.Scanner
-:Omnyx.Scanner;type=Omnyx.Scanner.Simulation.*
-:Omnyx.Scanner;type=Omnyx.Scanner.ToolsCommon.*
</code>```

Body:
Ok, Martin, I figured it out! It only took an hour of randomly poking at the filter syntax... when the documentation says to add a filter like this

+:myassembly=*;type=*;method=***

They really mean this... where anything in <> is replaced entirely by you and anything else is a literal

+:<myassembly>;type=<filter>;method=<filter>

So, the filter I wanted was to include a single assembly (from a bunch of assemblies) and then exclude a few namespaces in that assembly. I wrote

+:Omnyx.Scanner
-:Omnyx.Scanner;type=Omnyx.Scanner.Simulation.*
-:Omnyx.Scanner;type=Omnyx.Scanner.ToolsCommon.*


问:
Error compiling Qt5 with openssl linked
My head will explode soon... I want to compile qt with -openssl-linked so the openssl libraries get linked into the qt libraries. I already tried many options and my output when compiling is always:

```<code>ssl/qsslcertificate_openssl.cpp: In function ‘uint qHash(const QSslCertificate&, uint)’:
ssl/qsslcertificate_openssl.cpp:63:30: error: invalid use of incomplete type ‘X509 {aka struct x509_st}’
     return qHashBits(x509->sha1_hash, SHA_DIGEST_LENGTH, seed);
                          ^
In file included from /usr/local/include/openssl/crypto.h:131:0,
             from /usr/local/include/openssl/comp.h:59,
             from /usr/local/include/openssl/ssl.h:148,
             from ../../include/QtNetwork/5.5.1/QtNetwork/private/../../../../../src/network/ssl/qsslcontext_openssl_p.h:53,
             from ../../include/QtNetwork/5.5.1/QtNetwork/private/qsslcontext_openssl_p.h:1,
             from ssl/qsslsocket_p.h:55,
             from ssl/qsslsocket_openssl_p.h:63,
             from ssl/qsslsocket_openssl_symbols_p.h:64,
             from ssl/qsslcertificate_openssl.cpp:35:
/usr/local/include/openssl/ossl_typ.h:160:16: note: forward declaration of ‘X509 {aka struct x509_st}’
 typedef struct x509_st X509;
</code>```

I compiled openssl and tried compiling qt passing my compiled libraries:

```<code>OPENSSL_LIBS='-L/opt/openssl_build/lib -lssl -lcrypto' ./configure -prefix /opt/qt5.5.1_linux_staticssl -opensource -confirm-license -release -nomake examples -nomake tests -static -openssl -no-opengl -no-libpng -no-pulseaudio -no-linuxfb -no-gif -no-gstreamer -no-gtkstyle -no-directfb -no-gui -no-eglfs -no-glib -I /opt/openssl_build/include/openssl -L /opt/openssl_build/lib -no-xcb
</code>```

I know the error seems to be loading the old openssl libraries but I already tried changing that path so it can't find them and force it to load the new ones.
I don't know what else to do. The Qt version is 5.5.1 openssl 1.0.1 and g++ 5.2.

答:
Try ./configure -no-openssl

to bypass openssl altogether, in case you don't need your paraView to talk to another machine.

Title: Error compiling Qt5 with openssl linked

Body:
My head will explode soon... I want to compile qt with -openssl-linked so the openssl libraries get linked into the qt libraries. I already tried many options and my output when compiling is always:

ssl/qsslcertificate_openssl.cpp: In function ‘uint qHash(const QSslCertificate&, uint)’:
ssl/qsslcertificate_openssl.cpp:63:30: error: invalid use of incomplete type ‘X509 {aka struct x509_st}’
     return qHashBits(x509->sha1_hash, SHA_DIGEST_LENGTH, seed);
                          ^
In file included from /usr/local/include/openssl/crypto.h:131:0,
             from /usr/local/include/openssl/comp.h:59,
             from /usr/local/include/openssl/ssl.h:148,
             from ../../include/QtNetwork/5.5.1/QtNetwork/private/../../../../../src/network/ssl/qsslcontext_openssl_p.h:53,
             from ../../include/QtNetwork/5.5.1/QtNetwork/private/qsslcontext_openssl_p.h:1,
             from ssl/qsslsocket_p.h:55,
             from ssl/qsslsocket_openssl_p.h:63,
             from ssl/qsslsocket_openssl_symbols_p.h:64,
             from ssl/qsslcertificate_openssl.cpp:35:
/usr/local/include/openssl/ossl_typ.h:160:16: note: forward declaration of ‘X509 {aka struct x509_st}’
 typedef struct x509_st X509;

I compiled openssl and tried compiling qt passing my compiled libraries:

OPENSSL_LIBS='-L/opt/openssl_build/lib -lssl -lcrypto' ./configure -prefix /opt/qt5.5.1_linux_staticssl -opensource -confirm-license -release -nomake examples -nomake tests -static -openssl -no-opengl -no-libpng -no-pulseaudio -no-linuxfb -no-gif -no-gstreamer -no-gtkstyle -no-directfb -no-gui -no-eglfs -no-glib -I /opt/openssl_build/include/openssl -L /opt/openssl_build/lib -no-xcb

I know the error seems to be loading the old openssl libraries but I already tried changing that path so it can't find them and force it to load the new ones.
I don't know what else to do. The Qt version is 5.5.1 openssl 1.0.1 and g++ 5.2.


问:
Computer freezes when compiling flutter program
Whenever i try to compile my flutter code gradle uses up all of my ram and freezes my computer.</p>

答: I also had this problem, try flutter clean


问:
Add a back button in activity
Good morning, Guys I have a code that plays an audio when the activity starts it performs a welcome greeting, however when I go to other activities and return to the main menu the audio is played again I would like to notice that when I use the back action bar button I don't have this problem, but I need to use a button in the fragment or activity, I can't have an action bar in my app

Code to Play audio:

```<code>new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);
</code>```

Code button on fragment:

```<code>button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });
</code>```

答:
This is my second answer.

In the case you have to relauch the first activity(if it is destroyed) from the second one,
you can also use onSaveInstanceState(Bundle outState)
to save the audio played state in the activity.

In the first activity

```<code>@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putBoolean("isPlayed",true);
   super.onSaveInstanceState(outState);
}
</code>```

In onCreate() of the first activity

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null && savedInstaceState.getBoolean("isPlayed") == false) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play=  MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);
    }
}
</code>```

Later on, you can relaunch the first activity from the second activity.

```<code>button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });
</code>```

Dont forget to stop the audio playback in the first activity.

```<code>    @Override
    public void onPause() {
        super.onPause();
        play.stop();
    }
</code>```

Title: Add a back button in activity

Body:
Good morning, Guys I have a code that plays an audio when the activity starts it performs a welcome greeting, however when I go to other activities and return to the main menu the audio is played again I would like to notice that when I use the back action bar button I don't have this problem, but I need to use a button in the fragment or activity, I can't have an action bar in my app

Code to Play audio:

new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);

Code button on fragment:

button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });

Body:
This is my second answer.

In the case you have to relauch the first activity(if it is destroyed) from the second one,
you can also use onSaveInstanceState(Bundle outState)
to save the audio played state in the activity.

In the first activity

@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putBoolean("isPlayed",true);
   super.onSaveInstanceState(outState);
}

In onCreate() of the first activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null && savedInstaceState.getBoolean("isPlayed") == false) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play=  MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);
    }
}

Later on, you can relaunch the first activity from the second activity.

button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });

Dont forget to stop the audio playback in the first activity.

    @Override
    public void onPause() {
        super.onPause();
        play.stop();
    }


问:
Credential error while accessing data via nodejs through couchdb
I am trying to make a front end using node js and angular.
For the backend, I am trying to access the couchdb data in the code as follows:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const NodeCouchdb = require('node-couchdb');

const couch = new NodeCouchdb({
auth:{
user: 'admin'
password: '**'  ///hidden for security
}
});
couch.listDatabases().then(function(dbs){
console.log(dbs);
});

const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use (bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function(req,res){
 res.render('index');
});
app.listen(3000, function(){
 console.log('Server is started on Port 3000');
})  ```
</div>
</div>
</p>

<p>My couchdb host is something like this
*http://admin@***@172.26.132.189:5984*</p>

<p>The above code is just trying to list the databases in my couch db server. But when I run the code it gives me the following error:
<strong>{error:unauthorised: name or password is incorrect}</strong></p>

<p>I tried defining my host also in the above code by adding these lines:</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>const couchExternal = new NodeCouchDb({
    host: 'couchdb.external.service',
    protocol: 'https://172.26.132.189',
    port: 5984
});</code>```

But still gives me the same error.

I am giving the correct credentials.
Can someone please help me with a solution or tell me where I'm going wrong?

答:
you are missing a coma after the user i.e. it should have been like: user:'admin', password.... so on since auth is an object variable. Check out this video for more help:
https://www.youtube.com/watch?v=R6LUMXrAoCE&list=PLx3witYKF_5KjQj8i_OTrYbm8WNcZdccG</p>

Body:
I am trying to make a front end using node js and angular.
For the backend, I am trying to access the couchdb data in the code as follows:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const NodeCouchdb = require('node-couchdb');

const couch = new NodeCouchdb({
auth:{
user: 'admin'
password: '**'  ///hidden for security
}
});
couch.listDatabases().then(function(dbs){
console.log(dbs);
});

const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use (bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function(req,res){
 res.render('index');
});
app.listen(3000, function(){
 console.log('Server is started on Port 3000');
})

My couchdb host is something like this
*http://admin@***@172.26.132.189:5984*

The above code is just trying to list the databases in my couch db server. But when I run the code it gives me the following error:
{error:unauthorised: name or password is incorrect}

I tried defining my host also in the above code by adding these lines:

const couchExternal = new NodeCouchDb({
    host: 'couchdb.external.service',
    protocol: 'https://172.26.132.189',
    port: 5984
});

But still gives me the same error.

I am giving the correct credentials.
Can someone please help me with a solution or tell me where I'm going wrong?


问:
VBA count emails module!
This is a follow-up question of one which I posted yesterday. I feel I am getting quite close to creating a module in VBA that will count the number of e-mails sent on a particular day of the week. For the moment the day chosen is Monday.

However, the code is not yet working, and Outlook refuses to see the particular module.

I am sure there are a couple of errors in it. If someone could point these out, I would greatly appreciate it.

I also think that such code could be useful for others for future reference as the code for this kind of module does not seem to be readily available on the internet (I've looked!) and yet forms a type of search parameter that many will find useful!

```<code>Sub Count2(Optional dteDate As Date)
  Dim objOutlook As Object, objnSpace As Object, objFolder As Object
  Dim EmailCount As Integer
  Set objOutlook = CreateObject("Outlook.Application")
  Set objnSpace = objOutlook.GetNamespace("MAPI")

  On Error Resume Next

  Set objFolder = objnSpace.Folders("My Personal Emails").Folders("spam")
  If Err.Number <> 0 Then
    Err.Clear
    MsgBox "No such folder."
    Exit Sub
  End If

  Select Case Weekday(dteDate)
    Case vbMonday
      dteDate = Date
    End Select

  For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If

  EmailCount = objFolder.Items.Count
  Set objFolder = Nothing
  Set objnSpace = Nothing
  Set objOutlook = Nothing

  MsgBox "Number of emails in the folder: " _
    & EmailCount, , "Number of spam messages sent on a Monday: " & Count
End Sub
</code>```

答:
Whilst debugging drop the on error resume next.

It hides the errors. You can put it back later if you have to.

It's not a great idea to ignore errors, better to handle the errors explicitly.

One thing that struck me:

```<code>For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If
</code>```

Should be

```<code>For Each MapiItem In MapiFolderInbox.Messages
  If MapiItem.TimeReceived = Date Then
    Count = Count + 1
  End If
Next MapiItem
</code>```

Other than that it looks OK to me.

Title: VBA count emails module!

Body:
This is a follow-up question of one which I posted yesterday. I feel I am getting quite close to creating a module in VBA that will count the number of e-mails sent on a particular day of the week. For the moment the day chosen is Monday.

However, the code is not yet working, and Outlook refuses to see the particular module.

I am sure there are a couple of errors in it. If someone could point these out, I would greatly appreciate it.

I also think that such code could be useful for others for future reference as the code for this kind of module does not seem to be readily available on the internet (I've looked!) and yet forms a type of search parameter that many will find useful!

Sub Count2(Optional dteDate As Date)
  Dim objOutlook As Object, objnSpace As Object, objFolder As Object
  Dim EmailCount As Integer
  Set objOutlook = CreateObject("Outlook.Application")
  Set objnSpace = objOutlook.GetNamespace("MAPI")

  On Error Resume Next

  Set objFolder = objnSpace.Folders("My Personal Emails").Folders("spam")
  If Err.Number <> 0 Then
    Err.Clear
    MsgBox "No such folder."
    Exit Sub
  End If

  Select Case Weekday(dteDate)
    Case vbMonday
      dteDate = Date
    End Select

  For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If

  EmailCount = objFolder.Items.Count
  Set objFolder = Nothing
  Set objnSpace = Nothing
  Set objOutlook = Nothing

  MsgBox "Number of emails in the folder: " _
    & EmailCount, , "Number of spam messages sent on a Monday: " & Count
End Sub

Body:
Whilst debugging drop the on error resume next.

It hides the errors. You can put it back later if you have to.

It's not a great idea to ignore errors, better to handle the errors explicitly.

One thing that struck me:

For Each MapiItem In MapiFolderInbox.Messages
    If MapiItem.TimeReceived = Date Then
      Count = Count + 1
      Next MapiItem
    End If

Should be

For Each MapiItem In MapiFolderInbox.Messages
  If MapiItem.TimeReceived = Date Then
    Count = Count + 1
  End If
Next MapiItem

Other than that it looks OK to me.


问:
How to fix timeout for packages on `npm install`?
When I run npm install it seems to work fine until part way installing packages. It seems to have no problem with the first half, but then after a while it will fail to be able to reach other packages. I just get the repeating errors, eg:

```<code>npm http request GET https://registry.npmjs.org/react-hot-loader
npm info attempt registry request try #3 at 6:43:34 AM
npm http request GET https://registry.npmjs.org/react-tap-event-plugin
npm info attempt registry request try #3 at 6:43:34 AM
npm http request GET https://registry.npmjs.org/react-test-renderer
</code>```

etc.

It will continue to do this for an hour and and then the install will fail.

The install breaks at a different package each time so I don't think it's a problem with a particular file.

I can access these files fine with my browser and curl.

My work has a firewall but this domain is whitelisted.

Would anyone know what I could do to get this to work or what could be causing it?

答:
I solved the timeout issue by executing these commands:

```<code>rm package-lock.json
npm i
</code>```

Body:
When I run npm install it seems to work fine until part way installing packages. It seems to have no problem with the first half, but then after a while it will fail to be able to reach other packages. I just get the repeating errors, eg:

npm http request GET https://registry.npmjs.org/react-hot-loader
npm info attempt registry request try #3 at 6:43:34 AM
npm http request GET https://registry.npmjs.org/react-tap-event-plugin
npm info attempt registry request try #3 at 6:43:34 AM
npm http request GET https://registry.npmjs.org/react-test-renderer

etc.

It will continue to do this for an hour and and then the install will fail.

The install breaks at a different package each time so I don't think it's a problem with a particular file.

I can access these files fine with my browser and curl.

My work has a firewall but this domain is whitelisted.

Would anyone know what I could do to get this to work or what could be causing it?

Body:
I solved the timeout issue by executing these commands:

rm package-lock.json
npm i


问:
Losing Access Tokens on refreshing redirected page
So the access token authentication with Spotify works fine if I log in via the authentication flow. But if I press refresh on my 'Home' page (the page that the authentication redirects to), without logging out and logging back in. My token variable that's suppose to store the access token becomes a null value in the console. I notice other Spotify API built web-apps allow users to be automatically logged in when you enter their url without having to redirect the user to the Spotify login authentication. I'm not sure how to get to that point.</p>

答: Any variable that you have in memory will be lost on refresh. One solution could be to save the token in local storage right when you get it, and check if it exists when you load the application. Local storage persists refreshes and revisits so it would be the quickest solution. After that you could check more secure routes.</p>


问:
Java simple login system using a for loop
I'm trying to learn how loops work, here's a very simple login system I wrote. There seems to be an error with this code though

```<code>import java.util.Scanner;

public class Main {
static String password, loginPass, username, loginUser;
static Scanner sc = new Scanner(System.in);

static boolean login = true;
static boolean checkvalid = false;

public static void main(String[] args) {
    System.out.println("Enter a desired username: \n");
    username = sc.nextLine();

    System.out.println("Enter a desired password: \n");
    password = sc.nextLine();

    System.out.println("Thank you, please log in.\n");
    while (login) {
        checkvalid = false;
        System.out.println(" ------------------ \n" + "Username: \n");
        loginUser = sc.nextLine();
        System.out.println("Password: \n");
        loginPass = sc.nextLine();

        if (loginUser.equals(password) && (loginPass.equals(username))) {
            checkvalid = true;
        } else {
            checkvalid = false;
        }
    }
    for (;;){
        if (checkvalid = true){
            login = false;
            System.out.println("You have logged in.");

        }else if (checkvalid = false){
            System.out.println("Incorrect username or password");
            login = true;
        }
    }
}

}
</code>```

It repeatedly asks for the "desired login credentials" that I entered before. Please help me resolve this problem, thank you!)

答:
Try this :D</p>

```<code>           Scanner sc = new Scanner(System.in);

            String x = sc.nextLine();// Put the user

            while(!x.equals("John")) {
                System.out.println("Wrong User, try again :D");
                x = sc.nextLine();

            }
            sc.close();
</code>```

Body:
I'm trying to learn how loops work, here's a very simple login system I wrote. There seems to be an error with this code though

import java.util.Scanner;

public class Main {
static String password, loginPass, username, loginUser;
static Scanner sc = new Scanner(System.in);

static boolean login = true;
static boolean checkvalid = false;

public static void main(String[] args) {
    System.out.println("Enter a desired username: \n");
    username = sc.nextLine();

    System.out.println("Enter a desired password: \n");
    password = sc.nextLine();

    System.out.println("Thank you, please log in.\n");
    while (login) {
        checkvalid = false;
        System.out.println(" ------------------ \n" + "Username: \n");
        loginUser = sc.nextLine();
        System.out.println("Password: \n");
        loginPass = sc.nextLine();

        if (loginUser.equals(password) && (loginPass.equals(username))) {
            checkvalid = true;
        } else {
            checkvalid = false;
        }
    }
    for (;;){
        if (checkvalid = true){
            login = false;
            System.out.println("You have logged in.");

        }else if (checkvalid = false){
            System.out.println("Incorrect username or password");
            login = true;
        }
    }
}

}

It repeatedly asks for the "desired login credentials" that I entered before. Please help me resolve this problem, thank you!)

Body:
Try this :D

           Scanner sc = new Scanner(System.in);

            String x = sc.nextLine();// Put the user

            while(!x.equals("John")) {
                System.out.println("Wrong User, try again :D");
                x = sc.nextLine();

            }
            sc.close();


问:
Parse JSON Data in Swift from API Call "Value of type 'Any?' has no subscripts"
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > tags. When I navigate to media it works, but when I add faces i receive the "Value of type 'Any?' has no subscripts" error.

I know this has been covered before on Stackoverflow but I can't seem to find out what is wrong. Any help is appreciated!

```<code>let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any];

//                        print(dictionary!["media"]) //this line works

                        print(dictionary!["media"]["faces"]) // this line does not work
</code>```

The API returned data looks something like this

```<code>Optional({
    checksum = 44efb3256385bfe62425c5fde195a3352e814ff6d900058e47a07b2cd7654252;
    duration = "00:00:00";
    faces =     (
                {
            angle = "1.2222";
            "appearance_id" = 0;
            "detection_score" = 1;
            duration = "00:00:00";
            "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
            height = "74.31999999999999";
            "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
            "person_id" = "";
            points =             (
                                {
                    name = "basic eye left";
                    type = 512;
                    x = "85.16";
                    y = "86.62";
                },
</code>```

答:
You need to cast the value returned from dictionary!["media"] as another Dictionary to be able to do this. Try this:

if let data = data,
    let dictionary = try JSONSerialization.jsonObject(with: data, options:.mutableContainers) as? [String: Any],
    let media = dictionary["media"] as? [String: Any] {
    print(media["faces"])
}
```

Body:
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > tags. When I navigate to media it works, but when I add faces i receive the "Value of type 'Any?' has no subscripts" error.

I know this has been covered before on Stackoverflow but I can't seem to find out what is wrong. Any help is appreciated!

let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any];

//                        print(dictionary!["media"]) //this line works

                        print(dictionary!["media"]["faces"]) // this line does not work

The API returned data looks something like this

Optional({
    checksum = 44efb3256385bfe62425c5fde195a3352e814ff6d900058e47a07b2cd7654252;
    duration = "00:00:00";
    faces =     (
                {
            angle = "1.2222";
            "appearance_id" = 0;
            "detection_score" = 1;
            duration = "00:00:00";
            "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
            height = "74.31999999999999";
            "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
            "person_id" = "";
            points =             (
                                {
                    name = "basic eye left";
                    type = 512;
                    x = "85.16";
                    y = "86.62";
                },


问:
Running a function in parallel and saving the return in a list using python
I have a function that scrapes href link form a particular page and returns the result. I want to call this function in a parallel way to save time. I have visited this problem Running same function for multiple files in parallel in python
But the challenge is that I need to save the return element in a list. How can I do that? Here is my code snippet.</p>

```<code>url = "https://www.programmableweb.com/category/all/apis"
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data,'html.parser')

#function to scrape individual pages
def scrap_api_url(i):
    print(i)
    page_url = "https://www.programmableweb.com" + mid_url + '=' + str(i)
    response = requests.get(page_url)
    data = response.text
    soup = BeautifulSoup(data, 'html.parser')
    all_api = soup.find_all('tr', class_ = re.compile('^(even|odd)$'))
    return all_api

url_tag = soup.find('a',{'title' : 'Go to next page'})
mid_url = url_tag.get('href').split('=')[0]
threads=[]

#calling functions
if __name__ == '__main__':
    inputs = [i for i in range(851)]
    for item in inputs:
        print('Thread Started :: ', item)
        t = threading.Thread(target = scrap_api_url, args=(item,))
        threads.append(t)
        t.start()
h = []
for t in threads:
    h.append(t.join())
</code>```

答:
You can use the ThreadPoolExecutor map method:

import re
from concurrent.futures import ThreadPoolExecutor

import requests
from bs4 import BeautifulSoup

def main():
    url = "https://www.programmableweb.com/category/all/apis"
    response = requests.get(url)
    data = response.text
    soup = BeautifulSoup(data,'html.parser')

    url_tag = soup.find('a',{'title' : 'Go to next page'})
    mid_url = url_tag.get('href').split('=')[0]

    # function to scrape individual pages
    def scrap_api_url(i):
        print(i)
        page_url = "https://www.programmableweb.com" + mid_url + '=' + str(i)
        response = requests.get(page_url)
        data = response.text
        soup = BeautifulSoup(data, 'html.parser')
        all_api = soup.find_all('tr', class_=re.compile('^(even|odd)$'))
        return all_api

    inputs = [i for i in range(851)]
    with ThreadPoolExecutor() as executor:
        future_results = executor.map(scrap_api_url, inputs)
        results = [result for result in future_results]

    print(results)

#calling functions
if __name__ == '__main__':
    main()

```

Body:
I have a function that scrapes href link form a particular page and returns the result. I want to call this function in a parallel way to save time. I have visited this problem Running same function for multiple files in parallel in python
But the challenge is that I need to save the return element in a list. How can I do that? Here is my code snippet.

url = "https://www.programmableweb.com/category/all/apis"
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data,'html.parser')

#function to scrape individual pages
def scrap_api_url(i):
    print(i)
    page_url = "https://www.programmableweb.com" + mid_url + '=' + str(i)
    response = requests.get(page_url)
    data = response.text
    soup = BeautifulSoup(data, 'html.parser')
    all_api = soup.find_all('tr', class_ = re.compile('^(even|odd)$'))
    return all_api

url_tag = soup.find('a',{'title' : 'Go to next page'})
mid_url = url_tag.get('href').split('=')[0]
threads=[]

#calling functions
if __name__ == '__main__':
    inputs = [i for i in range(851)]
    for item in inputs:
        print('Thread Started :: ', item)
        t = threading.Thread(target = scrap_api_url, args=(item,))
        threads.append(t)
        t.start()
h = []
for t in threads:
    h.append(t.join())


问:
How to use JWT from social auth to fetch the respective user of django.contrib.models.user
Maybe I am missing something fundamental about JWT theory and concept, but I tear my hair on my head trying to understand the following.

Right now I have a login and signup powered by REST framework JWT Auth. The flow is like this:

I create a django.contrib.auth.models.user instance

Call REST framework JWT Auth endpoint to get a token based on username and psw

In my settings.py I have

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ), ...
}
</code>```

Also, I have MyModel which has a foreign key referencing User which stores some user data (say, her shopping list). So I use the JWT token to fetch the user shopping list.

Now I need to add social auth feature for the users. Following this post, I get the token from FB. But the problem is that I do not undestand how should I associate this token with a django.contrib.auth.models.user instance. More specifically,

How do I actually fill in the fields first_name, last_name, email etc... of the User instance? I undestand that this info should be somehow included in the payload part of the JWT?

When authenticating views to fetch user shopping list, how should I tell Django that the token I included in the header is actually originated from FB, rather than REST framework JWT Auth ?

UPDATE.

Do I understand correctly, that, for example, in case of FB, I should just send a request to FB to get the token along with email, name, and say, photo of the user, and in case of success, I should fall back to the procedure desribed in the beginning of the question (create my 'native' django.contrib.auth.user instance, obtain Django JWT token) and forget about FB token at all ? But that would mean that the password field in my User model should become nullable.

答:
You are almost correct .

Those are the steps to follow.

Pass the token to your django rest server and server will verify the token and return decoded token. Please see this link .

After successful validation, you should either create a user by ID (get from above link's response) or fetch user by ID. All required information will be in response of above link. You just need to map the keys to your django model columns.

During creation of user you should set unusable password for that user instead of null. Please see django user manager to set unusable password.

Now you get your desire user from your system. You can easily generate JWT token from your system for that user and respond back that own system generated token to your user.

Each next subsequent API call; your rest_framework_jwt.authentication.JSONWebTokenAuthentication will validate, fetch user and attach that user to request.

You can experiment with your jwt token here. That token can be decoded as json payload and you can access that json by key and value.

Body:
Maybe I am missing something fundamental about JWT theory and concept, but I tear my hair on my head trying to understand the following.

Right now I have a login and signup powered by REST framework JWT Auth. The flow is like this:

I create a django.contrib.auth.models.user instance

Call REST framework JWT Auth endpoint to get a token based on username and psw

In my settings.py I have

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ), ...
}

Also, I have MyModel which has a foreign key referencing User which stores some user data (say, her shopping list). So I use the JWT token to fetch the user shopping list.

Now I need to add social auth feature for the users. Following this post, I get the token from FB. But the problem is that I do not undestand how should I associate this token with a django.contrib.auth.models.user instance. More specifically,

How do I actually fill in the fields first_name, last_name, email etc... of the User instance? I undestand that this info should be somehow included in the payload part of the JWT?

When authenticating views to fetch user shopping list, how should I tell Django that the token I included in the header is actually originated from FB, rather than REST framework JWT Auth ?

UPDATE.

Do I understand correctly, that, for example, in case of FB, I should just send a request to FB to get the token along with email, name, and say, photo of the user, and in case of success, I should fall back to the procedure desribed in the beginning of the question (create my 'native' django.contrib.auth.user instance, obtain Django JWT token) and forget about FB token at all ? But that would mean that the password field in my User model should become nullable.


问:
How to add event listener to the div element accessed with ref using react and typescript?
i want to add event listener to the div element using ref.

I add ref div_ref to Wrapper div and access that div_ref in  enableDragEventListeners method to add event listeners to that on componentmount.

Below is my code,

```<code>const SomeComponent: React.FC<any> = props => {
    const div_ref  = React.useRef(null);
    React.useEffect(() => {
        const enableDragEventListeners = () => {
            const div = dropRef.current;
            if (div) {
                div.addEventListener('dragenter', handleDragIn); // get error here
                div.addEventListener('dragleave', handleDragOut); //error here
                div.addEventListener('dragover', handleDrag);//error here
                div.addEventListener('drop', handleDrop);//error here
            }
        };
        enableDragEventListeners();
    }, []);

    return (
        <Wrapper ref={div_ref}>
           {dragging && <Overlay>{props.children}</Overlay>}
        </Wrapper>
    );
}
</code>```

But i get error property addEventListener doesnt exist on type 'never'. could someone help me fix this. thanks.

Edit: Complete code looks like this...i am implementing a draganddrop component so wrapping this around a component that wants to use this will be able to drag and drop files into it.

```<code>const DragAndDrop: React.FC<any> = props => {
    const dropRef = useRef(null);
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);
    React.useEffect(() => {
        // componentDidMount()
        const handleDrag = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
            }
        };

        const handleDragIn = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev + 1);
                if (e.dataTransfer.files) {
                    setDragging(true);
                }
            }
        };

        const handleDragOut = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev - 1);
                if (dragCounter === 0) {
                    setDragging(false);
                }
            }
        };

        const handleDrop = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragging(false);
                if (e.dataTransfer.files && e.dataTransfer.files.length > 0){
                    props.handle_drop(e);
                    e.dataTransfer.clearData();
                   setDragCounter(0);
                }
            }
       };
       const enableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           if (div) {
               div.addEventListener('dragenter', handleDragIn);
               div.addEventListener('dragleave', handleDragOut);
               div.addEventListener('dragover', handleDrag);
               div.addEventListener('drop', handleDrop);
           }
       };
       const disableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           div.removeEventListener('dragenter', handleDragIn);
           div.removeEventListener('dragleave', handleDragOut);
           div.removeEventListener('dragover', handleDrag);
           div.removeEventListener('drop', handleDrop);
       };
       setDragCounter(0);
       enableDragEventListeners();
       return () => {
           // componentWillUnmount()
           disableDragEventListeners();
       };
   }, [dragCounter, props]);

   return (
       <wrapper ref={dropRef}>
           {dragging && <Overlay>{props.children}</Overlay>}
       </Wrapper>
   );
};

const DropZone = styled.div``;

export default DragAndDrop;
</code>```

答:
I am not sure why are you manually adding those event listeners via the component's ref, but since you are adding those event listeners when the component is mounted, you can bind those methods to the synthetic events.</p>

```<code><Wrapper
  ref={div_ref}
  onDragEnter={handleDragIn}
  onDragLeave={handleDragOut}
  onDragover={handleDrag};
  onDrop={handleDrop}
>
</code>```

Body:
i want to add event listener to the div element using ref.

I add ref div_ref to Wrapper div and access that div_ref in  enableDragEventListeners method to add event listeners to that on componentmount.

Below is my code,

const SomeComponent: React.FC<any> = props => {
    const div_ref  = React.useRef(null);
    React.useEffect(() => {
        const enableDragEventListeners = () => {
            const div = dropRef.current;
            if (div) {
                div.addEventListener('dragenter', handleDragIn); // get error here
                div.addEventListener('dragleave', handleDragOut); //error here
                div.addEventListener('dragover', handleDrag);//error here
                div.addEventListener('drop', handleDrop);//error here
            }
        };
        enableDragEventListeners();
    }, []);

    return (
        <Wrapper ref={div_ref}>
           {dragging && <Overlay>{props.children}</Overlay>}
        </Wrapper>
    );
}

But i get error property addEventListener doesnt exist on type 'never'. could someone help me fix this. thanks.

Edit: Complete code looks like this...i am implementing a draganddrop component so wrapping this around a component that wants to use this will be able to drag and drop files into it.

const DragAndDrop: React.FC<any> = props => {
    const dropRef = useRef(null);
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);
    React.useEffect(() => {
        // componentDidMount()
        const handleDrag = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
            }
        };

        const handleDragIn = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev + 1);
                if (e.dataTransfer.files) {
                    setDragging(true);
                }
            }
        };

        const handleDragOut = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragCounter((prev: number) => prev - 1);
                if (dragCounter === 0) {
                    setDragging(false);
                }
            }
        };

        const handleDrop = (e: any) => {
            if (!props.loading) {
                e.preventDefault();
                e.stopPropagation();
                setDragging(false);
                if (e.dataTransfer.files && e.dataTransfer.files.length > 0){
                    props.handle_drop(e);
                    e.dataTransfer.clearData();
                   setDragCounter(0);
                }
            }
       };
       const enableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           if (div) {
               div.addEventListener('dragenter', handleDragIn);
               div.addEventListener('dragleave', handleDragOut);
               div.addEventListener('dragover', handleDrag);
               div.addEventListener('drop', handleDrop);
           }
       };
       const disableDragEventListeners = () => {
           const div = dropRef && dropRef.current;
           div.removeEventListener('dragenter', handleDragIn);
           div.removeEventListener('dragleave', handleDragOut);
           div.removeEventListener('dragover', handleDrag);
           div.removeEventListener('drop', handleDrop);
       };
       setDragCounter(0);
       enableDragEventListeners();
       return () => {
           // componentWillUnmount()
           disableDragEventListeners();
       };
   }, [dragCounter, props]);

   return (
       <wrapper ref={dropRef}>
           {dragging && <Overlay>{props.children}</Overlay>}
       </Wrapper>
   );
};

const DropZone = styled.div``;

export default DragAndDrop;

Body:
I am not sure why are you manually adding those event listeners via the component's ref, but since you are adding those event listeners when the component is mounted, you can bind those methods to the synthetic events.

<Wrapper
  ref={div_ref}
  onDragEnter={handleDragIn}
  onDragLeave={handleDragOut}
  onDragover={handleDrag};
  onDrop={handleDrop}
>