问:
What happens if I have expired additional certificate in the chain with alternate trust path?
I have a certificate, issued by Sectigo (former Comodo Positive SSL product). It's in good condition and expires in 1 year and 7 months. This certificate issued by Sectigo RSA Domain Validation Secure Server CA. There are two intermediate certificates in the CA chain, provided by the vendor: the closest Sectigo RSA Domain Validation Secure Server CA and next intermediate USERTrust RSA Certification Authority, which expires on May 30, 2020.

Intermediate USERTrust RSA Certification Authority has very close expiration date and signed by trusted by browsers AddTrust External CA Root.

Meanwhile the closest to my domain certificate intermediate Sectigo RSA Domain Validation Secure Server CA signed by another root with same name USERTrust RSA Certification Authority, but this is different CA certificate than mentioned before. And this root is trusted by common browsers.

I've tried to check it by ssllabs.com's checker and I see that today all is ok. But I don't understand about future. What happens after May 30 in case if I leave expired intermediate in the chain? Or is it better to exclude this intermediate from the chain beforehand?

答:
That day has come. On 30th May 2020 the USERTrust RSA Certification Authority has expired and I see that modern browsers works correctly, but most automatics isn't (e.g. curl from Ubuntu 18.04 LTS console and from PHP and Ruby scripts).

One of SSL distributers said:

Previously they [Sectigo] assured everyone that no issues will be. However, the reality is that some legacy servers/devices are affected.

That is a ridiculous situation. We pointed their attention to the expiring AddTrust RSA/ECC multiple times within a year and each time Sectigo assured us no issues will be.

Sectigo issued faq page.

The right chains in my case (Sectigo DV product / Positive SSL):

For RSA:

```<code># Subject: /C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA
# Algo: RSA, key size: 2048
# Issuer: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority
# Not valid before: 2018-11-02T00:00:00Z
# Not valid after: 2030-12-31T23:59:59Z
# SHA-1 Fingerprint: 33:E4:E8:08:07:20:4C:2B:61:82:A3:A1:4B:59:1A:CD:25:B5:F0:DB
# SHA-256 Fingerprint: 7F:A4:FF:68:EC:04:A9:9D:75:28:D5:08:5F:94:90:7F:4D:1D:D1:C5:38:1B:AC:DC:83:2E:D5:C9:60:21:46:76
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KUErmgQfky3xxzlIPK1aEn8=
-----END CERTIFICATE-----

# Subject: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority
# Algo: RSA, key size: 4096
# Issuer: /C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services
# Not valid before: 2019-03-12T00:00:00Z
# Not valid after: 2028-12-31T23:59:59Z
# SHA-1 Fingerprint: D8:9E:3B:D4:3D:5D:90:9B:47:A1:89:77:AA:9D:5C:E3:6C:EE:18:4C
# SHA-256 Fingerprint: 68:B9:C7:61:21:9A:5B:1F:01:31:78:44:74:66:5D:B6:1B:BD:B1:09:E0:0F:05:CA:9F:74:24:4E:E5:F5:F5:2B
-----BEGIN CERTIFICATE-----
MIIFgTCCBGmgAwIBAgIQOXJEOvkit1HX02wQ3TE1lTANBgkqhkiG9w0BAQwFADB7
MQswCQYDVQQGEwJHQjEbMBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYD
VQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UE
AwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTE5MDMxMjAwMDAwMFoXDTI4
MTIzMTIzNTk1OVowgYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5
MRQwEgYDVQQHEwtKZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBO
ZXR3b3JrMS4wLAYDVQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgBJlFzYOw9sI
s9CsVw127c0n00ytUINh4qogTQktZAnczomfzD2p7PbPwdzx07HWezcoEStH2jnG
vDoZtF+mvX2do2NCtnbyqTsrkfjib9DsFiCQCT7i6HTJGLSR1GJk23+jBvGIGGqQ
Ijy8/h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BHaIkU4MiRTOok3JMrO66BQavHHxW/BBC5gA
CiIDEOUMsfnNkjcZ7Tvx5Dq2+UUTJnWvu6rvP3t3O9LEApE9GQDTF1w52z97GA1F
zZOFli9d31kWTz9RvdVFGD/tSo7oBmF0Ixa1DVBzJ0RHfxBdiSprhTEUxOipakyA
vGp4z7h/jnZymQyd/teRCBaho1+V
-----END CERTIFICATE-----
</code>```

For ECC:

```<code># Subject: /C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo ECC Domain Validation Secure Server CA
# Algo: EC secp256r1, key size: 256
# Issuer: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust ECC Certification Authority
# Not valid before: 2018-11-02T00:00:00Z
# Not valid after: 2030-12-31T23:59:59Z
# SHA-1 Fingerprint: E8:49:90:CB:9B:F8:E3:AB:0B:CA:E8:A6:49:CB:30:FE:4D:C4:D7:67
# SHA-256 Fingerprint: 61:E9:73:75:E9:F6:DA:98:2F:F5:C1:9E:2F:94:E6:6C:4E:35:B6:83:7C:E3:B9:14:D2:24:5C:7F:5F:65:82:5F
-----BEGIN CERTIFICATE-----
MIIDqDCCAy6gAwIBAgIRAPNkTmtuAFAjfglGvXvh9R0wCgYIKoZIzj0EAwMwgYgx
CzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtKZXJz
ZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYDVQQD
EyVVU0VSVHJ1c3QgRUNDIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTE4MTEw
MjAwMDAwMFoXDTMwMTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAkdCMRswGQYDVQQI
ExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGDAWBgNVBAoT
D1NlY3RpZ28gTGltaXRlZDE3MDUGA1UEAxMuU2VjdGlnbyBFQ0MgRG9tYWluIFZh
bGlkYXRpb24gU2VjdXJlIFNlcnZlciBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEH
A0IABHkYk8qfbZ5sVwAjBTcLXw9YWsTef1Wj6R7W2SUKiKAgSh16TwUwimNJE4xk
IQeV/To14UrOkPAY9z2vaKb71EijggFuMIIBajAfBgNVHSMEGDAWgBQ64QmG1M8Z
wpZ2dEl23OA1xmNjmjAdBgNVHQ4EFgQU9oUKOxGG4QR9DqoLLNLuzGR7e64wDgYD
VR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYB
BQUHAwEGCCsGAQUFBwMCMBsGA1UdIAQUMBIwBgYEVR0gADAIBgZngQwBAgEwUAYD
VR0fBEkwRzBFoEOgQYY/aHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VTRVJUcnVz
dEVDQ0NlcnRpZmljYXRpb25BdXRob3JpdHkuY3JsMHYGCCsGAQUFBwEBBGowaDA/
BggrBgEFBQcwAoYzaHR0cDovL2NydC51c2VydHJ1c3QuY29tL1VTRVJUcnVzdEVD
Q0FkZFRydXN0Q0EuY3J0MCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC51c2VydHJ1
c3QuY29tMAoGCCqGSM49BAMDA2gAMGUCMEvnx3FcsVwJbZpCYF9z6fDWJtS1UVRs
cS0chWBNKPFNpvDKdrdKRe+oAkr2jU+ubgIxAODheSr2XhcA7oz9HmedGdMhlrd9
4ToKFbZl+/OnFFzqnvOhcjHvClECEQcKmc8fmA==
-----END CERTIFICATE-----

# Subject: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust ECC Certification Authority
# Algo: EC secp384r1, key size: 384
# Issuer: /C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services
# Not valid before: 2019-03-12T00:00:00Z
# Not valid after: 2028-12-31T23:59:59Z
# SHA-1 Fingerprint: CA:77:88:C3:2D:A1:E4:B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EEKDAmMCQG
CCsGAQUFBzABhhhodHRwOi8vb2NzcC5jb21vZG9jYS5jb20wDQYJKoZIhvcNAQEM
BQADggEBABns652JLCALBIAdGN5CmXKZFjK9Dpx1WywV4ilAbe7/ctvbq5AfjJXy
ij0IckKJUAfiORVsAYfZFhr1wHUrxeZWEQff2Ji8fJ8ZOd+LygBkc7xGEJuTI42+
FsMuCIKchjN0djsoTI0DQoWz4rIjQtUfenVqGtF8qmchxDM6OW1TyaLtYiKou+JV
bJlsQ2uRl9EMC5MCHdK8aXdJ5htN978UeAOwproLtOGFfy/cQjutdAFI3tZs4RmY
CV4Ks2dH/hzg1cEo70qLRDEmBDeNiXQ2Lu+lIg+DdEmSx/cQwgwp+7e9un/jX9Wf
8qn0dNW44bOwgeThpWOjzOoEeJBuv/c=
-----END CERTIFICATE-----
</code>```

Body:
That day has come. On 30th May 2020 the USERTrust RSA Certification Authority has expired and I see that modern browsers works correctly, but most automatics isn't (e.g. curl from Ubuntu 18.04 LTS console and from PHP and Ruby scripts).

One of SSL distributers said:

Previously they [Sectigo] assured everyone that no issues will be. However, the reality is that some legacy servers/devices are affected.

That is a ridiculous situation. We pointed their attention to the expiring AddTrust RSA/ECC multiple times within a year and each time Sectigo assured us no issues will be.

Sectigo issued faq page.

The right chains in my case (Sectigo DV product / Positive SSL):

For RSA:

# Subject: /C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo RSA Domain Validation Secure Server CA
# Algo: RSA, key size: 2048
# Issuer: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority
# Not valid before: 2018-11-02T00:00:00Z
# Not valid after: 2030-12-31T23:59:59Z
# SHA-1 Fingerprint: 33:E4:E8:08:07:20:4C:2B:61:82:A3:A1:4B:59:1A:CD:25:B5:F0:DB
# SHA-256 Fingerprint: 7F:A4:FF:68:EC:04:A9:9D:75:28:D5:08:5F:94:90:7F:4D:1D:D1:C5:38:1B:AC:DC:83:2E:D5:C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4K
00u/I5sUKUErmgQfky3xxzlIPK1aEn8=
-----END CERTIFICATE-----

# Subject: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority
# Algo: RSA, key size: 4096
# Issuer: /C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services
# Not valid before: 2019-03-12T00:00:00Z
# Not valid after: 2028-12-31T23:59:59Z
# SHA-1 Fingerprint: D8:9E:3B:D4:3D:5D:90:9B:47:A1:89:77:AA:9D:5C:E3:6C:EE:18:4C
# SHA-256 Fingerprint: 68:B9:C7:61:21:9A:5B:1F:01:31:78:44:74:66:5D:B6:1B:BD:B1:09:E0:0F:05:CA:9F:74:24:4E:E5:F5:F5:2B
-----BEGIN CERTIFICATE-----
MIIFgTCCBGmgAwIBAgIQOXJEOvkit1HX02wQ3TE1lTANBgkqhkiG9w0BAQwFADB7
MQswCQYDVQQGEwJHQjEbMBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYD
VQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UE
AwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTE5MDMxMjAwMDAwMFoXDTI4
MTIzMTIzNTk1OVowgYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5
MRQwEgYDVQQHEwtKZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBO
ZXR3b3JrMS4wLAYDVQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0
aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgBJlFzYOw9sI
s9CsVw127c0n00ytUINh4qogTQktZAnczomfzD2p7PbPwdzx07HWezcoEStH2jnG
vDoZtF+mvX2do2NCtnbyqTsrkfjib9DsFiCQCT7i6HTJGLSR1GJk23+jBvGIGGq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O/WIu6pKJmBHaIkU4MiRTOok3JMrO66BQavHHxW/BBC5gA
CiIDEOUMsfnNkjcZ7Tvx5Dq2+UUTJnWvu6rvP3t3O9LEApE9GQDTF1w52z97GA1F
zZOFli9d31kWTz9RvdVFGD/tSo7oBmF0Ixa1DVBzJ0RHfxBdiSprhTEUxOipakyA
vGp4z7h/jnZymQyd/teRCBaho1+V
-----END CERTIFICATE-----

For ECC:

# Subject: /C=GB/ST=Greater Manchester/L=Salford/O=Sectigo Limited/CN=Sectigo ECC Domain Validation Secure Server CA
# Algo: EC secp256r1, key size: 256
# Issuer: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust ECC Certification Authority
# Not valid before: 2018-11-02T00:00:00Z
# Not valid after: 2030-12-31T23:59:59Z
# SHA-1 Fingerprint: E8:49:90:CB:9B:F8:E3:AB:0B:CA:E8:A6:49:CB:30:FE:4D:C4:D7:67
# SHA-256 Fingerprint: 61:E9:73:75:E9:F6:DA:98:2F:F5:C1:9E:2F:94:E6:6C:4E:35:B6:83:7C:E3:B9:14:D2:24:5C:7F:5F:65:82:5F
-----BEGIN CERTIFICATE-----
MIIDqDCCAy6gAwIBAgIRAPNkTmtuAFAjfglGvXvh9R0wCgYIKoZIzj0EAwMwgYgx
CzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtKZXJz
ZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYDVQQD
EyVVU0VSVHJ1c3QgRUNDIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTE4MTEw
MjAwMDAwMFoXDTMwMTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAkdCMRswGQYDVQQI
ExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGDAWBgNVBAoT
D1NlY3RpZ28gTGltaXRlZDE3MDUGA1UEAxMuU2VjdGlnbyBFQ0MgRG9tYWluIFZh
bGlkYXRpb24gU2VjdXJlIFNlcnZlciBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEH
A0IABHkYk8qfbZ5sVwAjBTcLXw9YWsTef1Wj6R7W2SUKiKAgSh16TwUwimNJE4xk
IQeV/To14UrOkPAY9z2vaKb71EijggFuMIIBajAfBgNVHSMEGDAWgBQ64QmG1M8Z
wpZ2dEl23OA1xmNjmjAdBgNVHQ4EFgQU9oUKOxGG4QR9DqoLLNLuzGR7e64wDgYD
VR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYB
BQUHAwEGCCsGAQUFBwMCMBsGA1UdIAQUMBIwBgYEVR0gADAIBgZngQwBAgEwUAYD
VR0fBEkwRzBFoEOgQYY/aHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VTRVJUcnVz
dEVDQ0NlcnRpZmljYXRpb25BdXRob3JpdHkuY3JsMHYGCCsGAQUFBwEBBGowaDA/
BggrBgEFBQcwAoYzaHR0cDovL2NydC51c2VydHJ1c3QuY29tL1VTRVJUcnVzdEVD
Q0FkZFRydXN0Q0EuY3J0MCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC51c2VydHJ1
c3QuY29tMAoGCCqGSM49BAMDA2gAMGUCMEvnx3FcsVwJbZpCYF9z6fDWJtS1UVRs
cS0chWBNKPFNpvDKdrdKRe+oAkr2jU+ubgIxAODheSr2XhcA7oz9HmedGdMhlrd9
4ToKFbZl+/OnFFzqnvOhcjHvClECEQcKmc8fmA==
-----END CERTIFICATE-----

# Subject: /C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust ECC Certification Authority
# Algo: EC secp384r1, key size: 384
# Issuer: /C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=AAA Certificate Services
# Not valid before: 2019-03-12T00:00:00Z
# Not valid after: 2028-12-31T23:59:59Z
# SHA-1 Fingerprint: CA:77:88:C3:2D:A1:E4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AQEEKDAmMCQG
CCsGAQUFBzABhhhodHRwOi8vb2NzcC5jb21vZG9jYS5jb20wDQYJKoZIhvcNAQEM
BQADggEBABns652JLCALBIAdGN5CmXKZFjK9Dpx1WywV4ilAbe7/ctvbq5AfjJXy
ij0IckKJUAfiORVsAYfZFhr1wHUrxeZWEQff2Ji8fJ8ZOd+LygBkc7xGEJuTI42+
FsMuCIKchjN0djsoTI0DQoWz4rIjQtUfenVqGtF8qmchxDM6OW1TyaLtYiKou+JV
bJlsQ2uRl9EMC5MCHdK8aXdJ5htN978UeAOwproLtOGFfy/cQjutdAFI3tZs4RmY
CV4Ks2dH/hzg1cEo70qLRDEmBDeNiXQ2Lu+lIg+DdEmSx/cQwgwp+7e9un/jX9Wf
8qn0dNW44bOwgeThpWOjzOoEeJBuv/c=
-----END CERTIFICATE-----


来源: stackexchange

问:
How do I find the source code for a method in Pandas?
The following is the GitHub link for Python's Pandas package.

https://github.com/pandas-dev/pandas

I would like to find the source code for a specific method (for instance, iterrows). What would be the file path for this?

答:
Python, in general, is easily introspect-able. You can use the inspect module if you want to do this programatically. so for example:

```<code>In [8]: import pandas as pd

In [9]: import inspect

In [10]: pd.DataFrame.iterrows
Out[10]: <function pandas.core.frame.DataFrame.iterrows(self)>

In [11]: inspect.getsourcefile(pd.DataFrame.iterrows)
Out[11]: '/Users/juan/anaconda3/envs/py38/lib/python3.8/site-packages/pandas/core/frame.py'
</code>```

So you can go to pandas/core/frame.py. Note, this won't always work if it is, say, a method written in C as an extension. But it should for Python source code. In fact, you can even get the source code lines using inspect.getsourcelines, which returns a tuple of lines, line_number:

```<code>In [12]: inspect.getsourcelines(pd.DataFrame.iterrows)
Out[12]:
(['    def iterrows(self):\n',
  '        """\n',
  '        Iterate over DataFrame rows as (index, Series) pairs.\n',
  '\n',
  '        Yields\n',
  '        ------\n',
  '        index : label or tuple of label\n',
  '            The index of the row. A tuple for a `MultiIndex`.\n',
  '        data : Series\n',
  '            The data of the row as a Series.\n',
  '\n',
  '        it : generator\n',
  '            A generator that iterates over the rows of the frame.\n',
  '\n',
  '        See Also\n',
  '        --------\n',
  '        itertuples : Iterate over DataFrame rows as namedtuples of the values.\n',
  '        items : Iterate over (column name, Series) pairs.\n',
  '\n',
  '        Notes\n',
  '        -----\n',
  '\n',
  '        1. Because ``iterrows`` returns a Series for each row,\n',
  '           it does **not** preserve dtypes across the rows (dtypes are\n',
  '           preserved across columns for DataFrames). For example,\n',
  '\n',
  "           >>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])\n",
  '           >>> row = next(df.iterrows())[1]\n',
  '           >>> row\n',
  '           int      1.0\n',
  '           float    1.5\n',
  '           Name: 0, dtype: float64\n',
  "           >>> print(row['int'].dtype)\n",
  '           float64\n',
  "           >>> print(df['int'].dtype)\n",
  '           int64\n',
  '\n',
  '           To preserve dtypes while iterating over the rows, it is better\n',
  '           to use :meth:`itertuples` which returns namedtuples of the values\n',
  '           and which is generally faster than ``iterrows``.\n',
  '\n',
  '        2. You should **never modify** something you are iterating over.\n',
  '           This is not guaranteed to work in all cases. Depending on the\n',
  '           data types, the iterator returns a copy and not a view, and writing\n',
  '           to it will have no effect.\n',
  '        """\n',
  '        columns = self.columns\n',
  '        klass = self._constructor_sliced\n',
  '        for k, v in zip(self.index, self.values):\n',
  '            s = klass(v, index=columns, name=k)\n',
  '            yield k, s\n'],
 860)
</code>```

Generally, also, you can just print the function/method and look at the information in the string representation, and pretty much figure it out:

```<code>In [19]: pd.DataFrame.iterrows
Out[19]: <function pandas.core.frame.DataFrame.iterrows(self)>
</code>```

So just from that you could see it is in pandas.core.frame.

ContentLicense: CC BY-SA 4.0

Body:
Python, in general, is easily introspect-able. You can use the inspect module if you want to do this programatically. so for example:

In [8]: import pandas as pd

In [9]: import inspect

In [10]: pd.DataFrame.iterrows
Out[10]: <function pandas.core.frame.DataFrame.iterrows(self)>

In [11]: inspect.getsourcefile(pd.DataFrame.iterrows)
Out[11]: '/Users/juan/anaconda3/envs/py38/lib/python3.8/site-packages/pandas/core/frame.py'

So you can go to pandas/core/frame.py. Note, this won't always work if it is, say, a method written in C as an extension. But it should for Python source code. In fact, you can even get the source code lines using inspect.getsourcelines, which returns a tuple of lines, line_number:

In [12]: inspect.getsourcelines(pd.DataFrame.iterrows)
Out[12]:
(['    def iterrows(self):\n',
  '        """\n',
  '        Iterate over DataFrame rows as (index, Series) pairs.\n',
  '\n',
  '        Yields\n',
  '        ------\n',
  '        index : label or tuple of label\n',
  '            The index of the row. A tuple for a `MultiIndex`.\n',
  '        data : Series\n',
  '            The data of the row as a Series.\n',
  '\n',
  '        it : generator\n',
  '            A generator that iterates over the rows of the frame.\n',
  '\n',
  '        See Also\n',
  '        --------\n',
  '        itertuples : Iterate over DataFrame rows as namedtuples of the values.\n',
  '        items : Iterate over (column name, Series) pairs.\n',
  '\n',
  '        Notes\n',
  '        -----\n',
  '\n',
  '        1. Because ``iterrows`` returns a Series for each row,\n',
  '           it does **not** preserve dtypes across the rows (dtypes are\n',
  '           preserved across columns for DataFrames). For example,\n',
  '\n',
  "           >>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])\n",
  '           >>> row = next(df.iterrows())[1]\n',
  '           >>> row\n',
  '           int      1.0\n',
  '           float    1.5\n',
  '           Name: 0, dtype: float64\n',
  "           >>> print(row['int'].dtype)\n",
  '           float64\n',
  "           >>> print(df['int'].dtype)\n",
  '           int64\n',
  '\n',
  '           To preserve dtypes while iterating over the rows, it is better\n',
  '           to use :meth:`itertuples` which returns namedtuples of the values\n',
  '           and which is generally faster than ``iterrows``.\n',
  '\n',
  '        2. You should **never modify** something you are iterating over.\n',
  '           This is not guaranteed to work in all cases. Depending on the\n',
  '           data types, the iterator returns a copy and not a view, and writing\n',
  '           to it will have no effect.\n',
  '        """\n',
  '        columns = self.columns\n',
  '        klass = self._constructor_sliced\n',
  '        for k, v in zip(self.index, self.values):\n',
  '            s = klass(v, index=columns, name=k)\n',
  '            yield k, s\n'],
 860)

Generally, also, you can just print the function/method and look at the information in the string representation, and pretty much figure it out:

In [19]: pd.DataFrame.iterrows
Out[19]: <function pandas.core.frame.DataFrame.iterrows(self)>

So just from that you could see it is in pandas.core.frame.


问:
How to toggle dark theme in Angular when I click on the switch?
I am using angular and I am trying to switch between light and dark themes. The toggle switch is in my header component. Please see below

And my header component is the child component in the app component. See below also

```<code>// app.component.html

    <app-header (mode)="receiveMode($event)"></app-header>

     <router-outlet></router-outlet>
</code>```

Therefore, I set the boolean value for the toggle theme in my header component TS file

```<code>// header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  @Output() mode = new EventEmitter<boolean>();

  setDark = false;

  constructor() { }

  ngOnInit(): void {

  }

  onChangeToggle() {
    this.setDark = !this.setDark;
    this.mode.emit(this.setDark);
    console.log(this.setDark);
  }

}
</code>```

I then pass that value to the parent component with the Output decorator and receive it in the app.component.ts file so that all other components can have the theme as well, (not just HomeComponent).

```<code>// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  setMode = false;

  receiveMode($event) {
    this.setMode = $event;
    console.log("MODEEEE", this.setMode);
  }

  title = 'about-me';
}
</code>```

I then receive the boolean value from the app-header in the app.component.html file

```<code>// app.component.html

    <app-header (mode)="receiveMode($event)"></app-header>

    <router-outlet></router-outlet>
</code>```

And I added the darkTheme class to my global stylessheet in styles.css

```<code>.darkTheme {
    background-color: black;
}
</code>```

I want to know how  can use ngClass or ngStyle to set it conditionally based on the boolean value.

答:
Here is one way to do it:

```<code><div [ngClass]="{
  darkTheme: setMode
}">
</div>
</code>```

You can also add additional classes and conditions in the same ngClass.

Another:

```<code><div [class.darkTheme]="setMode"></div>
</code>```

EDIT: As mentioned in my comment, I would prefer this approach:

```<code><link rel="stylesheet" href="/theme/css/dark-theme.min.css" *ngIf="setMode">
</code>```

Body:
I am using angular and I am trying to switch between light and dark themes. The toggle switch is in my header component. Please see below

And my header component is the child component in the app component. See below also

// app.component.html

    <app-header (mode)="receiveMode($event)"></app-header>

     <router-outlet></router-outlet>

Therefore, I set the boolean value for the toggle theme in my header component TS file

// header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  @Output() mode = new EventEmitter<boolean>();

  setDark = false;

  constructor() { }

  ngOnInit(): void {

  }

  onChangeToggle() {
    this.setDark = !this.setDark;
    this.mode.emit(this.setDark);
    console.log(this.setDark);
  }

}

I then pass that value to the parent component with the Output decorator and receive it in the app.component.ts file so that all other components can have the theme as well, (not just HomeComponent).

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  setMode = false;

  receiveMode($event) {
    this.setMode = $event;
    console.log("MODEEEE", this.setMode);
  }

  title = 'about-me';
}

I then receive the boolean value from the app-header in the app.component.html file

// app.component.html

    <app-header (mode)="receiveMode($event)"></app-header>

    <router-outlet></router-outlet>

And I added the darkTheme class to my global stylessheet in styles.css

.darkTheme {
    background-color: black;
}

I want to know how  can use ngClass or ngStyle to set it conditionally based on the boolean value.

Body:
Here is one way to do it:

<div [ngClass]="{
  darkTheme: setMode
}">
</div>

You can also add additional classes and conditions in the same ngClass.

Another:

<div [class.darkTheme]="setMode"></div>

EDIT: As mentioned in my comment, I would prefer this approach:

<link rel="stylesheet" href="/theme/css/dark-theme.min.css" *ngIf="setMode">


问:
C++: Container of different types
I have some functions (simple for this example) with different paramaters:

```<code>int addNums(int a, int b) {
    return a + b;
}

int squareNum(int a) {
    return a * a;
}
</code>```

I have a template class action which has a function pointer which will eventually point to either of the above functions:

```<code>template<class T>
class action {
public:
    std::string descriptionOfAction;
    T functionPtr;
};
</code>```

I have a class user which should have some form of a container of actions:

```<code>class user {
public:
    std::string name;

    //container of actions
};
</code>```

In main, I defined and initialized two actions to correspond with the first two functions listed above:

```<code>action<int(*)(int, int)> addAction;
addAction.descriptionOfAction = "Add two numbers together";
addAction.functionPtr = addNums;

action<int(*)(int)> squareAction;
squareAction.descriptionOfAction = "Square a number";
squareAction.functionPtr = squareNum;
</code>```

Now I want to insert both of these actions into a users container of actions:

```<code>user aUser;
aUser.name = "User's Name";
//insert "addAction" and "squareAction" to user's container of actions
</code>```

Because of the templating, these actions are not the same types. Is there an existing type of container to hold these? If not, is there a way to do something similar without templates? Ideally, when a user "uses" one of the actions in their container, the action should be erased.

答:
Don't store pointers to functions as void*. A pointer-to-function is not the same as a pointer-to-variable.

If you want to store multiple types in one variable, use std::variant if you can use C++17, otherwise use a union if you can't.

Title: C++: Container of different types

Body:
I have some functions (simple for this example) with different paramaters:

int addNums(int a, int b) {
    return a + b;
}

int squareNum(int a) {
    return a * a;
}

I have a template class action which has a function pointer which will eventually point to either of the above functions:

template<class T>
class action {
public:
    std::string descriptionOfAction;
    T functionPtr;
};

I have a class user which should have some form of a container of actions:

class user {
public:
    std::string name;

    //container of actions
};

In main, I defined and initialized two actions to correspond with the first two functions listed above:

action<int(*)(int, int)> addAction;
addAction.descriptionOfAction = "Add two numbers together";
addAction.functionPtr = addNums;

action<int(*)(int)> squareAction;
squareAction.descriptionOfAction = "Square a number";
squareAction.functionPtr = squareNum;

Now I want to insert both of these actions into a users container of actions:

user aUser;
aUser.name = "User's Name";
//insert "addAction" and "squareAction" to user's container of actions

Because of the templating, these actions are not the same types. Is there an existing type of container to hold these? If not, is there a way to do something similar without templates? Ideally, when a user "uses" one of the actions in their container, the action should be erased.


问:
Create multiple phases in Stripe instead of schedule using PHP foreach
I have this piece of PHP code that iterates through a Stripe request to create schedules. In the request below it is iterating through the entire request (thereby creating a new subscription for each element of the array). What I need it to do is to only iterate it through the phases part (so that all of the payment dates are in one schedule).</p>

```<code>$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");

  foreach ($paymentdates as $paymentdate) {
  $schedule = \Stripe\SubscriptionSchedule::create([
    'customer' => 'cus_HMDwmb8iAV0X7k',
    'start_date' => 'now',
    'end_behavior' => 'cancel',

      'phases' => [
        // only iterate this part
        [
          'end_date' => $paymentdate,
          'proration_behavior' => 'none',
          'plans' => [
            [
              'price_data' => [
                'unit_amount' => 2300,
                'currency' => 'usd',
                'product' => 'prod_HMDoA6Jpf0U1Fh',
                'recurring' => [
                    'interval' => 'year',
                ],
              ],
            ],
          ],
          // end iterate here
        ],
      ],
  ]);

  }
</code>```

答:
What you should do here is build the array of phases first and at the end create the schedule. I don't fully grasp why you have so many phases with the same plan but ultimately you'd want something like this</p>

```<code>$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");
$phases = []
foreach ($paymentdates as $paymentdate) {
  $phases[] = [
    'end_date' => $paymentdate,
    'plans' => [
        [
          'price_data' => [
            'unit_amount' => 2300,
            'currency' => 'usd',
            'product' => 'prod_HMDoA6Jpf0U1Fh',
            'recurring' => [
                'interval' => 'year',
            ],
          ],
        ],
      ],
  ];
}
$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => 'cus_HMDwmb8iAV0X7k',
  'start_date' => 'now',
  'end_behavior' => 'cancel',
  'phases' => $phases
]);
</code>```

Body:
I have this piece of PHP code that iterates through a Stripe request to create schedules. In the request below it is iterating through the entire request (thereby creating a new subscription for each element of the array). What I need it to do is to only iterate it through the phases part (so that all of the payment dates are in one schedule).

$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");

  foreach ($paymentdates as $paymentdate) {
  $schedule = \Stripe\SubscriptionSchedule::create([
    'customer' => 'cus_HMDwmb8iAV0X7k',
    'start_date' => 'now',
    'end_behavior' => 'cancel',

      'phases' => [
        // only iterate this part
        [
          'end_date' => $paymentdate,
          'proration_behavior' => 'none',
          'plans' => [
            [
              'price_data' => [
                'unit_amount' => 2300,
                'currency' => 'usd',
                'product' => 'prod_HMDoA6Jpf0U1Fh',
                'recurring' => [
                    'interval' => 'year',
                ],
              ],
            ],
          ],
          // end iterate here
        ],
      ],
  ]);

  }

Body:
What you should do here is build the array of phases first and at the end create the schedule. I don't fully grasp why you have so many phases with the same plan but ultimately you'd want something like this

$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");
$phases = []
foreach ($paymentdates as $paymentdate) {
  $phases[] = [
    'end_date' => $paymentdate,
    'plans' => [
        [
          'price_data' => [
            'unit_amount' => 2300,
            'currency' => 'usd',
            'product' => 'prod_HMDoA6Jpf0U1Fh',
            'recurring' => [
                'interval' => 'year',
            ],
          ],
        ],
      ],
  ];
}
$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => 'cus_HMDwmb8iAV0X7k',
  'start_date' => 'now',
  'end_behavior' => 'cancel',
  'phases' => $phases
]);


问:
How to collapse an array by joining all strings, but leaving objects
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

```<code>array = ["I","want","to",[Obj],"come","together"]
</code>```

outputs

```<code>["I want to", [Obj], "come together"];
</code>```

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.

答:
I would do this:

const array = ["I","want","to",{},"come","together"];

let outputArr = [];
let strArr = [];

array.forEach(elem => {
  if (typeof elem === 'string') {
    return strArr.push(elem);
  }

  outputArr.push(strArr.join(' '));
  strArr = [];
  outputArr.push(elem);
});

outputArr.push(strArr.join(' '));

console.log(outputArr);```

Body:
While I'm sure I'm waay over-complicating things, I'm curious to know how I would "collapse" an array by combining all adjacent strings, but leaving objects as objects so that:

array = ["I","want","to",[Obj],"come","together"]

outputs

["I want to", [Obj], "come together"];

I feel like array.reduce() might be the ticket here, but I'm still wrapping my head around that function.


问:
Why does getch() output 10 characters on first run (line) but 9 characters for all following lines?
I have this program that create a new line after every 10 characters. However, once it hits the second iteration and there after it only outputs 9 characters. The program works if I set the second i to -1 but I do not understand why it will not work with i set to 0. The logic is the exact same as the first run as the first i is only run once, so when I want a new line I reset i. Can someone explain what I am missing? I drew out the steps on paper but it still doesn't make sense. Thank you.

```<code>#include <stdio.h>
#include <ncurses.h>

#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = 0;          // Counter is reset. To break out of the loop use CTRL + D.
         }
    }

    // to close curses terminal
    endwin();
}
</code>```

答:
You seem to intermixed both of my examples of my previous answer to your previous question.

Unfortunately, It seems that I didn´t pointed out the reset explicitly although I hinted the difference. I apologize.

The reset needs to be 1 less than the initial start value of the counter because the counter gets incremented at the end of the loop in which the reset takes place, although the incrementation should be only valid for every fully next iteration. We need to make it one integral value less to compensate this effect.

In your actual code, You need to replace i = 0; with i = -1 as seen in one of the examples in my previous answer.

Furthermore, the commenting of cbreak() isn´t a good idea as the console can be either in cbreak() or nocbreak() mode when the program is started up (it is not fixed). Use the explicit cbreak() to determine that the input will immediately read by characters, without the wait for a newline character to flush the buffer.

The Linux man page says:

"Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly."

Body:
I have this program that create a new line after every 10 characters. However, once it hits the second iteration and there after it only outputs 9 characters. The program works if I set the second i to -1 but I do not understand why it will not work with i set to 0. The logic is the exact same as the first run as the first i is only run once, so when I want a new line I reset i. Can someone explain what I am missing? I drew out the steps on paper but it still doesn't make sense. Thank you.

#include <stdio.h>
#include <ncurses.h>

#define MAXLINE 10

// count number of chars, once it reaches certain amount
int main (void)
{
    //cbreak();
    // to open curses terminal
    initscr();

    int i, c;

    // first iteration set to 1
    for (i = 0; (c = getch()) != EOF; i++)
    {
         if (i == (MAXLINE-1))
         {
             printf("\r\n");
             i = 0;          // Counter is reset. To break out of the loop use CTRL + D.
         }
    }

    // to close curses terminal
    endwin();
}


问:
Calling angular function from dynamically added hyperlink
I'm adding some html dynamically to my page.
I have add this

```<code><a [routerLink]="[]" class="image-fav" (click)="imageDel()">CLICK-ME</a>
</code>```

Click on this hyperlink should call the imageDel function but it does not do so.

If I add this html to component template straight everything works fine.
How can I fix this problem ?

答:
Angular doesn't understand the events of dynamically added elements. One workaround would be to use ElementRef's querySelector function to add the event handler. Try the following

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

constructor(private elementRef: ElementRef) { }

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
    'click', this.imageDel.bind(this)
  );
}
```

Alternatively, you could also use Renderer2's listen method or HostListener to bind the event handler.

Body:
I'm adding some html dynamically to my page.
I have add this

CLICK-ME

Click on this hyperlink should call the imageDel function but it does not do so.

If I add this html to component template straight everything works fine.
How can I fix this problem ?

Body:
Angular doesn't understand the events of dynamically added elements. One workaround would be to use ElementRef's querySelector function to add the event handler. Try the following

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

constructor(private elementRef: ElementRef) { }

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('.image-fav').addEventListener(
    'click', this.imageDel.bind(this)
  );
}

Alternatively, you could also use Renderer2's listen method or HostListener to bind the event handler.


问:
Can't zoom out in visual studio code
I accidentally hit CTRL + = and my IDE is too much zoomed now. I tried the shortcut to zoom out as stated in the official vscode doc, (CTRL + -) but this is not working.

Some help would be appreciated.

Thanks,

答: It's simple I just found out, hold ctrl + -. This should zoom out and zoom in again just do what you did to zoom in. There are many ways to do it, this is just one of them.

Title: Can't zoom out in visual studio code


问:
How do I download tensorflow on pycharm
I'm trying to install tensorflow in Pycharm, but typing pip install tensorflow isn't working. I'd prefer not to download anaconda.. any ideas on how to do this?

答:
Are you sure you're typing that in terminal?

Also, you don't need anaconda to install anything. You can just type pip install tensorflow using CLI.

Title: How do I download tensorflow on pycharm


问:
Solving problem to generate custom number from inserted values with GUI in Python
Hello im having python learning project. I want to insert in GUI two numbers, which are defining range for program to generate random number from.

I am really having problems with calling function with press of the button. And constantly getting error ValueError: invalid literal for int() with base 10: '', when trying to convert string from entry in GUI to int and then inserting them into random.randint.

Thx for Help!

```<code>from tkinter import *
import random

root = Tk()
root.title("Generator custom random number")

#function that gets number from entry converts string to int and defines target number in stevilo
def function():
    string_answer1 = prvo_stevilo.get()
    int1 = int(string_answer1)
    string_answer2 = drugo_stevilo.get()
    int2 = int(string_answer2)
    stevilo = random.randint(int1, int2)

#Defining GUI
navodilo = Label(root, text="Choose custom lower and upper number to chose random number from", width=60)
navodilo2 = Label(root, text="From", width=20, borderwidth=3)
navodilo3 = Label(root, text="To", width=20, borderwidth=3)
prvo_stevilo = Entry(root, width=20, borderwidth=3)
drugo_stevilo = Entry(root, width=20, borderwidth=3)
gumb = Button(root, text="Generate number", width=17, height=2, command=function)
praznavrstica = Label(root, text="")
izpis = Label(root, text="Random number is: ", width=20)
izpis_stevila = Label(root, text="" + stevilo)

#Showcase of gui
navodilo.grid(row=0, column=0, columnspan=1)
navodilo2.grid(row=1, column=0, columnspan=1)
navodilo3.grid(row=3, column=0, columnspan=1)
prvo_stevilo.grid(row=2, column=0, columnspan=1)
drugo_stevilo.grid(row=4, column=0, columnspan=1)
praznavrstica.grid(row=5, column=0, columnspan=1)
gumb.grid(row=6, column=0, columnspan=1)
praznavrstica.grid(row=7, column=0, columnspan=1)
izpis.grid(row=8, column=0, columnspan=1)
izpis_stevila.grid(row=9, column=0, columnspan=1)

#Loop
root.mainloop()
</code>```

答:
I've noticed few problems with your code. I was able to make it running without too many changes, although probably it is not the best way.

First answer to your question: you are getting this error, because you are trying to change string -> '' to int. It happens because function() is running before you click button.

Another problem:

```<code>izpis_stevila = Label(root, text="" + stevilo)
</code>```

variable 'stevilo' simply doesn't exist before calling function(), so delete it from here.

My proposition for changes:

1)

```<code>gumb = Button(root, text="Generate number", width=17, height=2,command = lambda: function())
</code>```

Without lambda your function will run no matter of state of your button.

2)

```<code>first = IntVar(root, value=0)
second = IntVar(root, value=1)
prvo_stevilo = Entry(root, width=20, borderwidth=3, textvariable=first)
drugo_stevilo = Entry(root, width=20, borderwidth=3, textvariable=second)
</code>```

If you run function without any values in your entry you will get error. This change allows you to put default value for your entry widgets.

3)

```<code>def function():
if prvo_stevilo.get() == '' or drugo_stevilo.get() =='':
    return
else:
    string_answer1 = prvo_stevilo.get()
    int1 = int(string_answer1)
    string_answer2 = drugo_stevilo.get()
    int2 = int(string_answer2)
    stevilo = random.randint(int1, int2)
    izpis_stevila = Label(root, text=str(stevilo))
    izpis_stevila.grid(row=9, column=0)
</code>```

Firstly check if your entry is not empty.
Secondly update label, also remeber about changing int to string here text=str(stevilo).

Body:
Hello im having python learning project. I want to insert in GUI two numbers, which are defining range for program to generate random number from.

I am really having problems with calling function with press of the button. And constantly getting error ValueError: invalid literal for int() with base 10: '', when trying to convert string from entry in GUI to int and then inserting them into random.randint.

Thx for Help!

from tkinter import *
import random

root = Tk()
root.title("Generator custom random number")

#function that gets number from entry converts string to int and defines target number in stevilo
def function():
    string_answer1 = prvo_stevilo.get()
    int1 = int(string_answer1)
    string_answer2 = drugo_stevilo.get()
    int2 = int(string_answer2)
    stevilo = random.randint(int1, int2)

#Defining GUI
navodilo = Label(root, text="Choose custom lower and upper number to chose random number from", width=60)
navodilo2 = Label(root, text="From", width=20, borderwidth=3)
navodilo3 = Label(root, text="To", width=20, borderwidth=3)
prvo_stevilo = Entry(root, width=20, borderwidth=3)
drugo_stevilo = Entry(root, width=20, borderwidth=3)
gumb = Button(root, text="Generate number", width=17, height=2, command=function)
praznavrstica = Label(root, text="")
izpis = Label(root, text="Random number is: ", width=20)
izpis_stevila = Label(root, text="" + stevilo)

#Showcase of gui
navodilo.grid(row=0, column=0, columnspan=1)
navodilo2.grid(row=1, column=0, columnspan=1)
navodilo3.grid(row=3, column=0, columnspan=1)
prvo_stevilo.grid(row=2, column=0, columnspan=1)
drugo_stevilo.grid(row=4, column=0, columnspan=1)
praznavrstica.grid(row=5, column=0, columnspan=1)
gumb.grid(row=6, column=0, columnspan=1)
praznavrstica.grid(row=7, column=0, columnspan=1)
izpis.grid(row=8, column=0, columnspan=1)
izpis_stevila.grid(row=9, column=0, columnspan=1)

#Loop
root.mainloop()

Body:
I've noticed few problems with your code. I was able to make it running without too many changes, although probably it is not the best way.

First answer to your question: you are getting this error, because you are trying to change string -> '' to int. It happens because function() is running before you click button.

Another problem:

izpis_stevila = Label(root, text="" + stevilo)

variable 'stevilo' simply doesn't exist before calling function(), so delete it from here.

My proposition for changes:

1)

gumb = Button(root, text="Generate number", width=17, height=2,command = lambda: function())

Without lambda your function will run no matter of state of your button.

2)

first = IntVar(root, value=0)
second = IntVar(root, value=1)
prvo_stevilo = Entry(root, width=20, borderwidth=3, textvariable=first)
drugo_stevilo = Entry(root, width=20, borderwidth=3, textvariable=second)

If you run function without any values in your entry you will get error. This change allows you to put default value for your entry widgets.

3)

def function():
if prvo_stevilo.get() == '' or drugo_stevilo.get() =='':
    return
else:
    string_answer1 = prvo_stevilo.get()
    int1 = int(string_answer1)
    string_answer2 = drugo_stevilo.get()
    int2 = int(string_answer2)
    stevilo = random.randint(int1, int2)
    izpis_stevila = Label(root, text=str(stevilo))
    izpis_stevila.grid(row=9, column=0)

Firstly check if your entry is not empty.
Secondly update label, also remeber about changing int to string here text=str(stevilo).


问:
Setting the Value of a Long and the Time on a Date to Midnight
All, I am trying to set the time component of a order. The OrderDate field is defined as follows

```<code>{
    "OrderDate" : {
        "DateTime" : ISODate("2017-11-29T00:00:00.000+00:00"),
        "Ticks" : 636475104000000000
    }
}
</code>```

I wish to update an OrderDate that has a non-zero time component, to have a time components of 00:00:00.000+00:00. The order I wish to change looks like

```<code>{
    "OrderDate" : {
        "DateTime" : ISODate("2020-04-17T01:52:14.280+01:00"),
        "Ticks" : 637226815342800000
    }
}
</code>```

I want this too look like

```<code>"OrderDate" : {
    "DateTime" : ISODate("2020-04-17T00:00:00.000+00:00"),
    "Ticks" : 636475104000000000
}
</code>```

The function I am attempting to use is

```<code>function (order)
{
    const midnightTime = new Date(0, 0, 0, 0, 0, 0, 0);
    print("midnightTime = " , midnightTime.toLocaleString());
    print("orderTime = " , order.OrderDate.DateTime.toLocaleString());

    order.OrderDate.DateTime = new Date(
        order.OrderDate.DateTime.getFullYear(),
        order.OrderDate.DateTime.getMonth(),
        order.OrderDate.DateTime.getDay(),
        0,
        0,
        0,
        0);
    print("orderTime = " , order.OrderDate.DateTime.toLocaleString());

    //order.OrderDate.Ticks = NumberLong(636475104000000000);
    db.Orders.save(order);
}
</code>```

The output of this is

midnightTime =  31/12/1899, 00:00:00

marketOrderTime =  17/04/2020, 01:52:14

marketOrderTime =  05/04/2020, 00:00:00

Q1. Why do I get 05/04/2020 here and not 17/04/2020, 00:00:00 and how can I correct this?
Q2. When I uncomment the setting of the ticks, I get

"message" : "Cannot set property 'Ticks' of null",   "stack" :
  "script:27:45" +
              "script:28:91" +
              "script:28:91" +
              "script:9:7"

how can I set the Tick value?

答:
It's a legacy "feature" of ECMAScript that year values 0 to 99 are treated as 1900 to 1999, so new Date(0, 0, 1) creates a Date for 1900-01-01.

If orderDate.DateTime is a Date instance, then to set the UTC time to zero just do:

```<code>orderDate.DateTime.setUTCHours(0,0,0,0);
</code>```

Q1. Why do I get 05/04/2020 here and not 17/04/2020, 00:00:00

Because you're creating the date using getDay, which returns the day of the week numbered 0 to 6 for Sunday to Saturday. You should be using getDate instead.

However, the original date is UTC, so you should use UTC methods:

```<code>order.OrderDate.DateTime = new Date(
    order.OrderDate.DateTime.getUTCFullYear(),
    order.OrderDate.DateTime.getUTCMonth(),
    order.OrderDate.DateTime.getUTCDate());
</code>```

Missing values are treated as zero (except for date, which is 1). But just set the time to zero as shown above.

Q2. When I uncomment the setting of the ticks, I get…

The message is telling you that order.OrderDate is null. Try

```<code>console.log(typeof order.OrderDate)
</code>```

You need to post a runnable snippet demonstrating that.

What is "NumberLong"? Perhaps you're looking for BigInt?

Body:
All, I am trying to set the time component of a order. The OrderDate field is defined as follows

{
    "OrderDate" : {
        "DateTime" : ISODate("2017-11-29T00:00:00.000+00:00"),
        "Ticks" : 636475104000000000
    }
}

I wish to update an OrderDate that has a non-zero time component, to have a time components of 00:00:00.000+00:00. The order I wish to change looks like

{
    "OrderDate" : {
        "DateTime" : ISODate("2020-04-17T01:52:14.280+01:00"),
        "Ticks" : 637226815342800000
    }
}

I want this too look like

"OrderDate" : {
    "DateTime" : ISODate("2020-04-17T00:00:00.000+00:00"),
    "Ticks" : 636475104000000000
}

The function I am attempting to use is

function (order)
{
    const midnightTime = new Date(0, 0, 0, 0, 0, 0, 0);
    print("midnightTime = " , midnightTime.toLocaleString());
    print("orderTime = " , order.OrderDate.DateTime.toLocaleString());

    order.OrderDate.DateTime = new Date(
        order.OrderDate.DateTime.getFullYear(),
        order.OrderDate.DateTime.getMonth(),
        order.OrderDate.DateTime.getDay(),
        0,
        0,
        0,
        0);
    print("orderTime = " , order.OrderDate.DateTime.toLocaleString());

    //order.OrderDate.Ticks = NumberLong(636475104000000000);
    db.Orders.save(order);
}

The output of this is

midnightTime =  31/12/1899, 00:00:00

marketOrderTime =  17/04/2020, 01:52:14

marketOrderTime =  05/04/2020, 00:00:00

Q1. Why do I get 05/04/2020 here and not 17/04/2020, 00:00:00 and how can I correct this?
Q2. When I uncomment the setting of the ticks, I get

"message" : "Cannot set property 'Ticks' of null",   "stack" :
  "script:27:45" +
              "script:28:91" +
              "script:28:91" +
              "script:9:7"

how can I set the Tick value?

Body:
It's a legacy "feature" of ECMAScript that year values 0 to 99 are treated as 1900 to 1999, so new Date(0, 0, 1) creates a Date for 1900-01-01.

If orderDate.DateTime is a Date instance, then to set the UTC time to zero just do:

orderDate.DateTime.setUTCHours(0,0,0,0);

Q1. Why do I get 05/04/2020 here and not 17/04/2020, 00:00:00

Because you're creating the date using getDay, which returns the day of the week numbered 0 to 6 for Sunday to Saturday. You should be using getDate instead.

However, the original date is UTC, so you should use UTC methods:

order.OrderDate.DateTime = new Date(
    order.OrderDate.DateTime.getUTCFullYear(),
    order.OrderDate.DateTime.getUTCMonth(),
    order.OrderDate.DateTime.getUTCDate());

Missing values are treated as zero (except for date, which is 1). But just set the time to zero as shown above.

Q2. When I uncomment the setting of the ticks, I get…

The message is telling you that order.OrderDate is null. Try

console.log(typeof order.OrderDate)

You need to post a runnable snippet demonstrating that.

What is "NumberLong"? Perhaps you're looking for BigInt?


问:
centos not update, centos 7.8 (2003)
```<code> dnf -y upgrade http://mirror.bytemark.co.uk/centos/8/BaseOS/x86_64/os/Packages/centos-release-8.1-1.1911.0.8.el8.x86_64.rpm
Last metadata expiration check: 0:35:45 ago on Tue May 12 20:59:10 2020.
centos-release-8.1-1.1911.0.8.el8.x86_64.rpm     55 kB/s |  21 kB     00:00
Dependencies resolved.

 Problem: cannot install the best update candidate for package centos-release-7-8.2003.0.el7.centos.x86_64
  - nothing provides centos-gpg-keys = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
  - nothing provides centos-repos = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
================================================================================
 Package            Arch       Version                   Repository        Size
================================================================================
Skipping packages with broken dependencies:
 centos-release     x86_64     8.1-1.1911.0.8.el8        @commandline      21 k

Transaction Summary
================================================================================
Skip  1 Package

Nothing to do.
Complete!
</code>```

I want to update centos 7.8, I can’t get help.
first there was version 7.2, I upgraded to 7.8

答: date the release date corresponds to the release, at the moment this is the latest release, the problem was in the kernel, tried to install on OpenVz, centos does not work does not support open. So tnank you.</p>

Title: centos not update, centos 7.8 (2003)

Body:
 dnf -y upgrade http://mirror.bytemark.co.uk/centos/8/BaseOS/x86_64/os/Packages/centos-release-8.1-1.1911.0.8.el8.x86_64.rpm
Last metadata expiration check: 0:35:45 ago on Tue May 12 20:59:10 2020.
centos-release-8.1-1.1911.0.8.el8.x86_64.rpm     55 kB/s |  21 kB     00:00
Dependencies resolved.

 Problem: cannot install the best update candidate for package centos-release-7-8.2003.0.el7.centos.x86_64
  - nothing provides centos-gpg-keys = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
  - nothing provides centos-repos = 8.1-1.1911.0.8.el8 needed by centos-release-8.1-1.1911.0.8.el8.x86_64
================================================================================
 Package            Arch       Version                   Repository        Size
================================================================================
Skipping packages with broken dependencies:
 centos-release     x86_64     8.1-1.1911.0.8.el8        @commandline      21 k

Transaction Summary
================================================================================
Skip  1 Package

Nothing to do.
Complete!

I want to update centos 7.8, I can’t get help.
first there was version 7.2, I upgraded to 7.8


问:
Data attributes in head and meta tags
Similar to this question, I want to dynamically change and translate the values of some head tags (title, meta description, meta keywords ...) based on a chosen language by the user. It's a node.js application where I'm using Express and ejs to inject the language.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title data-translate-key="title">Translated title</title>
    <meta name="description" data-translate-key="description" content="Translated description">
</head>
<body>
</body>
</html>
</code>```

Is this allowed, and is this valid html? This document on w3docs.com says the following:

Allows private information to be exchanged between HTML and its DOM representation. It gives the ability to embed custom data attributes on all HTML elements.

I ran the above snippet in the official w3 validator and it did not show any errors. So therefore I assumed it is valid html. However I cannot find much information about it.

答:
Yes, it is valid.

As stated in MDN web docs:

The data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation by scripts.

data-* attributes are global attributes and global attributes as stated in MDN web docs:

Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements.

can be applied to all elements.

Title: Data attributes in head and meta tags

Body:
Similar to this question, I want to dynamically change and translate the values of some head tags (title, meta description, meta keywords ...) based on a chosen language by the user. It's a node.js application where I'm using Express and ejs to inject the language.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title data-translate-key="title">Translated title</title>
    <meta name="description" data-translate-key="description" content="Translated description">

Is this allowed, and is this valid html? This document on w3docs.com says the following:

Allows private information to be exchanged between HTML and its DOM representation. It gives the ability to embed custom data attributes on all HTML elements.

I ran the above snippet in the official w3 validator and it did not show any errors. So therefore I assumed it is valid html. However I cannot find much information about it.


问:
Why long types are rounded in .NET Web API JSON response payload after 16 digits?
I am working with web api 2 which I coincidentally realized that it rounds the long type value in the response model if it is longer than 16 digits.

(simplifying the example for the sake of the question) Assume I have a web api method as "GetOrders" which returns list of orderVm model which is defined as below:

```<code>public class OrderVm{
    public int OrderID {get;set;}
    public long? OrderNumber {get;set;}
}
</code>```

What is happening is, if my order number value is

1234567890123459 there is no issue - total of 16 digits.

1234567890123499 there is no issue - total of 16 digits.

12345678901234599 this is the problematic one. total of 17 digits. It is rounding this to 12345678901234600

Below is my simplified example API Method:

```<code>        [HttpPost]
        [Route("get-orders/")]
        public IHttpActionResult GetOrders(PostedVm postedVm)
        {
              var orderDtoList = _orderManager.GetOrders(postedVm.Active); // I checked the value in orderDtoList and it is not rounded at this moment...
              var orderVmList  = MapDtoToVm(orderDtoList);
              return Ok(orderVmList);// I thought maybe something happens during the property mapping (which is just using simple reflection) but I checked the value in orderVmList and it is not rounded at this moment...
        }
</code>```

Even though right before returning the response, I checked that the values actually were not rounded.. But somehow on the client, it is coming as rounded. I thought maybe the browser does some magic (for some reason) but I checked my payload on postman and fiddler, it was showing that the value as rounded in the response payload.

This sounds something related to web api configuration but if so, how I can set it to not modify the data? And I am also curious about "why it is happening after 16 digits?"

Just in case I added my WebApiConfig class below:

```<code> public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        //GZip Compression
        GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
        name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
            id = RouteParameter.Optional
        });
    }
}
</code>```

答:
This is most likey due to number represented as IEEE 754 (double in C#).

Due to the binary representation rounding may apply, so that 12345678901234599 and 12345678901234600 have the same binary representation.

You can observe this behavior in C# as well:

```<code>double x = 12345678901234599;
double y = 12345678901234600;
Console.WriteLine(x == y); // Prints true
</code>```

https://dotnetfiddle.net/G0KOqZ

EDIT: Despite my original answer the JSON standard does not specify numeric limits, but the problem is the same.

This specification allows implementations to set limits on the range
and precision of numbers accepted.  Since software that implements
IEEE 754 binary64 (double precision) numbers [IEEE754] is generally
available and widely used, good interoperability can be achieved by
implementations that expect no more precision or range than these
provide, in the sense that implementations will approximate JSON
numbers within the expected precision.

https://www.rfc-editor.org/rfc/rfc8259#section-6

Body:
I am working with web api 2 which I coincidentally realized that it rounds the long type value in the response model if it is longer than 16 digits.

(simplifying the example for the sake of the question) Assume I have a web api method as "GetOrders" which returns list of orderVm model which is defined as below:

public class OrderVm{
    public int OrderID {get;set;}
    public long? OrderNumber {get;set;}
}

What is happening is, if my order number value is

1234567890123459 there is no issue - total of 16 digits.

1234567890123499 there is no issue - total of 16 digits.

12345678901234599 this is the problematic one. total of 17 digits. It is rounding this to 12345678901234600

Below is my simplified example API Method:

        [HttpPost]
        [Route("get-orders/")]
        public IHttpActionResult GetOrders(PostedVm postedVm)
        {
              var orderDtoList = _orderManager.GetOrders(postedVm.Active); // I checked the value in orderDtoList and it is not rounded at this moment...
              var orderVmList  = MapDtoToVm(orderDtoList);
              return Ok(orderVmList);// I thought maybe something happens during the property mapping (which is just using simple reflection) but I checked the value in orderVmList and it is not rounded at this moment...
        }

Even though right before returning the response, I checked that the values actually were not rounded.. But somehow on the client, it is coming as rounded. I thought maybe the browser does some magic (for some reason) but I checked my payload on postman and fiddler, it was showing that the value as rounded in the response payload.

This sounds something related to web api configuration but if so, how I can set it to not modify the data? And I am also curious about "why it is happening after 16 digits?"

Just in case I added my WebApiConfig class below:

 public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        //GZip Compression
        GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
        name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
            id = RouteParameter.Optional
        });
    }
}

Body:
This is most likey due to number represented as IEEE 754 (double in C#).

Due to the binary representation rounding may apply, so that 12345678901234599 and 12345678901234600 have the same binary representation.

You can observe this behavior in C# as well:

double x = 12345678901234599;
double y = 12345678901234600;
Console.WriteLine(x == y); // Prints true

https://dotnetfiddle.net/G0KOqZ

EDIT: Despite my original answer the JSON standard does not specify numeric limits, but the problem is the same.

This specification allows implementations to set limits on the range
and precision of numbers accepted.  Since software that implements
IEEE 754 binary64 (double precision) numbers [IEEE754] is generally
available and widely used, good interoperability can be achieved by
implementations that expect no more precision or range than these
provide, in the sense that implementations will approximate JSON
numbers within the expected precision.

https://www.rfc-editor.org/rfc/rfc8259#section-6


问:
Add A Class To An Input Using PHP
I have been working on a form that uses PHP form validation. I also have a class in my CSS file that should be added to each of the invalid inputs. You can view a JSFiddle here. The class I am trying to add is only visible when the input is returned invalid. The class name is .invalid which you can find in the CSS. Thanks in advance, and any help is appreciated.

答:
You can have PHP add a class to your inputs if a field is invalid, but you may need to adjust your approach.

If you want to maintain using a form POST method (as you have it), you'd want to move your validation code to be processed on the same page that renders your view (the easiest way to do this is to have it within the same page). You can still use and include a separate file to pull in a PHP class or other system you want to use for validation if you want to keep your code neat. Here's an example:

```<code><?php
// filter_input returns null or false if invalid.
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
?>

<form method="POST" action="<?php echo getenv('REQUEST_URI'); ?>">
<input type="text" name="firstname" value="<?php echo $firstname; ?>" class="<?php echo $firstname ? '' : 'invalid'; ?>" />
<input type="submit" name="submit" value="Submit" />
</form>
</code>```

However, I would recommend a more robust approach which would be to use an AJAX handler for submitting your form. This will give your users a better experience, and it also allows you to neatly have your form processing entirely separate from your view. That solution is a bit beyond the scope of this question, but ultimately you would have your PHP AJAX handler return information as to whether or not the submission was valid or what fields are invalid and have the javascript add your invalid class to the fields in error.

Title: Add A Class To An Input Using PHP

Body:
You can have PHP add a class to your inputs if a field is invalid, but you may need to adjust your approach.

If you want to maintain using a form POST method (as you have it), you'd want to move your validation code to be processed on the same page that renders your view (the easiest way to do this is to have it within the same page). You can still use and include a separate file to pull in a PHP class or other system you want to use for validation if you want to keep your code neat. Here's an example:

<?php
// filter_input returns null or false if invalid.
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
?>

<form method="POST" action="<?php echo getenv('REQUEST_URI'); ?>">
<input type="text" name="firstname" value="<?php echo $firstname; ?>" class="<?php echo $firstname ? '' : 'invalid'; ?>" />
<input type="submit" name="submit" value="Submit" />
</form>

However, I would recommend a more robust approach which would be to use an AJAX handler for submitting your form. This will give your users a better experience, and it also allows you to neatly have your form processing entirely separate from your view. That solution is a bit beyond the scope of this question, but ultimately you would have your PHP AJAX handler return information as to whether or not the submission was valid or what fields are invalid and have the javascript add your invalid class to the fields in error.


问:
Save value on stepper SwiftUI
I have a stepper:

```<code>Stepper(value: $timeBetweenMeals, in: 1...10, step: 1) {
                                Text("Time Between Meals: \(timeBetweenMeals, specifier: "%.0f")h")
                                self.settingsUserDefaults = $timeBetweenMeals
                            }
</code>```

That gives me error because I'm trying to set: self.settingsUserDefaults = $timeBetweenMeals inside that view. How can I run that logic? I don't have a button, I just want to save that @Published value as the user changes it

答:
You need to perform other actions when Stepper value changes in onIncrement and onDecrement method not inside of the label parameter which is meant to return the View of the Stepper. Here is an example (Note: this is just an example, you can achieve this in many easier ways too):

struct ContentView: View {
    @State var timeBetweenMeals: Int
    var body: some View {
        Stepper(value: Binding<Int>(get: {
            self.timeBetweenMeals
        }, set: {
            print($0)
            self.timeBetweenMeals = $0
        }), in: 1...10, step: 1) {
            Text("Time Between Meals: \(timeBetweenMeals)h")
        }
    }
}
```

Note: I've updated to a much better approach. Credits to davidev. Also, your specifier seems to be incorrect.

Title: Save value on stepper SwiftUI

Body:
I have a stepper:

Stepper(value: $timeBetweenMeals, in: 1...10, step: 1) {
                                Text("Time Between Meals: \(timeBetweenMeals, specifier: "%.0f")h")
                                self.settingsUserDefaults = $timeBetweenMeals
                            }

That gives me error because I'm trying to set: self.settingsUserDefaults = $timeBetweenMeals inside that view. How can I run that logic? I don't have a button, I just want to save that @Published value as the user changes it

Body:
You need to perform other actions when Stepper value changes in onIncrement and onDecrement method not inside of the label parameter which is meant to return the View of the Stepper. Here is an example (Note: this is just an example, you can achieve this in many easier ways too):

struct ContentView: View {
    @State var timeBetweenMeals: Int
    var body: some View {
        Stepper(value: Binding<Int>(get: {
            self.timeBetweenMeals
        }, set: {
            print($0)
            self.timeBetweenMeals = $0
        }), in: 1...10, step: 1) {
            Text("Time Between Meals: \(timeBetweenMeals)h")
        }
    }
}

Note: I've updated to a much better approach. Credits to davidev. Also, your specifier seems to be incorrect.


问:
How not to let someone click on return button of navigator?
I checked this code on W3 schools :

```<code>window.addEventListener("beforeunload", function(event) {
  event.returnValue = "Write something clever here..";
});
</code>```

You can use on one of your HTML item, but to apply it to the return button of the navigator ?
(in order to warn the user that i will lose his job if he continues for example)

答:
This example is quite simple.

```<code>var formHasUnsavedChanges = false;

window.addEventListener("beforeunload", function (e) {
    if (formHasUnsavedChanges === true) {
        var msg = "your warning message"; // Some browsers show their own message.
        (e || window.event).returnValue = msg;
        return msg;
    }
});
</code>```

As soon as the user made changes, set formHasUnsavedChanges to true.

If you save your form through an AJaX call, you can set the variable to false after the save completed.

If you use a normal form, then set the variable to false right before submitting. Otherwise the warning message will pop up when saving.

This warning message will also pop up when clicking on a link or closing a tab.

Body:
I checked this code on W3 schools :

window.addEventListener("beforeunload", function(event) {
  event.returnValue = "Write something clever here..";
});

You can use on one of your HTML item, but to apply it to the return button of the navigator ?
(in order to warn the user that i will lose his job if he continues for example)

Body:
This example is quite simple.

var formHasUnsavedChanges = false;

window.addEventListener("beforeunload", function (e) {
    if (formHasUnsavedChanges === true) {
        var msg = "your warning message"; // Some browsers show their own message.
        (e || window.event).returnValue = msg;
        return msg;
    }
});

As soon as the user made changes, set formHasUnsavedChanges to true.

If you save your form through an AJaX call, you can set the variable to false after the save completed.

If you use a normal form, then set the variable to false right before submitting. Otherwise the warning message will pop up when saving.

This warning message will also pop up when clicking on a link or closing a tab.


问:
Frequency cipher in F#
I'm currently working on a frequency-substitution cipher in F#. Meaning that I count all the occurrences of each letter in a text and when that is done I want to replace the letters based on the letter frequency in the english alphabet.

What i've done so far is that i've created a (char * float * char) list that contains (letter, frequency percentage, recommended letter). Let's say the letter P is the most occurring letter in my ciphered text (13.5 percent of letters are P) and E is the most used letter in english texts our list element will look like this ('P', 13.5, 'E'). This procedure is done all letters in the text, so we will end up with a list of all letters and their recommended replacement.

The problem I have is that I don't really know how to replace the letters in the cipher text with their recommended replacements.

```<code>Letter frequency in the english alphabet.
[(' ', 20.0); ('E', 12.02); ('T', 9.1); ('A', 8.12); ('O', 7.68); ('I', 7.31);
 ('N', 6.95); ('S', 6.28); ('R', 6.02); ('H', 5.92); ('D', 4.32); ('L', 3.98);
 ('U', 2.88); ('C', 2.71); ('M', 2.61); ('F', 2.3); ('Y', 2.11); ('W', 2.09);
 ('G', 2.03); ('P', 1.82); ('B', 1.49); ('V', 1.11); ('K', 0.69); ('X', 0.17);
 ('Q', 0.11); ('J', 0.1); ('Z', 0.07)]

Letter frequency in cipher.
[('W', 21.18); ('Z', 8.31); ('I', 7.7); ('P', 6.96); ('Y', 5.5); ('H', 5.48);
 ('G', 5.35); ('K', 5.3); ('N', 4.31); ('O', 4.31); ('M', 3.66); (' ', 2.83);
 ('A', 2.58); ('T', 2.38); ('Q', 2.22); ('B', 2.11); ('F', 2.11); ('.', 2.04);
 ('R', 1.62); ('S', 1.37); ('E', 1.06); ('X', 0.97); ('U', 0.25); ('L', 0.16);
 ('V', 0.11); ('J', 0.07); ('C', 0.02); ('D', 0.02)]

Recommended letter changes.
[('W', 21.18, ' '); ('Z', 8.31, 'E'); ('I', 7.7, 'T'); ('P', 6.96, 'A');
 ('Y', 5.5, 'O'); ('H', 5.48, 'I'); ('G', 5.35, 'N'); ('K', 5.3, 'S');
 ('N', 4.31, 'R'); ('O', 4.31, 'H'); ('M', 3.66, 'D'); (' ', 2.83, ' ');
 ('A', 2.58, 'L'); ('T', 2.38, 'U'); ('Q', 2.22, 'C'); ('B', 2.11, 'M');
 ('F', 2.11, 'F'); ('.', 2.04, 'Y'); ('R', 1.62, 'W'); ('S', 1.37, 'G');
 ('E', 1.06, 'P'); ('X', 0.97, 'B'); ('U', 0.25, 'V'); ('L', 0.16, 'K');
 ('V', 0.11, 'X'); ('J', 0.07, 'Q'); ('C', 0.02, 'J'); ('D', 0.02, 'Z')]
</code>```

If anyone have any ideas that would put me in the right direction on how to tackle the problem i'd be very appreciative since i've been stuck on this problem for some while now.

答:
I believe you are missing . frequency in the English alphabet (should be between D and L. When you'll add missing value to alphaFreq list both lists will be of same length and you'll be able to produce recommended changes map by zipping two ordered lists:

```<code>let changes =
    alphaFreq // list with letter frequency in the English alphabet
    |> List.zip cipherFreq // zipping with cipher frequency list
    |> List.map (fun ((cipherLetter,_), (alphaLetter,_)) -> (alphaLetter, cipherLetter))
    |> Map.ofList
</code>```

Encoding test:

```<code>"HELLO WORLD" |> String.map (fun ch -> changes.[ch]) |> printfn "%s"
// OZAAYWRYNAM
</code>```

To get a decoder map just swap letter order -> (cipherLetter, alphaLetter)

Title: Frequency cipher in F#

Body:
I'm currently working on a frequency-substitution cipher in F#. Meaning that I count all the occurrences of each letter in a text and when that is done I want to replace the letters based on the letter frequency in the english alphabet.

What i've done so far is that i've created a (char * float * char) list that contains (letter, frequency percentage, recommended letter). Let's say the letter P is the most occurring letter in my ciphered text (13.5 percent of letters are P) and E is the most used letter in english texts our list element will look like this ('P', 13.5, 'E'). This procedure is done all letters in the text, so we will end up with a list of all letters and their recommended replacement.

The problem I have is that I don't really know how to replace the letters in the cipher text with their recommended replacements.

Letter frequency in the english alphabet.
[(' ', 20.0); ('E', 12.02); ('T', 9.1); ('A', 8.12); ('O', 7.68); ('I', 7.31);
 ('N', 6.95); ('S', 6.28); ('R', 6.02); ('H', 5.92); ('D', 4.32); ('L', 3.98);
 ('U', 2.88); ('C', 2.71); ('M', 2.61); ('F', 2.3); ('Y', 2.11); ('W', 2.09);
 ('G', 2.03); ('P', 1.82); ('B', 1.49); ('V', 1.11); ('K', 0.69); ('X', 0.17);
 ('Q', 0.11); ('J', 0.1); ('Z', 0.07)]

Letter frequency in cipher.
[('W', 21.18); ('Z', 8.31); ('I', 7.7); ('P', 6.96); ('Y', 5.5); ('H', 5.48);
 ('G', 5.35); ('K', 5.3); ('N', 4.31); ('O', 4.31); ('M', 3.66); (' ', 2.83);
 ('A', 2.58); ('T', 2.38); ('Q', 2.22); ('B', 2.11); ('F', 2.11); ('.', 2.04);
 ('R', 1.62); ('S', 1.37); ('E', 1.06); ('X', 0.97); ('U', 0.25); ('L', 0.16);
 ('V', 0.11); ('J', 0.07); ('C', 0.02); ('D', 0.02)]

Recommended letter changes.
[('W', 21.18, ' '); ('Z', 8.31, 'E'); ('I', 7.7, 'T'); ('P', 6.96, 'A');
 ('Y', 5.5, 'O'); ('H', 5.48, 'I'); ('G', 5.35, 'N'); ('K', 5.3, 'S');
 ('N', 4.31, 'R'); ('O', 4.31, 'H'); ('M', 3.66, 'D'); (' ', 2.83, ' ');
 ('A', 2.58, 'L'); ('T', 2.38, 'U'); ('Q', 2.22, 'C'); ('B', 2.11, 'M');
 ('F', 2.11, 'F'); ('.', 2.04, 'Y'); ('R', 1.62, 'W'); ('S', 1.37, 'G');
 ('E', 1.06, 'P'); ('X', 0.97, 'B'); ('U', 0.25, 'V'); ('L', 0.16, 'K');
 ('V', 0.11, 'X'); ('J', 0.07, 'Q'); ('C', 0.02, 'J'); ('D', 0.02, 'Z')]

If anyone have any ideas that would put me in the right direction on how to tackle the problem i'd be very appreciative since i've been stuck on this problem for some while now.

Body:
I believe you are missing . frequency in the English alphabet (should be between D and L. When you'll add missing value to alphaFreq list both lists will be of same length and you'll be able to produce recommended changes map by zipping two ordered lists:

let changes =
    alphaFreq // list with letter frequency in the English alphabet
    |> List.zip cipherFreq // zipping with cipher frequency list
    |> List.map (fun ((cipherLetter,_), (alphaLetter,_)) -> (alphaLetter, cipherLetter))
    |> Map.ofList

Encoding test:

"HELLO WORLD" |> String.map (fun ch -> changes.[ch]) |> printfn "%s"
// OZAAYWRYNAM

To get a decoder map just swap letter order -> (cipherLetter, alphaLetter)


问:
Discord.js v12 Message On Ban
I don't know the syntax to do an action when a user is banned.
It's also fine for discord.js v11.5.2.</p>

答:
<GuildMember>.ban();
```

Get a guild member instance by something like msg.mentions.members.first()

Docs:

https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=ban

https://discord.js.org/#/docs/main/stable/examples/moderation

Title: Discord.js v12 Message On Ban

Body:
<GuildMember>.ban();

Get a guild member instance by something like msg.mentions.members.first()

Docs:

https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=ban

https://discord.js.org/#/docs/main/stable/examples/moderation


问:
Why isn't .equals recognizing my variable as the same string that I'm passing it?
So this little function is supposed to check if parentheses and brackets are matched next to each other. I feel like it should work and I've tried it a few different ways but I can't figure out how to check if my next char is what I expect it to be.

```<code>class Parenths {
    public boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i+=2) {
            String curr= String.valueOf(parens[i]);
            String next = String.valueOf(parens[i+1]);
            // System.out.println(next.equals(")");      --------> false
            // System.out.println(Object.equals(next, ")")); ----> error
            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                case "{": if (!next.equals("}")) return false;
                case "[": if (!next.equals("]")) return false;
            }
        }
        return true;
    }
}
</code>```

You can see the lines I printed to debug and it seems that .equals is not the right thing to use here? Can anyone explain why this isn't working?

PS. I realize I don't have to convert the string to a char array to compare elements, so unless that's the only fix, please don't point that out to me.

答:
Not tested, but it seems to be a problem of fall through. <s>Try to replace if (boolean) return boolean with return boolean, this should do the trick.</s>

The problem is that you don't have a break at the end of the cases, so if, for example, your first case is true, it will not stop execution and execute the 2nd test, which will be false. If you change your conditional statements to a direct return, you will not have this problem.

EDIT: Sorry, I read too quickly. Doing so will break your loop. Actually, you have to add a break at the end of the cases.

                case "(": if (!next.equals(")")) return false; break;
                case "{": if (!next.equals("}")) return false; break;
                case "[": if (!next.equals("]")) return false; break;

```

Body:
So this little function is supposed to check if parentheses and brackets are matched next to each other. I feel like it should work and I've tried it a few different ways but I can't figure out how to check if my next char is what I expect it to be.

class Parenths {
    public boolean isValid(String s) {
        char[] parens = s.toCharArray();
        if (parens.length == 0) return true;
        for (int i = 0; i < parens.length; i+=2) {
            String curr= String.valueOf(parens[i]);
            String next = String.valueOf(parens[i+1]);
            // System.out.println(next.equals(")");      --------> false
            // System.out.println(Object.equals(next, ")")); ----> error
            switch (curr) {
                case "(": if (!next.equals(")")) return false;
                case "{": if (!next.equals("}")) return false;
                case "[": if (!next.equals("]")) return false;
            }
        }
        return true;
    }
}

You can see the lines I printed to debug and it seems that .equals is not the right thing to use here? Can anyone explain why this isn't working?

PS. I realize I don't have to convert the string to a char array to compare elements, so unless that's the only fix, please don't point that out to me.


问:
How to move items to folder based on first three characters of file Mac
I am trying to move files such as

68 - Logo - Standard (B&W).pdf

to the corresponding folder which would be something like

68 - Oak Hill xyz

These folders are in a sorted logos folder, which has all of the folders in a list like

68 - Oak Hill Xyz
284 - Juniata Hill Xyz
294 - Highland Hill xyz

I have found multiple versions of different AppleScripts to accomplish this, but they seem to be outdated or no longer work properly when I try them. I have also tried this terminal script to no avail.

find . -type f -name “*pdf” -maxdepth 1 -exec bash -c 'mkdir -p “${0%%-*}”’ {} \; \
-exec bash -c 'mv "$0" "${0%%_*}"' {} \;

These pdf files are also in a different folder than the corresponding numbered folders are in.

答:
This should do what you want (making a few assumptions...):

```<code>property destination_folders : "/Users/<your name>/Downloads/Logos/BW PDF"

set files_to_sort to choose file with multiple selections allowed

tell application "System Events"
    repeat with a_file in files_to_sort
        set prefix to text 1 through 3 of (get name of a_file)
        set destination to my folderStartingWith(prefix)
        if destination is not false then
            move a_file to destination
        end
    end repeat
end tell

on folderStartingWith(txt)
    tell application "System Events"
        try
            set target_folder to first folder of folder destination_folders whose name begins with txt
        on error errstr
            display dialog errstr
            return false
        end try
        return target_folder
    end tell
end folderStartingWith
</code>```

Just substitute your user_name where it says  in the first line, run the script, and select the files you want to process in the dialog that appears. This will present an error message and skip over any files that do not have corresponding folders.

This does not follow folder hierarchies (though could be modified to do so). It could also be adapted into a droplet, folder action, or finder service if this is something that you have to do regularly.

Body:
This should do what you want (making a few assumptions...):

property destination_folders : "/Users/<your name>/Downloads/Logos/BW PDF"

set files_to_sort to choose file with multiple selections allowed

tell application "System Events"
    repeat with a_file in files_to_sort
        set prefix to text 1 through 3 of (get name of a_file)
        set destination to my folderStartingWith(prefix)
        if destination is not false then
            move a_file to destination
        end
    end repeat
end tell

on folderStartingWith(txt)
    tell application "System Events"
        try
            set target_folder to first folder of folder destination_folders whose name begins with txt
        on error errstr
            display dialog errstr
            return false
        end try
        return target_folder
    end tell
end folderStartingWith

Just substitute your user_name where it says  in the first line, run the script, and select the files you want to process in the dialog that appears. This will present an error message and skip over any files that do not have corresponding folders.

This does not follow folder hierarchies (though could be modified to do so). It could also be adapted into a droplet, folder action, or finder service if this is something that you have to do regularly.


问:
Get and Set a Single Cookie with Node.js HTTP Server
I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

```<code>var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');
</code>```

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

答:
I wrote this simple function just pass
req.headers.cookie and cookie name

```<code>const getCookieByName =(cookies,name)=>{
    const arrOfCookies = cookies.split(' ')
    let yourCookie = null

    arrOfCookies.forEach(element => {
        if(element.includes(name)){
            yourCookie = element.replace(name+'=','')
        }
    });
    return yourCookie
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

Body:
I wrote this simple function just pass
req.headers.cookie and cookie name

const getCookieByName =(cookies,name)=>{
    const arrOfCookies = cookies.split(' ')
    let yourCookie = null

    arrOfCookies.forEach(element => {
        if(element.includes(name)){
            yourCookie = element.replace(name+'=','')
        }
    });
    return yourCookie
}


问:
Java For Loop into Recursive function
```<code>public class For {
 public static void main(String[] args){
          for(int i=2; i<=1024; i *= 2){
           System.out.println("Count is: " + i);
      }
 }

public class While {
    public static void main(String[] args){
        int i = 1;
        while (i < 1024) {
            i *= 2;
            System.out.println("Count is: " + i);
      }
 }

public class DoWhile {
     public static void main(String[] args){
        int i = 1;
        if (i < 1024) {
            do { i*=2;
                System.out.println("Count is: " + i);
            } while (i < 1024);
        }
     }
</code>```

How would one convert the for loop/while loop so it does the same thing, but using a recursive function?

答:
public class Test1 {

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

    Test1 mainFunc = new Test1();

    int[] arr = {1,2,4,3,5,6};

    int start=0;
    int end=arr.length;
    mainFunc.callRecursiveFun(start, end, arr);
}

public int callRecursiveFun(int start, int end, int[] arr) {
    int arrLen = end;
    if(arrLen == 0) {
        return 0;
    } else {

    System.out.println("Loop Index at "+start +": "+arr[start]);

    }
    return callRecursiveFun(start+1, end-1, arr);
}
</code>```

}

ContentLicense: CC BY-SA 3.0

Title: Java For Loop into Recursive function

Body:
public class For {
 public static void main(String[] args){
          for(int i=2; i<=1024; i *= 2){
           System.out.println("Count is: " + i);
      }
 }

public class While {
    public static void main(String[] args){
        int i = 1;
        while (i < 1024) {
            i *= 2;
            System.out.println("Count is: " + i);
      }
 }

public class DoWhile {
     public static void main(String[] args){
        int i = 1;
        if (i < 1024) {
            do { i*=2;
                System.out.println("Count is: " + i);
            } while (i < 1024);
        }
     }

How would one convert the for loop/while loop so it does the same thing, but using a recursive function?

Body:
public class Test1 {

public static void main(String[] args) {

    Test1 mainFunc = new Test1();

    int[] arr = {1,2,4,3,5,6};

    int start=0;
    int end=arr.length;
    mainFunc.callRecursiveFun(start, end, arr);
}

public int callRecursiveFun(int start, int end, int[] arr) {
    int arrLen = end;
    if(arrLen == 0) {
        return 0;
    } else {

    System.out.println("Loop Index at "+start +": "+arr[start]);

    }
    return callRecursiveFun(start+1, end-1, arr);
}

}


答:
Use a custom Binding, and inside your set you can store your value:

```<code>Stepper(value: Binding<Int>(get: {
    self.timeBetweenMeals
}, set: {
    print($0) // here you can access your value with $0, store it here
    self.timeBetweenMeals = $0
}), in: 1...10, step: 1) {
    Text("Time Between Meals: \(timeBetweenMeals)h")
}
</code>```

Title: Save value on stepper SwiftUI

Body:
Use a custom Binding, and inside your set you can store your value:

Stepper(value: Binding<Int>(get: {
    self.timeBetweenMeals
}, set: {
    print($0) // here you can access your value with $0, store it here
    self.timeBetweenMeals = $0
}), in: 1...10, step: 1) {
    Text("Time Between Meals: \(timeBetweenMeals)h")
}