问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
To fix the problem, remove the expired root certificate from your domain certificate.

Go to https://whatsmychaincert.com

Test Your Server

If they confirm you you have an expired root certificate, download and use the .crt without this certificate.

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


来源: stackexchange

问:
debugg not going inside the loop
I am practicing on chars and i wrote a while loop that ends whenver i see a ";"

however when i am trying to debug it doesnt go inside the loop only at the last loop and I dont understand why

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    void main()
{
    char str[] = "abccc;";
    int i = 0;
    while (str[i] != ';')
    {
        i++;
        printf("%d \n",i);
    }

}
</code>```

thats the code, it works and realy simple but if I debugg to see it only goes inside the loop in the last time
I am not sure why and how to fix

答: I would suggest keep tracing even if it looks like its not going inside the loop. Sometimes the way the code is generated, the execution in the debugger is not linear. In fact as you keep tracing, keep a watch for output of the printf from the program.</p>

ContentLicense: CC BY-SA 4.0

Title: debugg not going inside the loop

Body:
I am practicing on chars and i wrote a while loop that ends whenver i see a ";"

however when i am trying to debug it doesnt go inside the loop only at the last loop and I dont understand why

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    void main()
{
    char str[] = "abccc;";
    int i = 0;
    while (str[i] != ';')
    {
        i++;
        printf("%d \n",i);
    }

}

thats the code, it works and realy simple but if I debugg to see it only goes inside the loop in the last time
I am not sure why and how to fix


问:
Select the value of an element by name
How to access the value of this input field that is checked by its name attribute using Javascript :

```<code><input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">
</code>```

I write this :

```<code>document.querySelector('input[name="rate"]:checked').value;
</code>```

but there is an error:

```<code>TypeError: document.querySelector(...) is null
</code>```

And I do not want to be checked any inputs by default

答:
What you're doing is absolutely correct! You just need to call this in onchange of the input. Since, you're calling this when no inputs are checked, you're getting this error.

function handleChange1(){
console.log(document.querySelector('input[name="rate"]:checked').value);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" onchange="handleChange1();" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4"></code>```

Title: Select the value of an element by name

Body:
How to access the value of this input field that is checked by its name attribute using Javascript :

<input type="radio" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">

I write this :

document.querySelector('input[name="rate"]:checked').value;

but there is an error:

TypeError: document.querySelector(...) is null

And I do not want to be checked any inputs by default

Body:
What you're doing is absolutely correct! You just need to call this in onchange of the input. Since, you're calling this when no inputs are checked, you're getting this error.

function handleChange1(){
console.log(document.querySelector('input[name="rate"]:checked').value);

}

<input type="radio" onchange="handleChange1();" class="radioButton" name="rate" value="1">
<input type="radio" class="radioButton" name="rate" value="2">
<input type="radio" class="radioButton" name="rate" value="3">
<input type="radio" class="radioButton" name="rate" value="4">


问:
IndexError: list index out of range (bimbam.py)
So I wanted to decompile a game using:

Python 2.7.15, Microsoft Visual C++ Compiler Package for Python 2.7, Cython 0.21.2 and the anaconda-master package.

I'm doing this on Windows 8.1 Build 9600 just so you know.

I followed this guide: (https://www.youtube.com/watch?v=lK_DDFpvlFw) But at 20:56 I get an error of bimbam.py (the tool to decompile the game). I reinstalled everything, used different versions, changed directories, followed other guides and used older anaconda-master packages but I can't get rid of the error. I think I know what the error means: "there is nothing in the place where something should be" or  "the script wants to access a variable/path which doesn't exist".

```<code>Traceback (most recent call last):
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 72, in <module>
    main()
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 38, in main
    input = sys.argv[1]
IndexError: list index out of range
</code>```

答: Ok I fixed the probleme, as you said "python bimbam.py " I tried >> python bimbam.py "path\of\the\game\exe" "path\of\the\output\foulder" and it goes. I don't know why, but now I'm happy that my morning wasn't for free! ... By the way, how dumb to answer my own question.</p>

Body:
So I wanted to decompile a game using:

Python 2.7.15, Microsoft Visual C++ Compiler Package for Python 2.7, Cython 0.21.2 and the anaconda-master package.

I'm doing this on Windows 8.1 Build 9600 just so you know.

I followed this guide: (https://www.youtube.com/watch?v=lK_DDFpvlFw) But at 20:56 I get an error of bimbam.py (the tool to decompile the game). I reinstalled everything, used different versions, changed directories, followed other guides and used older anaconda-master packages but I can't get rid of the error. I think I know what the error means: "there is nothing in the place where something should be" or  "the script wants to access a variable/path which doesn't exist".

Traceback (most recent call last):
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 72, in <module>
    main()
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 38, in main
    input = sys.argv[1]
IndexError: list index out of range


问:
Which SQL join should I use?
I have two tables and I need to join them.

Here is my tables and what I need

答:
This would be a left join, to bring all rows from the clients table, along with available rows in the applications table:

```<code>select
    c.date,
    c.group,
    c.count client_count,
    coalesce(a.count, 0) application_count
from clients-by_days c
left join applications_by_days a
    on a.date = c.date
    and a.group = c.group
</code>```

If there are missing matches in both tables, the you need a full join:

```<code>select
    date,
    group,
    coalesce(c.count, 0)client_count,
    coalesce(a.count, 0) application_count
from clients-by_days c
left join applications_by_days a
    using(date, group)
</code>```

Not all database support full join (and not all support the using()) syntax for join predicates).

Title: Which SQL join should I use?

Body:
This would be a left join, to bring all rows from the clients table, along with available rows in the applications table:

select
    c.date,
    c.group,
    c.count client_count,
    coalesce(a.count, 0) application_count
from clients-by_days c
left join applications_by_days a
    on a.date = c.date
    and a.group = c.group

If there are missing matches in both tables, the you need a full join:

select
    date,
    group,
    coalesce(c.count, 0)client_count,
    coalesce(a.count, 0) application_count
from clients-by_days c
left join applications_by_days a
    using(date, group)

Not all database support full join (and not all support the using()) syntax for join predicates).


问:
Adding / Deleting rows without the usual copy paste method
I have 60 blocks of calculations in my excel model. Based on certain criteria, the model will generate 2 numbers. One determines the number of rows to be added and the other determines the number of rows to be deleted.

Based on these two numbers I have to EITHER add OR delete rows to each of the 60 blocks of calculation. So for each block, either the rows will be added or deleted but not both. I have created range names against each block in the form of "Check" & 'a' where 'a' goes from 1 to 60. These ranges contain either the addition or the deletion number. Have also created another set of 60 range names by the name "PStart" & 'a' to get the start cell of each block of calculation.

I have prepared a code using the usual method of copying the data and inserting the required number of rows but it is taking over 5 mins to add even 5 rows to each block.

Is there any other way to do this to speed up the process? Thanks for the help!

```<code>        Dim Rows, a As Long
        Dim rng, prng, sheetnm_rng As String

        For a = 1 To 60
        rng = "Check" & a
        prng = "PStart" & a
        sheetnm_rng = Range(rng).Parent.Name
        Rows = Range(rng).Value

        If Rows > 0 Then
            Sheets(sheetnm_rng).Range(prng).End(xlDown).EntireRow.Copy
            Sheets(sheetnm_rng).Range(prng).End(xlDown).EntireRow.Offset(1, 0).Resize(Rows).Insert shift:=xlDown
        ElseIf Rows < 0 Then
            Sheets(sheetnm_rng).Range(prng).End(xlDown).Offset(Rows + 1).Resize(-Rows).EntireRow.Delete
        End If
        Next a
</code>```

答:
I found this, which you might find useful:

https://www.quora.com/What-steps-can-I-take-to-speed-up-for-loops-in-Excel-VBA

points 3 and 4 seem important for your case.

3.- If you are using an older version of Excel, turn off Screen updating at the beginning of your code, and don’t bother turning it back on. Excel will do that for you automatically when the code finishes execution.

4.- If you are copying and pasting values but don’t need to paste the formats—don’t. It is faster to set the .Value property of one range to the .Value property of another range.

Also you can try to measure your Sub running time with the different options you try, to try to keep the best, even if it is not as fast as you would like. Find a code example:

```<code>Sub CalculateRunTime_Seconds()
'PURPOSE: Determine how many seconds it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim StartTime As Double
Dim SecondsElapsed As Double

'Remember time when macro starts
  StartTime = Timer

'*****************************
'Insert Your Code Here...
'*****************************

'Determine how many seconds code took to run
  SecondsElapsed = Round(Timer - StartTime, 2)

'Notify user in seconds
  MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub
</code>```

Hope that helps

Body:
I have 60 blocks of calculations in my excel model. Based on certain criteria, the model will generate 2 numbers. One determines the number of rows to be added and the other determines the number of rows to be deleted.

Based on these two numbers I have to EITHER add OR delete rows to each of the 60 blocks of calculation. So for each block, either the rows will be added or deleted but not both. I have created range names against each block in the form of "Check" & 'a' where 'a' goes from 1 to 60. These ranges contain either the addition or the deletion number. Have also created another set of 60 range names by the name "PStart" & 'a' to get the start cell of each block of calculation.

I have prepared a code using the usual method of copying the data and inserting the required number of rows but it is taking over 5 mins to add even 5 rows to each block.

Is there any other way to do this to speed up the process? Thanks for the help!

        Dim Rows, a As Long
        Dim rng, prng, sheetnm_rng As String

        For a = 1 To 60
        rng = "Check" & a
        prng = "PStart" & a
        sheetnm_rng = Range(rng).Parent.Name
        Rows = Range(rng).Value

        If Rows > 0 Then
            Sheets(sheetnm_rng).Range(prng).End(xlDown).EntireRow.Copy
            Sheets(sheetnm_rng).Range(prng).End(xlDown).EntireRow.Offset(1, 0).Resize(Rows).Insert shift:=xlDown
        ElseIf Rows < 0 Then
            Sheets(sheetnm_rng).Range(prng).End(xlDown).Offset(Rows + 1).Resize(-Rows).EntireRow.Delete
        End If
        Next a

Body:
I found this, which you might find useful:

https://www.quora.com/What-steps-can-I-take-to-speed-up-for-loops-in-Excel-VBA

points 3 and 4 seem important for your case.

3.- If you are using an older version of Excel, turn off Screen updating at the beginning of your code, and don’t bother turning it back on. Excel will do that for you automatically when the code finishes execution.

4.- If you are copying and pasting values but don’t need to paste the formats—don’t. It is faster to set the .Value property of one range to the .Value property of another range.

Also you can try to measure your Sub running time with the different options you try, to try to keep the best, even if it is not as fast as you would like. Find a code example:

Sub CalculateRunTime_Seconds()
'PURPOSE: Determine how many seconds it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim StartTime As Double
Dim SecondsElapsed As Double

'Remember time when macro starts
  StartTime = Timer

'*****************************
'Insert Your Code Here...
'*****************************

'Determine how many seconds code took to run
  SecondsElapsed = Round(Timer - StartTime, 2)

'Notify user in seconds
  MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub

Hope that helps


问:
c# - DownloadString with WebClient - 404 Error
I am trying to download string from discord webhook :("https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK")

When I normally open the site with browser string is : {"message": "Unknown Webhook", "code": 10015}

But when I do that with WebClient:

```<code>           WebClient wc = new WebClient();
           string site = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";
           string x = wc.DownloadString(site);
</code>```

It gives an "404 Error". Is there a way to get that {"message": "Unknown Webhook", "code": 10015} string with c#?

答:
A rough guess would be that it's to do with the accept header. Check the documentation for the api, but my browser sent an additional 17 headers along with the request.

The simple answer would be, use HttpClient. It's recommended for new development and also gives the correct response here:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            var response = await client.GetAsync("https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK");
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}
```

<p>However that doesn't help if you can't. Also I'm intrigued now...</p>

<hr>

<p><strong>Ha!</strong> I should have listened to my own advice. For web service related stuff, you can't beat fiddler and postman. It turns out that the api is returning a custom 404 to the browser that has json content.</p>

<p>Unfortunately DownloadString sees the 404 and throws a WebException.</p>

<p>Here's an updated version that works, using HttpClient and WebClient.</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static readonly string url = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";

        static async Task Main(string[] args)
        {
            Console.WriteLine(await UseHttpClient(url));
            Console.WriteLine(await UseWebClient(url));
        }

        private static async Task<string> UseHttpClient(string url)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        private static async Task<string> UseWebClient(string url)
        {
            var client = new WebClient();
            try
            {
                var response = await client.DownloadStringTaskAsync(url);
                return response;
            }
            catch (WebException wex)
            {
                using (var s = wex.Response.GetResponseStream())
                {
                    var buffer = new byte[wex.Response.ContentLength];
                    var contentBytes = await s.ReadAsync(buffer, 0, buffer.Length);
                    var content = Encoding.UTF8.GetString(buffer);
                    return content;
                }
            }
        }
    }
}
</code>```

Body:
I am trying to download string from discord webhook :("https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK")

When I normally open the site with browser string is : {"message": "Unknown Webhook", "code": 10015}

But when I do that with WebClient:

           WebClient wc = new WebClient();
           string site = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";
           string x = wc.DownloadString(site);

It gives an "404 Error". Is there a way to get that {"message": "Unknown Webhook", "code": 10015} string with c#?

Body:
A rough guess would be that it's to do with the accept header. Check the documentation for the api, but my browser sent an additional 17 headers along with the request.

The simple answer would be, use HttpClient. It's recommended for new development and also gives the correct response here:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            var response = await client.GetAsync("https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK");
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
    }
}

However that doesn't help if you can't. Also I'm intrigued now...

Ha! I should have listened to my own advice. For web service related stuff, you can't beat fiddler and postman. It turns out that the api is returning a custom 404 to the browser that has json content.

Unfortunately DownloadString sees the 404 and throws a WebException.

Here's an updated version that works, using HttpClient and WebClient.

using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace discordapi_headers
{
    class Program
    {
        static readonly string url = "https://discordapp.com/api/webhooks/704770710509453432/GdR4absQHKDKjUiNMpw3aIpX2tx-9Z7nmPE2Sn3TUkQDM12zUczaV-m80orh7WGVzvGK";

        static async Task Main(string[] args)
        {
            Console.WriteLine(await UseHttpClient(url));
            Console.WriteLine(await UseWebClient(url));
        }

        private static async Task<string> UseHttpClient(string url)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        private static async Task<string> UseWebClient(string url)
        {
            var client = new WebClient();
            try
            {
                var response = await client.DownloadStringTaskAsync(url);
                return response;
            }
            catch (WebException wex)
            {
                using (var s = wex.Response.GetResponseStream())
                {
                    var buffer = new byte[wex.Response.ContentLength];
                    var contentBytes = await s.ReadAsync(buffer, 0, buffer.Length);
                    var content = Encoding.UTF8.GetString(buffer);
                    return content;
                }
            }
        }
    }
}


问:
Syntax error near unexpected token `;' when running a command in Bash
In Bash in the terminal, it is impossible to run a command that ends with and & (being sent to the background) followed by another command (obviously with a ; between them). Why is that? Why can't you run anything with &;  or $ ; in it?

I'm trying to recreate a 502 error and was trying to DoS a specific page in a testing server. I was trying to run this:

```<code>while true; do curl -s https://some.site.com/someImage.jpg > /dev/null &; echo blah ; done
</code>```

as a "one-liner" in the terminal. However, I got this error:

-bash: syntax error near unexpected token `;'

However the commands work individually, and when I run the curl command not in the background it works as a loop as well. It also works when it write a one line script, "/tmp/curlBack.sh" that includes only

```<code>curl -s https://some.site.com/someImage.jpg > /dev/null &
</code>```

And then run

```<code>while true; do bash /tmp/curlBack.sh ; echo blah ; done
</code>```

Why am I getting this error and how do I fix it?

答:
The problem is with the semi-colon after the ampersand (&):

An ampersand does the same thing as a semicolon or newline in that it indicates the end of a command, but it causes Bash to execute the command asynchronously.
  BashSheet

Basically, it's as if you were to put double semi-colons back to back, that would cause a syntax error too.

To fix this problem, you simply need to remove the semi-colon, I tested it that way and it seems to be working:

while true; do curl -s https://some.site.com/someImage.jpg > /dev/null & echo blah ; done
```

Body:
In Bash in the terminal, it is impossible to run a command that ends with and & (being sent to the background) followed by another command (obviously with a ; between them). Why is that? Why can't you run anything with &;  or $ ; in it?

I'm trying to recreate a 502 error and was trying to DoS a specific page in a testing server. I was trying to run this:

while true; do curl -s https://some.site.com/someImage.jpg > /dev/null &; echo blah ; done

as a "one-liner" in the terminal. However, I got this error:

-bash: syntax error near unexpected token `;'

However the commands work individually, and when I run the curl command not in the background it works as a loop as well. It also works when it write a one line script, "/tmp/curlBack.sh" that includes only

curl -s https://some.site.com/someImage.jpg > /dev/null &

And then run

while true; do bash /tmp/curlBack.sh ; echo blah ; done

Why am I getting this error and how do I fix it?


问:
Can my docker image connect with a database running on same machine without network configuration?
I have created a docker image of my web application. I have a cassandra database running on my laptop and I am starting the container of my web application from the same laptop. The uri to connect to database is localhost:9042. However, the image is not able to connect with the database. Do I need to do some network configuration for the container to connect to the database?

```<code>[trace] CassandraRepositoryComponents - database will connect using parameters uri: cassandra://localhost:9042/, cluster name: myCluster
[trace] s.d.c.CassandraConnectionUri - created logger Logger[services.db.cassandra.CassandraConnectionUri]
[trace] s.d.c.CassandraConnectionManagementService - creating session with uri CassandraConnectionUri(cassandra://localhost:9042/) and cluster name myCluster
[trace] s.d.c.CassandraConnectionManagementService - exception in connecting with database com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect))
Oops, cannot start the server.
</code>```

docker file

```<code>FROM openjdk:8
RUN mkdir deploy
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf
</code>```

Cassandra is running as a standalone application

答:
Run your docker container with the host network mode which enable that container to use the host network.

```<code>docker run --network="host" -p 9000:9000 IMAGENAME
</code>```

and then access your application on http://localhost:9000 and shouldn't see any errors.

1 suggestion for Dockerfile, you don't have to mkdir if you are specifying the WORKDIR as it will create it for you.

```<code>FROM openjdk:8
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf
</code>```

Body:
I have created a docker image of my web application. I have a cassandra database running on my laptop and I am starting the container of my web application from the same laptop. The uri to connect to database is localhost:9042. However, the image is not able to connect with the database. Do I need to do some network configuration for the container to connect to the database?

[trace] CassandraRepositoryComponents - database will connect using parameters uri: cassandra://localhost:9042/, cluster name: myCluster
[trace] s.d.c.CassandraConnectionUri - created logger Logger[services.db.cassandra.CassandraConnectionUri]
[trace] s.d.c.CassandraConnectionManagementService - creating session with uri CassandraConnectionUri(cassandra://localhost:9042/) and cluster name myCluster
[trace] s.d.c.CassandraConnectionManagementService - exception in connecting with database com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.TransportException: [localhost/127.0.0.1:9042] Cannot connect))
Oops, cannot start the server.

docker file

FROM openjdk:8
RUN mkdir deploy
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf

Cassandra is running as a standalone application

Body:
Run your docker container with the host network mode which enable that container to use the host network.

docker run --network="host" -p 9000:9000 IMAGENAME

and then access your application on http://localhost:9000 and shouldn't see any errors.

1 suggestion for Dockerfile, you don't have to mkdir if you are specifying the WORKDIR as it will create it for you.

FROM openjdk:8
WORKDIR deploy
COPY target/universal/myapp-1.0.zip .

COPY conf/logback_dev.xml ./logback.xml
COPY conf/application_dev.conf ./application.conf
RUN unzip myapp-1.0.zip
RUN chmod +x myapp-1.0/bin/myapp
EXPOSE 9000
ENTRYPOINT myapp-1.0/bin/myapp -Dplay.http.secret.key=changemeplease -Dlogger.file=/deploy/logback.xml -Dconfig.file=/deploy/application.conf


问:
CSS selector that excludes some child elements
I have this HTML:

```<code><div class="item-cost">
    <a data-passage="Shop" class="link-internal macro-link" tabindex="0" id="Link1">$10 <sup>1</sup></a>
</div>
</code>```

I am writing this testcafe code to get the cost:

```<code>.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1')
</code>```

This fails because the inner text is $11, not $1. The reason it's failing is because the contents of the sup element are included in the inner text. Is there any way I can modify the selector above so that it gives me the inner text without including the sup element? I cannot modify the HTML.

答:
I hesitate to add my 2 cents to this discussion as I just happened to stumble into it and am not really familiar with testcafe. But those 2 cents are too long for a comment, so I figure I'll post it as a possible answer  and you make of it what you will.

It seems to me that what you are trying to do is select the text of the  node while at the same time excluding that of its  child node. An operation like that is easily achieved by using an xpath expression like:

```<code>//div/a/text()
</code>```

Unfortunately, testcafe doesn't seem to support xpath and there is no intention to do it in the future. The main reason seems to be the existence of utilities that can convert xpath to css selectors for use with testcafe.

Unfortunately again, xpath and css selctors aren't equivalent and there are things you can do with xpath that cannot (currently) be done with css selectors. And this case is probably one of them.

To the rescue may comes this utility for adding xpath support to testcafe. So I would try using that with the xpath expression above and see if it works for you. If not, no harm done, I guess.

Body:
I have this HTML:

    $10 1

I am writing this testcafe code to get the cost:

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1')

This fails because the inner text is $11, not $1. The reason it's failing is because the contents of the sup element are included in the inner text. Is there any way I can modify the selector above so that it gives me the inner text without including the sup element? I cannot modify the HTML.

Body:
I hesitate to add my 2 cents to this discussion as I just happened to stumble into it and am not really familiar with testcafe. But those 2 cents are too long for a comment, so I figure I'll post it as a possible answer  and you make of it what you will.

It seems to me that what you are trying to do is select the text of the <a> node while at the same time excluding that of its <sup> child node. An operation like that is easily achieved by using an xpath expression like:

//div/a/text()

Unfortunately, testcafe doesn't seem to support xpath and there is no intention to do it in the future. The main reason seems to be the existence of utilities that can convert xpath to css selectors for use with testcafe.

Unfortunately again, xpath and css selctors aren't equivalent and there are things you can do with xpath that cannot (currently) be done with css selectors. And this case is probably one of them.

To the rescue may comes this utility for adding xpath support to testcafe. So I would try using that with the xpath expression above and see if it works for you. If not, no harm done, I guess.


问:
Update title of button in for loop in swift UIButton
I have been trying to change the title of my UIButton every iteration of a for loop in swift, but it doesn't work as the titles are not being updated.
Heres the code:

```<code>@IBOutlet var generateButton: UIButton!
var x: Double = 0.0
for i in 0...nTokens {
    x = (Double(i)/Double(nTokens)) * 100
    print(self.generateButton.isHighlighted)
    self.generateButton.setTitle("\(x) %", for: .highlighted)
    self.generateButton.titleLabel!.font = UIFont.systemFont(ofSize: 20)
    sleep(3)
}
</code>```

Have already linked generateButton to the correct button in the view, and self.generateButton.isHighlighted always print true. What am I doing wrong? Thanks

答:
self.generateButton.setTitle("\(x) %", for: .normal)
```

Body:
I have been trying to change the title of my UIButton every iteration of a for loop in swift, but it doesn't work as the titles are not being updated.
Heres the code:

@IBOutlet var generateButton: UIButton!
var x: Double = 0.0
for i in 0...nTokens {
    x = (Double(i)/Double(nTokens)) * 100
    print(self.generateButton.isHighlighted)
    self.generateButton.setTitle("\(x) %", for: .highlighted)
    self.generateButton.titleLabel!.font = UIFont.systemFont(ofSize: 20)
    sleep(3)
}

Have already linked generateButton to the correct button in the view, and self.generateButton.isHighlighted always print true. What am I doing wrong? Thanks


问:
Heroku: "No default language could be detected for this app" error thrown for node app
I am learning NodeJS and the course I'm following has several projects, arranged by sections. I have all the projects under one main folder, which is also a git repository.

Each of these subfolders in the main folder is a node project by itself, complete with package.json and related dependencies in node_modules. The problem is when I tried to push the node app in one such folder(todo-api) to heroku, I get the following error -

```<code>remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to agile-forest-32749.
remote:
To https://git.heroku.com/agile-forest-32749.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/agile-forest-32749.git'
</code>```

This is the directory structure for the project -

I decided to refactor out the todo-api subfolder into a new project all by itself, and this time the push to Heroku works just fine -

I don't understand why I get the "no default language" error, especially when the node app is exactly the same in both places. Any thoughts?

答: You need to set a language for the project. Without using the terminal, go to Heroku project. Click on settings, scroll down Build Backbacks and add a language (nodejs, etc).</p>

ContentLicense: CC BY-SA 3.0

Body:
I am learning NodeJS and the course I'm following has several projects, arranged by sections. I have all the projects under one main folder, which is also a git repository.

Each of these subfolders in the main folder is a node project by itself, complete with package.json and related dependencies in node_modules. The problem is when I tried to push the node app in one such folder(todo-api) to heroku, I get the following error -

remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to agile-forest-32749.
remote:
To https://git.heroku.com/agile-forest-32749.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/agile-forest-32749.git'

This is the directory structure for the project -

I decided to refactor out the todo-api subfolder into a new project all by itself, and this time the push to Heroku works just fine -

I don't understand why I get the "no default language" error, especially when the node app is exactly the same in both places. Any thoughts?


问:
Maven JarJar Plugin: Exclude 'provided' scope?
Is there a way to have the Maven JarJar plugin exclude items in the 'provided' scope? This seems pretty straightforward... if something is provided, why would I want to include it in my megajar?</p>

答: Adding a "zap" rule might help. Example here</p>


问:
How to cancel pull request in Sourcetree
Well, I tried to merge the master branch (red-one) and statistics (blue-one) via GUI client of Bitbucket. I'd like to update the master branch by statistics branch. But I made an opposite action. And now I have a commit with conflicts. I want to cancel this commit and corresponding pull request. How to do that via GUI?

答:
You need a git checkout on the previous commit where everything was still correct (before doing the opposite action, git-merge wrong way). On the command line that will looks like:

git checkout 66dc132

Make right click on this commit where before git-merge the wrong way, and then click on Checkout.

Then you can make the merge-command the right way ;)


问:
no tests found with test runner JUnit 5 even after adding Junit Library
I wanted to test my classes in Java using JUnit 5, in Eclipse. all the files are in the same package. My test file is correct (syntax wise) and i get no errors from eclipse regarding the file itself. Only when i try to run the testfile, do i get the error: No tests found with test runner JUnit 5

I am really frustrated because i cannot seem to find the issue. i have included the JUnit-Library in my module path. I dont know if posting my code makes any sense, because i think it might be a different issue. Does anyone have any experience with this kind of error?

edit: here's a screenshot of my run configurations

答: You can add Junit 5 libraries to your build path by right clicking on the project -> properties -> Java Build Path -> Add library -> Junit -> Junit 5 -> Finish to run the test in your IDE.</p>


问:
Passing a heap as an argument
I tried to make several functions which passes a heap as a parameter through the code below. However, it did not turned out to be what I expected it to be.

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

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp;

        upHeap_min2(heap, parentIdx);
    }
}

void pushValue (int *heap, int count, int value)
{
    count++;
    heap[count] = value;
    upHeap_min2(heap, count);
}

void view(int *heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i < count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int count = -1;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}
</code>```

Function to get parent index:

```<code>int getParentIdx (int index)
{
    return (index-1)/2;
}
</code>```

The code above should have printed

```<code>10 20 40 90 30
</code>```

But instead it printed nothing. I have also thought to pass it as a double pointer as well but i did not work. Does this mean I cannot pass a heap as a parameter (which means i have to declare the heap as a global variable) or there is another way to do this?

答:
This is a valid solution, let me explain

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

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp;

        upHeap_min2(heap, parentIdx);
    }
}
int getParentIdx (int index)
{
    return (index-1)/2;
}

void pushValue (int *heap, int *count, int value)
{
    *count = *count + 1;
    heap[*count] = value;
    upHeap_min2(heap, *count);
}

void view(int *heap, int *count)
{
    printf("Values inside heap: ");
    for (int i = 0; i <= *count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int conter = -1; //new var
    int *count = &conter;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}
</code>```

The main error is that you were passing counter as simple variable, and you should do it as a pointer, this causes that counter never get incremented, so I created a pointer to that variable and now counter is incremented and it prints what you expect. In addition I have modified the body of the for you were using to print the values

Title: Passing a heap as an argument

Body:
I tried to make several functions which passes a heap as a parameter through the code below. However, it did not turned out to be what I expected it to be.

#include<stdio.h>

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp;

        upHeap_min2(heap, parentIdx);
    }
}

void pushValue (int *heap, int count, int value)
{
    count++;
    heap[count] = value;
    upHeap_min2(heap, count);
}

void view(int *heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i < count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int count = -1;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}

Function to get parent index:

int getParentIdx (int index)
{
    return (index-1)/2;
}

The code above should have printed

10 20 40 90 30

But instead it printed nothing. I have also thought to pass it as a double pointer as well but i did not work. Does this mean I cannot pass a heap as a parameter (which means i have to declare the heap as a global variable) or there is another way to do this?

Body:
This is a valid solution, let me explain

#include<stdio.h>

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp;

        upHeap_min2(heap, parentIdx);
    }
}
int getParentIdx (int index)
{
    return (index-1)/2;
}

void pushValue (int *heap, int *count, int value)
{
    *count = *count + 1;
    heap[*count] = value;
    upHeap_min2(heap, *count);
}

void view(int *heap, int *count)
{
    printf("Values inside heap: ");
    for (int i = 0; i <= *count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int conter = -1; //new var
    int *count = &conter;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}

The main error is that you were passing counter as simple variable, and you should do it as a pointer, this causes that counter never get incremented, so I created a pointer to that variable and now counter is incremented and it prints what you expect. In addition I have modified the body of the for you were using to print the values


问:
PHP naming conventions?
I'm coding smt right now, and am a little bit peeved by the fact that PHP sometimes calls its functions with underscore, and sometimes as one word. What's up with that?

Example:

int strlen(string $str)

and

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

I'm hoping that there is a good reason for this, and would really like to know what it is.

答:
Welcome to php. This has been a topic so many times.
Bottom line is, the only way to get over it is using a php centric ide/editor that suggests.
By the way that is just half the problem you will also see functions where the order is oposite.
Like

```<code>(mixed $needle , array $haystack)
</code>```

and then

```<code>(array $haystack , string $needle)
</code>```

So get used to it, or get out is the motto.

Title: PHP naming conventions?

Body:
Welcome to php. This has been a topic so many times.
Bottom line is, the only way to get over it is using a php centric ide/editor that suggests.
By the way that is just half the problem you will also see functions where the order is oposite.
Like

(mixed $needle , array $haystack)

and then

(array $haystack , string $needle)

So get used to it, or get out is the motto.


答:
Probably something like this:

```<code>SELECT c.Data, c.Group, c.Count AS 'Users Count', a.Count AS 'Application Count'
   FROM clients c
   LEFT JOIN applications a
     ON c.Data=a.DATA
     AND c.Group=a.Group
</code>```

You can test it here.

Title: Which SQL join should I use?

Body:
I have two tables and I need to join them.

Here is my tables and what I need

Body:
Probably something like this:

SELECT c.Data, c.Group, c.Count AS 'Users Count', a.Count AS 'Application Count'
   FROM clients c
   LEFT JOIN applications a
     ON c.Data=a.DATA
     AND c.Group=a.Group

You can test it here.


问:
ModuleNotFoundError - Cannot import a python file even though python file exists
I have a project structure like this:

```<code>.
├── .venv
|     └── bin
|          └── python
├── config
│     └── conf.py
├── utils
│   └── test.py
└── requirements.txt
</code>```

Each of the directories above have an __init__.py file so they should be picked up as a Python package.

I am unable to import config into the utils.test.py script.

The error I encounter is:

```<code>File "./utils/test.py", line 2, in <module>
import config.conf
ModuleNotFoundError: No module named 'config'
</code>```

My Python path is "./.venv/bin/python".

Can someone help me resolve this issue so I can import files from different sub-directories?

Thanks!

答:
Add empty __init__.py file to the config directory in order to identify it as a python package. See more here

Updating following the comment -
Add the folder path to the system path -

```<code>import os
import sys
sys.path.insert(0, os.path.dirname(os.getcwd()))
import config.conf
</code>```

Body:
I have a project structure like this:

.
├── .venv
|     └── bin
|          └── python
├── config
│     └── conf.py
├── utils
│   └── test.py
└── requirements.txt

Each of the directories above have an __init__.py file so they should be picked up as a Python package.

I am unable to import config into the utils.test.py script.

The error I encounter is:

File "./utils/test.py", line 2, in <module>
import config.conf
ModuleNotFoundError: No module named 'config'

My Python path is "./.venv/bin/python".

Can someone help me resolve this issue so I can import files from different sub-directories?

Thanks!

Body:
Add empty __init__.py file to the config directory in order to identify it as a python package. See more here

Updating following the comment -
Add the folder path to the system path -

import os
import sys
sys.path.insert(0, os.path.dirname(os.getcwd()))
import config.conf


问:
How to avoid System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length
I'm trying to rewrite some data in DB using Ajax, after passing it to controller I always have the same error: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length.

my Ajax code:

```<code>tab.on("click", ".edit", function (e) {

    var tr = $(this).closest("tr");
    var id = tr.data("id");
    var fse = $(this).closest("tr").find(".FSE").text();

    var field = $(this).closest("tr").find(".ui-widget");
    var mon = field.find(".desc_NumM");

    var monC = mon.css("background-color");
    var tue = field.find(".desc_NumT");
    var tueC = tue.css("background-color");
    var wed = field.find(".desc_NumW");
    var wedC = wed.css("background-color");
    var thur = field.find(".desc_NumTr");
    var thurC = thur.css("background-color");
    var fri = field.find(".desc_NumF");
    var friC = fri.css("background-color");
    var sat = field.find(".desc_NumSa");
    var satC = sat.css("background-color");
    var sun = field.find(".desc_NumSu");
    var sunC = sun.css("background-color");

    var monVal = mon.text();
    var tueVal = tue.text();
    var wedVal = wed.text();
    var thurVal = thur.text();
    var friVal = fri.text();
    var satrVal = sat.text();
    var sunVal = sun.text();

            $.ajax({
                type: "POST",
                url: "/Home/UpdateWeek",
                data: {
                    id: id,
                    FSE:fse,
                    Monday: monVal,
                    Tuesday: tueVal,
                    Wednesday: wedVal,
                    Thursday: thurVal,
                    Friday: friVal,
                    Saturday: satrVal,
                    Sunday: sunVal,
                    MonColor: monC,
                    TueColor: tueC,
                    WedColor: wedC,
                    ThurColor: thurC,
                    FriColor: friC,
                    SatColor: satC,
                    SunColor: sunC

                },
                dataType: "JSON",
                success: function (data) {

                    alert("Week for: " + fse + " changed!");
                    $('#weekEvents').load(loadWeekData());
                },
                error: function () {
                    alert("Failed, try again");
                }
            });
    });
</code>```

And here is my controller:

```<code>    [HttpPost]
    public JsonResult UpdateWeek(int id, EventsWeek w)
    {

        using (WeekEventsDBEntities db = new WeekEventsDBEntities())
        {
            EventsWeek ewupt = db.EventsWeeks.Where(x => x.Id == id).FirstOrDefault();
            ewupt.Monday = w.Monday.Substring(0, 100);
            ewupt.Tuesday = w.Tuesday.Substring(0, 100);
            ewupt.Wednesday = w.Wednesday.Substring(0, 100);
            ewupt.Thursday = w.Thursday.Substring(0, 100);
            ewupt.Friday = w.Friday.Substring(0, 100);
            ewupt.Saturday = w.Saturday.Substring(0, 100);
            ewupt.Sunday = w.Sunday.Substring(0, 100);
            ewupt.MonColor = w.MonColor.Substring(0, 50);
            ewupt.TueColor = w.TueColor.Substring(0, 10);
            ewupt.WedColor = w.WedColor.Substring(0, 10);
            ewupt.ThurColor = w.ThurColor.Substring(0, 10);
            ewupt.FriColor = w.FriColor.Substring(0, 10);
            ewupt.SatColor = w.SatColor.Substring(0, 10);
            ewupt.SunColor = w.SunColor.Substring(0, 10);
            ewupt.FSE = w.FSE.Substring(0, 20);
            db.SaveChanges();

        }
        return Json(true, JsonRequestBehavior.AllowGet);

    }
</code>```

debbuger always tell that there is a problem with "Substring(0, 50);". But the funny thing is, if I change "ewupt.MonColor = w.MonColor.Substring(0, 50);" to "ewupt.MonColor = w.MonColor.Substring(0, 10);" it will work ,but not like it should be. Anyway it will be no more error ans data will be passed to my DB... What I'm doing wrong here?

答: Because you are trying to access the string which is beyond the length of the string. </p>

Body:
I'm trying to rewrite some data in DB using Ajax, after passing it to controller I always have the same error: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length.

my Ajax code:

tab.on("click", ".edit", function (e) {

    var tr = $(this).closest("tr");
    var id = tr.data("id");
    var fse = $(this).closest("tr").find(".FSE").text();

    var field = $(this).closest("tr").find(".ui-widget");
    var mon = field.find(".desc_NumM");

    var monC = mon.css("background-color");
    var tue = field.find(".desc_NumT");
    var tueC = tue.css("background-color");
    var wed = field.find(".desc_NumW");
    var wedC = wed.css("background-color");
    var thur = field.find(".desc_NumTr");
    var thurC = thur.css("background-color");
    var fri = field.find(".desc_NumF");
    var friC = fri.css("background-color");
    var sat = field.find(".desc_NumSa");
    var satC = sat.css("background-color");
    var sun = field.find(".desc_NumSu");
    var sunC = sun.css("background-color");

    var monVal = mon.text();
    var tueVal = tue.text();
    var wedVal = wed.text();
    var thurVal = thur.text();
    var friVal = fri.text();
    var satrVal = sat.text();
    var sunVal = sun.text();

            $.ajax({
                type: "POST",
                url: "/Home/UpdateWeek",
                data: {
                    id: id,
                    FSE:fse,
                    Monday: monVal,
                    Tuesday: tueVal,
                    Wednesday: wedVal,
                    Thursday: thurVal,
                    Friday: friVal,
                    Saturday: satrVal,
                    Sunday: sunVal,
                    MonColor: monC,
                    TueColor: tueC,
                    WedColor: wedC,
                    ThurColor: thurC,
                    FriColor: friC,
                    SatColor: satC,
                    SunColor: sunC

                },
                dataType: "JSON",
                success: function (data) {

                    alert("Week for: " + fse + " changed!");
                    $('#weekEvents').load(loadWeekData());
                },
                error: function () {
                    alert("Failed, try again");
                }
            });
    });

And here is my controller:

    [HttpPost]
    public JsonResult UpdateWeek(int id, EventsWeek w)
    {

        using (WeekEventsDBEntities db = new WeekEventsDBEntities())
        {
            EventsWeek ewupt = db.EventsWeeks.Where(x => x.Id == id).FirstOrDefault();
            ewupt.Monday = w.Monday.Substring(0, 100);
            ewupt.Tuesday = w.Tuesday.Substring(0, 100);
            ewupt.Wednesday = w.Wednesday.Substring(0, 100);
            ewupt.Thursday = w.Thursday.Substring(0, 100);
            ewupt.Friday = w.Friday.Substring(0, 100);
            ewupt.Saturday = w.Saturday.Substring(0, 100);
            ewupt.Sunday = w.Sunday.Substring(0, 100);
            ewupt.MonColor = w.MonColor.Substring(0, 50);
            ewupt.TueColor = w.TueColor.Substring(0, 10);
            ewupt.WedColor = w.WedColor.Substring(0, 10);
            ewupt.ThurColor = w.ThurColor.Substring(0, 10);
            ewupt.FriColor = w.FriColor.Substring(0, 10);
            ewupt.SatColor = w.SatColor.Substring(0, 10);
            ewupt.SunColor = w.SunColor.Substring(0, 10);
            ewupt.FSE = w.FSE.Substring(0, 20);
            db.SaveChanges();

        }
        return Json(true, JsonRequestBehavior.AllowGet);

    }

debbuger always tell that there is a problem with "Substring(0, 50);". But the funny thing is, if I change "ewupt.MonColor = w.MonColor.Substring(0, 50);" to "ewupt.MonColor = w.MonColor.Substring(0, 10);" it will work ,but not like it should be. Anyway it will be no more error ans data will be passed to my DB... What I'm doing wrong here?


问:
can any one suggest a good math function in javascript to round integer?
i have to round the value from 2.3456789 to 2.345 .

After . there must be three number only remaining should be removed

答:
There is value.toFixed(3), but that will round up to 2.346.

You could just parseInt(value * 1000) / 1000 if you really don't want to round.

You may need to ensure value is a number first:

```<code>value = new Number(value)
</code>```

Now if value is user input, it's possible that it might now be NaN (Not a Number).

You can't do if(value == NaN) to check, NaN is never equal to anything (not even itself), you must use the isNaN(value) function.

Body:
There is value.toFixed(3), but that will round up to 2.346.

You could just parseInt(value * 1000) / 1000 if you really don't want to round.

You may need to ensure value is a number first:

value = new Number(value)

Now if value is user input, it's possible that it might now be NaN (Not a Number).

You can't do if(value == NaN) to check, NaN is never equal to anything (not even itself), you must use the isNaN(value) function.


问:
C# Firebase Admin SDK Push Notifications
I want to send push notifications to a mobile app, so I installed Firebase Admin SDK to my .Net project.
I followed the instructions on Firebase docs, but when I call the SendAsync from the SDK, it just hangs. Any idea why it would hang? Am I missing steps?

Here is my API code (Note this is only demo code to get it to work):

```<code>public async void SendPushNotification()
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("path to json file"),
            });

            var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";

            var message = new FirebaseAdmin.Messaging.Message()
            {
                Token = registrationToken,
            };

            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);

            Console.WriteLine("Successfully sent message: " + response);
        }

</code>```

答:
you have a deadlock because SendAsync will never finish.
if you are calling from ui thread you need to consider using ConfigureAwait(false)
so your snippet will look like below:

```<code>public async void SendPushNotification()
    {
        FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile("path to json file"),
        });

        var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";

        var message = new FirebaseAdmin.Messaging.Message()
        {
            Token = registrationToken,
        };

        string response = await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(false);

        Console.WriteLine("Successfully sent message: " + response);
    }
</code>```

Body:
I want to send push notifications to a mobile app, so I installed Firebase Admin SDK to my .Net project.
I followed the instructions on Firebase docs, but when I call the SendAsync from the SDK, it just hangs. Any idea why it would hang? Am I missing steps?

Here is my API code (Note this is only demo code to get it to work):

public async void SendPushNotification()
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("path to json file"),
            });

            var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";

            var message = new FirebaseAdmin.Messaging.Message()
            {
                Token = registrationToken,
            };

            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);

            Console.WriteLine("Successfully sent message: " + response);
        }

Body:
you have a deadlock because SendAsync will never finish.
if you are calling from ui thread you need to consider using ConfigureAwait(false)
so your snippet will look like below:

public async void SendPushNotification()
    {
        FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile("path to json file"),
        });

        var registrationToken = "fqCo_-tXKvY:APA91bGQ47Q2egnqn4Ml...";

        var message = new FirebaseAdmin.Messaging.Message()
        {
            Token = registrationToken,
        };

        string response = await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(false);

        Console.WriteLine("Successfully sent message: " + response);
    }


答:
try checking before using subString()</p>

```<code>if(w.MonColor.Length > 50)
{
    ewupt.MonColor = w.MonColor.Substring(0, 50);
}
</code>```

Title: How to avoid System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length

Body:
try checking before using subString()

if(w.MonColor.Length > 50)
{
    ewupt.MonColor = w.MonColor.Substring(0, 50);
}


问:
OpenCV throws errors after applying numpy transformations
I've run into a curious error. After applying np.flip, cv2.rectangle is throwing an error. Here's a minimal reproducible example:

```<code>image = np.random.choice(255,(50,50,3)).astype(np.uint8)
image_180 = np.flip(image.copy())
x1,y1,x2,y2 = 20,20,30,30
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0),1)
cv2.rectangle(image_180,(x1,y1),(x2,y2),(0,255,0),1)
</code>```

Both image and image_180 are of the type numpy.ndarray, and are of dtype np.uint8. However, the second call to rectangle throws the following error:

```<code>TypeError: an integer is required (got type tuple)
</code>```

Which makes no sense. I'm assuming this is a bug or something with a lazy fix.

答:
image_180 = np.flip(image.copy())

your code is slightly confused (deep copy position),

below code works for me:

```<code>image_180 = np.flip(image).copy()
</code>```

Body:
I've run into a curious error. After applying np.flip, cv2.rectangle is throwing an error. Here's a minimal reproducible example:

image = np.random.choice(255,(50,50,3)).astype(np.uint8)
image_180 = np.flip(image.copy())
x1,y1,x2,y2 = 20,20,30,30
cv2.rectangle(image,(x1,y1),(x2,y2),(0,255,0),1)
cv2.rectangle(image_180,(x1,y1),(x2,y2),(0,255,0),1)

Both image and image_180 are of the type numpy.ndarray, and are of dtype np.uint8. However, the second call to rectangle throws the following error:

TypeError: an integer is required (got type tuple)

Which makes no sense. I'm assuming this is a bug or something with a lazy fix.

Body:
image_180 = np.flip(image.copy())

your code is slightly confused (deep copy position),

below code works for me:

image_180 = np.flip(image).copy()


答:
Your pushValue function takes the count argument by value (which means the function receives a copy of the data), so it is never modified in the main function. Instead, you should pass count as a pointer, and (thus) will need to dereference it inside the function:

void pushValue(int* heap, int* count, int value)
{
    ++(*count);
    heap[*count] = value;
    upHeap_min2(heap, *count);
}
```

<p>Then, in <code>main</code>, you should call it using the <em>address</em> of <code>count</code>:</p>

<pre class="lang-c prettyprint-override"><code>    pushValue(heapDemo, &count, 30); // And similarly for the other calls
</code>```

Also, the loop in your view function stops one short of the end. Change the loop limit to i <= count. (This function uses count but doesn't modify it, so passing by value is OK.):

void view(int* heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i <= count; i++) {
        printf("%d ", heap[i]);
    }
    printf("\n");
}
```

Feel free to ask for further clarification and/or explanation.

Title: Passing a heap as an argument

Body:
Your pushValue function takes the count argument by value (which means the function receives a copy of the data), so it is never modified in the main function. Instead, you should pass count as a pointer, and (thus) will need to dereference it inside the function:

void pushValue(int* heap, int* count, int value)
{
    ++(*count);
    heap[*count] = value;
    upHeap_min2(heap, *count);
}

Then, in main, you should call it using the address of count:

    pushValue(heapDemo, &count, 30); // And similarly for the other calls

Also, the loop in your view function stops one short of the end. Change the loop limit to i <= count. (This function uses count but doesn't modify it, so passing by value is OK.):

void view(int* heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i <= count; i++) {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

Feel free to ask for further clarification and/or explanation.


问:
How does AWS DynamoDB count read units for Query?
I am working on a table, in which every item is approx. 3KB in size.

Now as per the docs, the read units are calculated in 4s - i.e. For every item less than 4 kb, it would be counted as 4KB, and occupy 1 read unit.

Let's say i have a table of 100 items, of 3kb each in size (total table = 300kb). I do a query, in which 50 items satisfy under the query condition, and they are returned to me.

Now, will the read units be counted like : 50 items of 3kb size (rounded to 4kb) = 200kb = 200/4 = 50 read units ?

Any help is appreciated! :) Thanks!

答:
Yes, if you read 50 items of 3K each with strongly consistent reads, the cost will be 50 units. If you do eventual consistent reads, the answer will be half - 25 units.

However, there is another important cost issue you should be aware of, if you are not already. You mentioned you actually have 100 items, but only retrieving half of them by using a "query condition". DynamoDB actually has two types of "conditions" on queries. One of them are called key conditions (KeyConditions or KeyConditionExpression) and the other is post-query filters (QueryFilter or FilterExpression). If you use key conditions, you will only pay for the retrieved items - as you hoped. But if you use filtering, you will pay for all items, not just for the retrieved items. So in your example you would be paying 100 units instead of 50.


问:
Python's time.clock() vs. time.time() accuracy?
Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?

for example:

```<code>start = time.clock()
... do something
elapsed = (time.clock() - start)
</code>```

vs.

```<code>start = time.time()
... do something
elapsed = (time.time() - start)
</code>```

答:
time.clock() was removed in Python 3.8 because it had platform-dependent behavior:

On Unix, return the current processor time as a floating point number expressed in seconds.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number

```<code>print(time.clock()); time.sleep(10); print(time.clock())
# Linux  :  0.0382  0.0384   # see Processor Time
# Windows: 26.1224 36.1566   # see Wall-Clock Time
</code>```

So which function to pick instead?

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()

OwnerDisplayName: cgoldberg

Body:
Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?

for example:

start = time.clock()
... do something
elapsed = (time.clock() - start)

vs.

start = time.time()
... do something
elapsed = (time.time() - start)

Body:
time.clock() was removed in Python 3.8 because it had platform-dependent behavior:

On Unix, return the current processor time as a floating point number expressed in seconds.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number

print(time.clock()); time.sleep(10); print(time.clock())
# Linux  :  0.0382  0.0384   # see Processor Time
# Windows: 26.1224 36.1566   # see Wall-Clock Time

So which function to pick instead?

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()


问:
Entity Framework Core: sanity-check if database and model are in sync
We're currently in a setup in which multiple systems use one huge database. In our newest system we're using Entity Framework Core with a code-first approach.
Unfortunately, some changes of the database, made by the other systems, are not updated in the code-first system. As we don't have a complete integration-test coverage, these changes sometimes go unnotified until someone uses the changed entity by chance.

We can't just change the setup in a swift manner; therefore, we would like to have some automated sanity checks if the database and the models are synchronized. Searching for such a solution, I found this fine piece of code: Does an equivalent to Database.CompatibleWithModel(bool) exist in EF Core

But it is explicitly stated that this code should not be used (and it doesn't work anymore anyway). I found some more ideas from Brice here: Validate that EF Core ModelSnapshot, migrations, and actual database schema are consistent with each other. But these approaches are mostly manual ones respectively not easy to use from the code directly.

Is there already a solution around, which allows to check the synchronization between the mapping and the actual database from C# directly? Checking the Entity Framework Core interface, I think we would have all needed information available, but programming this checks in a generic manner seems like a huge task?

答:
Unfortunately, EF will only detect and throw exceptions if a part of the schema is missing from the database that is referenced in EF.  As far as fields or tables added from another system, that would be ignored.

You can consider generating a schema change report that can be emailed to your team everytime there is a change:

Send Email Alert on Database Schema Change in SQL


问:
PrivateChannel 403 error Laravel Echo Pusher Laravel Websockets local setup
I am getting a 403 on broadcasting/auth route.

I am using Laravel websockets package for web sockets and I have the below setup

```<code>- Backend Laravel server ( on port 8000 )
- Laravel Websockets Server ( laravel is running on 8001 and websocket server on 6001 )
- Standalone Ionic React app ( on port 8100)
</code>```

Now everything works when I am trying Public Channel but when I try Private Channel it fails.

in the above screenshot of Laravel sockets dashboard I can see connection made as this is the same socketId which went with the request.

I am using Laravel Sanctum for Authentication.

PFB :- my client side code

```<code>const headers = {
    'Content-Type': 'application/json',
    Authorization: window.localStorage.getItem('token')
      ? `Bearer ${window.localStorage.getItem('token')}`
      : '',
    'Access-Control-Allow-Credentials': true,
  };
  const options = {
    broadcaster: 'pusher',
    key: 'abcsock',
    authEndpoint: 'http://localhost:8001/api/broadcasting/auth',
    authorizer: (channel, options) => {
      return {
        authorize: (socketId, callback) => {
          axios
            .post(
              'http://localhost:8001/api/broadcasting/auth',
              {
                socket_id: socketId,
                channel_name: channel.name,
              },
              { headers, withCredentials: true }
            )
            .then((response) => {
              callback(false, response.data);
            })
            .catch((error) => {
              callback(true, error);
            });
        },
      };
    },
    wsHost: '127.0.0.1',
    wsPort: 6001,
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    forceTLS: false,
  };
</code>```

Code from Laravel Websockets Server

api.php file

```<code>use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Broadcast;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Broadcast::routes(['middleware' => ['auth:sanctum']]);
</code>```

BroadcastServiceProvider.php

```<code>namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(['middleware' => ['auth:sanctum']]);

        require base_path('routes/channels.php');
    }
}
</code>```

NewNotification.php

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Broadcasting\PrivateChannel;

use App\AppNotification;
use App\User;

class NewNotification extends Notification
{
    use Queueable;

    public $notification;
    public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(AppNotification $notification, User $user)
    {
        $this->notification = $notification;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        $notification = $this->notification;
        return [
            'id' => $notification->id,
            'title' => $notification->title,
            'description' => $notification->description,
            'button_text' => $notification->button_text,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at,
            [
                'notification_for' => $notification->notifiable
            ]
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage($this->toArray($notifiable));
    }

    public function broadcastOn()
    {
        return new PrivateChannel('Notifications.' . $this->user->id);
    }
}
</code>```

channels.php

```<code><?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Notifications.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['sanctum']]);
</code>```

I have attached whatever I felt was sufficient to explain the issue and for you to troubleshoot but if you need anything more please ask.

Any help will be appreciated

答:
i liked this package because its wrote in php but its sortof abandon and a lot of issues that not solved.

alternative of this server is laravel-echo-server(as laravel docs recommends) very easier to use.
https://stackoverflow.com/a/61704796/7908390 more info if you can work with laravel-sockets im glad to see a new example

Body:
I am getting a 403 on broadcasting/auth route.

I am using Laravel websockets package for web sockets and I have the below setup

- Backend Laravel server ( on port 8000 )
- Laravel Websockets Server ( laravel is running on 8001 and websocket server on 6001 )
- Standalone Ionic React app ( on port 8100)

Now everything works when I am trying Public Channel but when I try Private Channel it fails.

in the above screenshot of Laravel sockets dashboard I can see connection made as this is the same socketId which went with the request.

I am using Laravel Sanctum for Authentication.

PFB :- my client side code

const headers = {
    'Content-Type': 'application/json',
    Authorization: window.localStorage.getItem('token')
      ? `Bearer ${window.localStorage.getItem('token')}`
      : '',
    'Access-Control-Allow-Credentials': true,
  };
  const options = {
    broadcaster: 'pusher',
    key: 'abcsock',
    authEndpoint: 'http://localhost:8001/api/broadcasting/auth',
    authorizer: (channel, options) => {
      return {
        authorize: (socketId, callback) => {
          axios
            .post(
              'http://localhost:8001/api/broadcasting/auth',
              {
                socket_id: socketId,
                channel_name: channel.name,
              },
              { headers, withCredentials: true }
            )
            .then((response) => {
              callback(false, response.data);
            })
            .catch((error) => {
              callback(true, error);
            });
        },
      };
    },
    wsHost: '127.0.0.1',
    wsPort: 6001,
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    forceTLS: false,
  };

Code from Laravel Websockets Server

api.php file

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Broadcast;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Broadcast::routes(['middleware' => ['auth:sanctum']]);

BroadcastServiceProvider.php

namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(['middleware' => ['auth:sanctum']]);

        require base_path('routes/channels.php');
    }
}

NewNotification.php

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Broadcasting\PrivateChannel;

use App\AppNotification;
use App\User;

class NewNotification extends Notification
{
    use Queueable;

    public $notification;
    public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(AppNotification $notification, User $user)
    {
        $this->notification = $notification;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        $notification = $this->notification;
        return [
            'id' => $notification->id,
            'title' => $notification->title,
            'description' => $notification->description,
            'button_text' => $notification->button_text,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at,
            [
                'notification_for' => $notification->notifiable
            ]
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage($this->toArray($notifiable));
    }

    public function broadcastOn()
    {
        return new PrivateChannel('Notifications.' . $this->user->id);
    }
}

channels.php

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Notifications.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['sanctum']]);

I have attached whatever I felt was sufficient to explain the issue and for you to troubleshoot but if you need anything more please ask.

Any help will be appreciated