问:
How to exclude 0 from count()? in sql?
I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0

For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.

If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.

My query is as follows:

```<code>with first_purchases as
    (select *,
    case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
    from sales)

select
    count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
    and date_id between '2021-02-01' and '2021-03-01'
    order by 1 desc;
</code>```

It returned the below which is not an intended output

Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.

答:
I think that you are using COUNT() when you want SUM().

```<code>    with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
from sales)

    select
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
</code>```

You could simplify your query as:

```<code>SELECT COUNT(*) AS
FROM  sales no_of_first_purchases
WHERE is_first_purchase = 1
AND buyer_id = 456391
AND date_id  BETWEEN '2021-02-01' AND '2021-03-01'
ORDER BY 1 DESC;
</code>```

It is better to avoid the use of functions like IF and CASE when it can be done with WHERE.

Title: How to exclude 0 from count()? in sql?

Body:
I have a code as below where I want to count number of first purchases for a given period of time. I have a column in my sales table where if the buyer is not a first time buyer, then is_first_purchase = 0

For example:
buyer_id = 456391 is already an existing buyer who made purchases on 2 different dates.
Hence is_first_purchase column will show as 0 as per below.

If i do a count() on is_first_purchase for this buyer_id = 456391 then it should return 0 instead of 2.

My query is as follows:

with first_purchases as
    (select *,
    case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
    from sales)

select
    count(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
    and date_id between '2021-02-01' and '2021-03-01'
    order by 1 desc;

It returned the below which is not an intended output

Appreciate if someone can help explain how to exclude is_first_purchase = 0 from the count, thanks.

Body:
I think that you are using COUNT() when you want SUM().

    with first_purchases as
(select *,
case when is_first_purchase = 1 then 'Yes'  else 'No' end as first_purchase
from sales)

    select
SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases
from first_purchases
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;

You could simplify your query as:

SELECT COUNT(*) AS
FROM  sales no_of_first_purchases
WHERE is_first_purchase = 1
AND buyer_id = 456391
AND date_id  BETWEEN '2021-02-01' AND '2021-03-01'
ORDER BY 1 DESC;

It is better to avoid the use of functions like IF and CASE when it can be done with WHERE.


来源: stackexchange

答:
Because COUNT function count when the value isn't NULL (include 0), if you don't want to count, need to let CASE WHEN return NULL

There are two ways you can count as your expectation, one is SUM other is COUNT but remove the part of else 0

```<code>SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases

COUNT(case when first_purchase = 'Yes' then 1 end) as no_of_first_purchases
</code>```

From your question, I would combine CTE and main query as below

```<code>select
    COUNT(case when is_first_purchase = 1 then 1 end) as no_of_first_purchases
from sales
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to exclude 0 from count()? in sql?

Body:
Because COUNT function count when the value isn't NULL (include 0), if you don't want to count, need to let CASE WHEN return NULL

There are two ways you can count as your expectation, one is SUM other is COUNT but remove the part of else 0

SUM(case when first_purchase = 'Yes' then 1 else 0 end) as no_of_first_purchases

COUNT(case when first_purchase = 'Yes' then 1 end) as no_of_first_purchases

From your question, I would combine CTE and main query as below

select
    COUNT(case when is_first_purchase = 1 then 1 end) as no_of_first_purchases
from sales
where buyer_id = 456391
and date_id between '2021-02-01' and '2021-03-01'
order by 1 desc;


问:
Import multi file dat in vba array
I want to import multiple dat files into one with sheet with sheet name "selectfile" and into table with name "TableDat".
The actual record is 100000. I tried the code below for fast but I haven't been able to get all the data files into one sheet as I want the output to look like in the excel screenshot below. If there are other recommendations that are very fast then I accept. I attached a screenshot of the dat file as well.

thanks
roy

```<code>Sub importmultidat()

Dim myFileNames As Variant
Dim iCtr As Long
myFileNames = Application.GetOpenFilename _
(filefilter:="DAT Files, *.DAT", MultiSelect:=True)

If IsArray(myFileNames) Then
For iCtr = LBound(myFileNames) To UBound(myFileNames)
Workbooks.OpenText Filename:=myFileNames(iCtr), _
Origin:=437, StartRow:=1, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, _
Tab:=True, Semicolon:=False, Comma:=False, Space:=True, _
Other:=False, FieldInfo:=Array(1, 1)
Next iCtr
End If

End Sub

</code>```

答:
```<code>
Sub importmultidat()
    Dim V, W, F%, R&, X, S, L&, Y
        V = ThisWorkbook.Path & "\test dat file update\":  If Dir(V & "*.dat") > "" Then ChDrive V: ChDir V
        W = Application.GetOpenFilename("Text files,*.dat", , "Select files(s)", , True):  If Not IsArray(W) Then Exit Sub
        F = FreeFile
        R = 2
    With Sheets("selectfile")
       .UsedRange.Clear
        Application.ScreenUpdating = False
        ReDim V(.Rows.Count - 2, 1 To 4)
    For Each X In W
        Open X For Input As #F
        S = Split(Input(LOF(F), #F), vbCrLf)
        Close #F
    For L = 0 To UBound(S) + (S(UBound(S)) = "")
        Y = Split(S(L), vbTab)
    If IsDate(Y(1)) Then
        V(L, 4) = Split(Y(1), "-", 2)(0)
    Else
        Y(1) = Replace(Replace(Y(1), "--", "/"), "-", "")
        V(L, 4) = Split(Y(1), "/", 2)(0)
    End If
        V(L, 1) = Y(0)
        V(L, 2) = Y(1)
        V(L, 3) = Split(Y(1))(0)
    Next
       .Cells(R, 1).Resize(L, UBound(V, 2)).Value = V
        R = R + L
    Next
       .[A1:G1] = [{"ID","DATE & TIME","DATE","YEAR","PERIOD","CATEGORY","NAME"}]
       .ListObjects.Add 1, .[A1].CurrentRegion, , 1
    End With
        Application.ScreenUpdating = True
End Sub

</code>```

Title: Import multi file dat in vba array

Body:
I want to import multiple dat files into one with sheet with sheet name "selectfile" and into table with name "TableDat".
The actual record is 100000. I tried the code below for fast but I haven't been able to get all the data files into one sheet as I want the output to look like in the excel screenshot below. If there are other recommendations that are very fast then I accept. I attached a screenshot of the dat file as well.

thanks
roy

Sub importmultidat()

Dim myFileNames As Variant
Dim iCtr As Long
myFileNames = Application.GetOpenFilename _
(filefilter:="DAT Files, *.DAT", MultiSelect:=True)

If IsArray(myFileNames) Then
For iCtr = LBound(myFileNames) To UBound(myFileNames)
Workbooks.OpenText Filename:=myFileNames(iCtr), _
Origin:=437, StartRow:=1, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, _
Tab:=True, Semicolon:=False, Comma:=False, Space:=True, _
Other:=False, FieldInfo:=Array(1, 1)
Next iCtr
End If

End Sub


问:
Android: WifiInfo.getIpAddress() deprecated
API 31 deprecated getIpAddress() Need help getting the address from the callback implementation</p>
```<code>val networkCallback = object : ConnectivityManager.NetworkCallback() {

    override fun onAvailable(network: Network) {}

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        val wifiInfo = networkCapabilities.transportInfo as? WifiInfo
    }

    override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
        super.onLinkPropertiesChanged(network, linkProperties)
        // val ipV4Address = ?

    }
};

</code>```

答:
for deprecated method you can read afficial android Documents,
as documnet syas :

This method was deprecated in API level 31. Use the methods on LinkProperties which can be obtained either via NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties) or ConnectivityManager#getLinkProperties(Network).

so by this method that i have added here you can obtain all of ip address:

```<code>   private fun getIpAddress() {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
     if (connectivityManager is ConnectivityManager) {
        var link:LinkProperties =  connectivityManager.getLinkProperties(connectivityManager.activeNetwork) as LinkProperties
         Log.e("NETWOOOOOOOOOOOORK", link.linkAddresses.toString())
    }

}
</code>```

Notice: link.linkAddresses method may return array of addresses

Body:
API 31 deprecated getIpAddress() Need help getting the address from the callback implementation

val networkCallback = object : ConnectivityManager.NetworkCallback() {

    override fun onAvailable(network: Network) {}

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        val wifiInfo = networkCapabilities.transportInfo as? WifiInfo
    }

    override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
        super.onLinkPropertiesChanged(network, linkProperties)
        // val ipV4Address = ?

    }
};

Body:
for deprecated method you can read afficial android Documents,
as documnet syas :

This method was deprecated in API level 31. Use the methods on LinkProperties which can be obtained either via NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties) or ConnectivityManager#getLinkProperties(Network).

so by this method that i have added here you can obtain all of ip address:

   private fun getIpAddress() {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
     if (connectivityManager is ConnectivityManager) {
        var link:LinkProperties =  connectivityManager.getLinkProperties(connectivityManager.activeNetwork) as LinkProperties
         Log.e("NETWOOOOOOOOOOOORK", link.linkAddresses.toString())
    }

}

Notice: link.linkAddresses method may return array of addresses


问:
Wordlist transfer for an anagram program
I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as the key of a map, and made the corresponding entry the original, unalphabetized word.

The program is messing up when it comes to the entries in the map. When the entry is six characters or less, the program tags a random character on the end of the string. I've narrowed down what can be causing the problem to a single loop:

```<code>while(myFile){
  myFile.getline(str, 30);
  int h=0;
  for (; str[h] != 0; h++)//setting the initial version of str
  {
      strInit[h]=str[h]; //strInit is what becomes the entry into the map.
  }
  strInit[h+1]='\0';    //I didn't know if the for loop would include the null char
  cout<<strInit; //Personal error-checking; not necessary for the program
 }
</code>```

And if it's necessary, here's the entire program:

Program

答:
Prevent issues, use normal functions:

```<code>getline(str, 30);
strncpy(strInit, str, 30);
</code>```

Prevent more issues, use standard strings:

```<code>std::string strInit, str;
while (std::getline(myFile, str)) {
    strInit = str;
    // do stuff
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm almost finished with my program, but there's one last bug that I'm having problems ferreting out. The program is supposed to check about 10 scrambled words against a wordlist to see what the scrambled words are anagrams of. To do this, I alphabetized each word in the wordlist (apple would become aelpp), set that as the key of a map, and made the corresponding entry the original, unalphabetized word.

The program is messing up when it comes to the entries in the map. When the entry is six characters or less, the program tags a random character on the end of the string. I've narrowed down what can be causing the problem to a single loop:

while(myFile){
  myFile.getline(str, 30);
  int h=0;
  for (; str[h] != 0; h++)//setting the initial version of str
  {
      strInit[h]=str[h]; //strInit is what becomes the entry into the map.
  }
  strInit[h+1]='\0';    //I didn't know if the for loop would include the null char
  cout<<strInit; //Personal error-checking; not necessary for the program
 }

And if it's necessary, here's the entire program:

Program

Body:
Prevent issues, use normal functions:

getline(str, 30);
strncpy(strInit, str, 30);

Prevent more issues, use standard strings:

std::string strInit, str;
while (std::getline(myFile, str)) {
    strInit = str;
    // do stuff
}


问:
Creating ForeignKey reference with 2 different models as choice
Here is what i want to try, I have a User model inherited from Abstract user with custom manager, i need a feeld in CustomUser model to choose either Seller model or Customer model</p>
```<code>class CustomUser(AbstractUser):
    is_seller = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=False)

    user_type = ? "I want to have a choice feild to choose either Seller or
    Customer model"

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = CustomUserManager()

class CustomUserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            return ValueError('Email required')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff true')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser true')

        return self.create_user(email, password, **extra_fields)

class SellerDetails(models.Model):
    pass

class CustomerDetails(models.Model):
    pass
</code>```

答:
GenericForeignKey is the solution. Django has a nice feature called a generic foreign key. In this particular type of field, you can save any type of object, only you have to mention which type of object is it referring to. Here I have put an example for you below:

```<code>class ModelA(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )

class ModelB(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )

class ModelC(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )
    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
</code>```

Now, when creating an object for ModelC, you can either select ModelA or ModelB, then the id of the object.

If you have your own template of the CRUD page or you are using an API to make the crud operation, then it will be very easy to populate the data. If you are using a Form then you might need to make a custom field, so that you can select a context type and based on the type you see can see a dropdown list.

Body:
Here is what i want to try, I have a User model inherited from Abstract user with custom manager, i need a feeld in CustomUser model to choose either Seller model or Customer model

class CustomUser(AbstractUser):
    is_seller = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=False)

    user_type = ? "I want to have a choice feild to choose either Seller or
    Customer model"

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = CustomUserManager()

class CustomUserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            return ValueError('Email required')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff true')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser true')

        return self.create_user(email, password, **extra_fields)

class SellerDetails(models.Model):
    pass

class CustomerDetails(models.Model):
    pass

Body:
GenericForeignKey is the solution. Django has a nice feature called a generic foreign key. In this particular type of field, you can save any type of object, only you have to mention which type of object is it referring to. Here I have put an example for you below:

class ModelA(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )

class ModelB(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )

class ModelC(models.Model):
    achar = models.CharField(
        max_length=255,
        blank=True,
        default="",
    )
    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

Now, when creating an object for ModelC, you can either select ModelA or ModelB, then the id of the object.

If you have your own template of the CRUD page or you are using an API to make the crud operation, then it will be very easy to populate the data. If you are using a Form then you might need to make a custom field, so that you can select a context type and based on the type you see can see a dropdown list.


问:
How can I parse repeated HTML elements by their class attribute?
I'm trying to parse an HTML file with basically the same tags.

I want to get this output:

BTC - Bitcoin, BEP20(BSC), Bitcoin(Segwit)

ETH - ERC20, BEP20(BSC), POLYGON, ARBITRUM, AURORA, MATISEVM

USDT - OMNI,TRC20,ERC20,BEP20(BSC),HECO,POLYGON,FTM, AVAX-C ,ARBITRUM,METISEVM

QASH - ERC20

Here is a sample of the HTML:

         BTC

Bitcoin

BitcoinBEP20(BSC)Bitcoin(SegWit)

         0.001
         0.002

         ETH

ERC20

ERC20BEP20(BSC)POLYGONARBITRUMAURORAMETISEVM

         0.012
         0.024

         USDT

OMNI

OMNITRC20ERC20BEP20(BSC)HECOPOLYGONFTMAVAX-CARBITRUMMETISEVM

         30
         50

         QASH

               ERC20

         513
         1026

```
<p>I'm using the <code>HtmlAgilityPack</code> library without success:</p>
<pre class="lang-vbnet prettyprint-override"><code>Dim arqHtml As String = "C:\Users\Mattia\Desktop\ready.html"
Dim myHtml As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument()
myHtml.Load(arqHtml)
Dim myTable As HtmlAgilityPack.HtmlNode = myHtml.DocumentNode.SelectSingleNode("//table")
Dim myRows As HtmlAgilityPack.HtmlNodeCollection = myTable.SelectNodes("tr")
For Each tmpRow As HtmlAgilityPack.HtmlNode In myRows
    Dim myCells As HtmlAgilityPack.HtmlNodeCollection = tmpRow.SelectNodes("td")
    If myCells IsNot Nothing Then
        Dim myToken As String = myCells(0).InnerText
        Dim mySpans As HtmlAgilityPack.HtmlNodeCollection = myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")
        If mySpans IsNot Nothing Then
            Dim myListBChain As New List(Of String)
            For Each mySpan As HtmlAgilityPack.HtmlNode In mySpans
                RichTextBox1.Text += mySpan.InnerText
            Next
            Dim allItensAsString = String.Join(", ", richtextbox1.text)
        End If
    End If
Next
</code>```

This returns this output:

BitcoinBEP20(BSC)Bitcoin(SegWit)ERC20BEP20(BSC)POLYGONARBITRUMAURORAMETISEVMOMNITRC20ERC20BEP20(BSC)HECOPOLYGONFTMAVAX-CARBITRUMMETISEVMEOSBEP20(BSC)ERC20BEP20(BSC)TRC20BEP20(BSC)ZILBEP20(BSC)NEOLEGACYNEON3ERC20POLYGONERC20DAGBEP2BEP20(BSC)FTMAVAX-CERC20BEP20(BSC)ERC20BEP20(BSC)ERC20HECOBEP20(BSC)ERC20HECOERC20POLYGONERC20HECOERC20POLYGONERC20BEP20(BSC)BCHBEP20(BSC)ERC20LOOPPOLYGONBEP20(BSC)FTMAVAX-CMETISEVMERC20TOLERC20METAERC20BEP20(BSC)

How do I make it return the output I want?

答:
Incorporating my comment on the original issue, in the last
 in the sample...

    QASH

        ERC20

    513
    1026

```
<p>...the second <code><td></code> does not contain a <code><div class="select-list" ... ></code>, so...</p>
<pre class="lang-vbnet prettyprint-override"><code>myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")
</code>```

...returns Nothing, hence the NullReferenceException.

As far as building the output you want, first you need to test if such a
 element exists...

If mySpans Is Nothing Then
```
<p>If it doesn't, then save the contents of the <code><div class="chain_box" ... ><span class="chain_name ... ></code> element...</p>
<pre class="lang-vbnet prettyprint-override"><code>Dim chainTextNode As HtmlAgilityPack.HtmlNode = myCells(1).SelectSingleNode(
    "div[contains(@class, 'chain_box')]/span[contains(@class, 'chain_name')]"
)

chainText = If(chainTextNode Is Nothing OrElse String.IsNullOrWhiteSpace(chainTextNode.InnerText), "(unknown)", chainTextNode.InnerText)
</code>```

I added a little extra handling just in case that element doesn't exist or have a value.

If there is a
 element, then save the values of its child  elements separated by commas...

chainText = String.Join(", ", mySpans.Select(Function(span) span.InnerText))
' Alternative: chainText = String.Join(", ", From span In mySpans Select span.InnerText)
```
<p>Finally, build and append a new line to your text box...</p>
<pre class="lang-vbnet prettyprint-override"><code>RichTextBox1.Text &= $"{myToken} - {chainText}{Environment.NewLine}"
</code>```

The complete code looks like this...

Dim arqHtml As String = "C:\Users\Mattia\Desktop\ready.html"
Dim myHtml As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument()
myHtml.Load(arqHtml)
Dim myTable As HtmlAgilityPack.HtmlNode = myHtml.DocumentNode.SelectSingleNode("//table")

Dim myRows As HtmlAgilityPack.HtmlNodeCollection = myTable.SelectNodes("tr")
For Each tmpRow As HtmlAgilityPack.HtmlNode In myRows
    Dim myCells As HtmlAgilityPack.HtmlNodeCollection = tmpRow.SelectNodes("td")
    If myCells IsNot Nothing Then
        Dim myToken As String = myCells(0).InnerText
        Dim mySpans As HtmlAgilityPack.HtmlNodeCollection = myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")
        Dim chainText As String

        If mySpans Is Nothing Then
            Dim chainTextNode As HtmlAgilityPack.HtmlNode = myCells(1).SelectSingleNode(
                "div[contains(@class, 'chain_box')]/span[contains(@class, 'chain_name')]"
            )

            chainText = If(chainTextNode Is Nothing OrElse String.IsNullOrWhiteSpace(chainTextNode.InnerText), "(unknown)", chainTextNode.InnerText)
        Else
            chainText = String.Join(", ", mySpans.Select(Function(span) span.InnerText))
            ' Alternative: chainText = String.Join(", ", From span In mySpans Select span.InnerText)
        End If

        RichTextBox1.Text &= $"{myToken} - {chainText}{Environment.NewLine}"
    End If
Next
```
<p>If you have a very large input HTML file you might consider...</p>
<ul>
<li>Appending each iteration's line to a <code>StringBuilder</code>...
<pre class="lang-vbnet prettyprint-override"><code>outputBuilder.Append($"{myToken} - {chainText}{Environment.NewLine}")
</code>```
...and then setting RichTextBox1.Text once after the loop...

RichTextBox1.Text = outputBuilder.ToString()
```

(Assuming WinForms) Calling RichTextBox1.SuspendLayout() before the loop and RichTextBox1.ResumeLayout() after the loop

...to improve performance, however, using either or both approaches means RichTextBox1 won't display any output until the HTML is completely processed.

Body:
I'm trying to parse an HTML file with basically the same tags.

I want to get this output:

BTC - Bitcoin, BEP20(BSC), Bitcoin(Segwit)

ETH - ERC20, BEP20(BSC), POLYGON, ARBITRUM, AURORA, MATISEVM

USDT - OMNI,TRC20,ERC20,BEP20(BSC),HECO,POLYGON,FTM, AVAX-C ,ARBITRUM,METISEVM

QASH - ERC20

Here is a sample of the HTML:

         BTC

Bitcoin

BitcoinBEP20(BSC)Bitcoin(SegWit)

         0.001
         0.002

         ETH

ERC20

ERC20BEP20(BSC)POLYGONARBITRUMAURORAMETISEVM

         0.012
         0.024

         USDT

OMNI

OMNITRC20ERC20BEP20(BSC)HECOPOLYGONFTMAVAX-CARBITRUMMETISEVM

         30
         50

         QASH

               ERC20

         513
         1026

I'm using the HtmlAgilityPack library without success:

Dim arqHtml As String = "C:\Users\Mattia\Desktop\ready.html"
Dim myHtml As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument()
myHtml.Load(arqHtml)
Dim myTable As HtmlAgilityPack.HtmlNode = myHtml.DocumentNode.SelectSingleNode("//table")
Dim myRows As HtmlAgilityPack.HtmlNodeCollection = myTable.SelectNodes("tr")
For Each tmpRow As HtmlAgilityPack.HtmlNode In myRows
    Dim myCells As HtmlAgilityPack.HtmlNodeCollection = tmpRow.SelectNodes("td")
    If myCells IsNot Nothing Then
        Dim myToken As String = myCells(0).InnerText
        Dim mySpans As HtmlAgilityPack.HtmlNodeCollection = myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")
        If mySpans IsNot Nothing Then
            Dim myListBChain As New List(Of String)
            For Each mySpan As HtmlAgilityPack.HtmlNode In mySpans
                RichTextBox1.Text += mySpan.InnerText
            Next
            Dim allItensAsString = String.Join(", ", richtextbox1.text)
        End If
    End If
Next

This returns this output:

BitcoinBEP20(BSC)Bitcoin(SegWit)ERC20BEP20(BSC)POLYGONARBITRUMAURORAMETISEVMOMNITRC20ERC20BEP20(BSC)HECOPOLYGONFTMAVAX-CARBITRUMMETISEVMEOSBEP20(BSC)ERC20BEP20(BSC)TRC20BEP20(BSC)ZILBEP20(BSC)NEOLEGACYNEON3ERC20POLYGONERC20DAGBEP2BEP20(BSC)FTMAVAX-CERC20BEP20(BSC)ERC20BEP20(BSC)ERC20HECOBEP20(BSC)ERC20HECOERC20POLYGONERC20HECOERC20POLYGONERC20BEP20(BSC)BCHBEP20(BSC)ERC20LOOPPOLYGONBEP20(BSC)FTMAVAX-CMETISEVMERC20TOLERC20METAERC20BEP20(BSC)

How do I make it return the output I want?

Body:
Incorporating my comment on the original issue, in the last <tr> in the sample...

<tr data-v-326d86f4="">
    <td data-v-326d86f4="">QASH</td>
    <td data-v-326d86f4="" class="block-chain">
    <div data-v-326d86f4="" class="chain_box">
        <span data-v-326d86f4="" class="chain_name">ERC20</span> <!---->
    </div>
    <!---->
    </td>
    <td data-v-326d86f4="">513</td>
    <td data-v-326d86f4="">1026</td>
</tr>

...the second <td> does not contain a <div class="select-list" ... >, so...

myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")

...returns Nothing, hence the NullReferenceException.

As far as building the output you want, first you need to test if such a <div class="select-list" ... > element exists...

If mySpans Is Nothing Then

If it doesn't, then save the contents of the <div class="chain_box" ... ><span class="chain_name ... > element...

Dim chainTextNode As HtmlAgilityPack.HtmlNode = myCells(1).SelectSingleNode(
    "div[contains(@class, 'chain_box')]/span[contains(@class, 'chain_name')]"
)

chainText = If(chainTextNode Is Nothing OrElse String.IsNullOrWhiteSpace(chainTextNode.InnerText), "(unknown)", chainTextNode.InnerText)

I added a little extra handling just in case that element doesn't exist or have a value.

If there is a <div class="select-list" ... > element, then save the values of its child <span ... > elements separated by commas...

chainText = String.Join(", ", mySpans.Select(Function(span) span.InnerText))
' Alternative: chainText = String.Join(", ", From span In mySpans Select span.InnerText)

Finally, build and append a new line to your text box...

RichTextBox1.Text &= $"{myToken} - {chainText}{Environment.NewLine}"

The complete code looks like this...

Dim arqHtml As String = "C:\Users\Mattia\Desktop\ready.html"
Dim myHtml As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument()
myHtml.Load(arqHtml)
Dim myTable As HtmlAgilityPack.HtmlNode = myHtml.DocumentNode.SelectSingleNode("//table")

Dim myRows As HtmlAgilityPack.HtmlNodeCollection = myTable.SelectNodes("tr")
For Each tmpRow As HtmlAgilityPack.HtmlNode In myRows
    Dim myCells As HtmlAgilityPack.HtmlNodeCollection = tmpRow.SelectNodes("td")
    If myCells IsNot Nothing Then
        Dim myToken As String = myCells(0).InnerText
        Dim mySpans As HtmlAgilityPack.HtmlNodeCollection = myCells(1).SelectNodes("div[contains(@class,'select-list')]/span")
        Dim chainText As String

        If mySpans Is Nothing Then
            Dim chainTextNode As HtmlAgilityPack.HtmlNode = myCells(1).SelectSingleNode(
                "div[contains(@class, 'chain_box')]/span[contains(@class, 'chain_name')]"
            )

            chainText = If(chainTextNode Is Nothing OrElse String.IsNullOrWhiteSpace(chainTextNode.InnerText), "(unknown)", chainTextNode.InnerText)
        Else
            chainText = String.Join(", ", mySpans.Select(Function(span) span.InnerText))
            ' Alternative: chainText = String.Join(", ", From span In mySpans Select span.InnerText)
        End If

        RichTextBox1.Text &= $"{myToken} - {chainText}{Environment.NewLine}"
    End If
Next

If you have a very large input HTML file you might consider...

Appending each iteration's line to a StringBuilder...

outputBuilder.Append($"{myToken} - {chainText}{Environment.NewLine}")

...and then setting RichTextBox1.Text once after the loop...

RichTextBox1.Text = outputBuilder.ToString()

(Assuming WinForms) Calling RichTextBox1.SuspendLayout() before the loop and RichTextBox1.ResumeLayout() after the loop

...to improve performance, however, using either or both approaches means RichTextBox1 won't display any output until the HTML is completely processed.


问:
How to get My PUBLIC IP address Using Node js
I want to get my Public IP address using Node js only

For example when i search on Google "What is my Ip address "

Gives me output like 10X.XX.XX.XXX

How to get this Ip address Using node js without importing any Libraries like ip , Public-ip etc ...

I want to write my Custom Code to get public ip Without sending requests to other websites like whatismyipaddress.com , ipconfig.com etc ...

答:
There is no native way to get the public IP, in fact, there is no way to get it from your server, not even from the Linux command, you have to ask an external server, and this package does exactly so with different servers.

I understand you don't want to ask an external library or an external server, but you have no choice.

Im suggesting using an external library, because it takes care of asking multiple servers instead of just one in the case that one goes offline

You can try this package it works perfectly


问:
tkinter how to change attribute value of object using OOP?
How can I change an attribute on the object when the attribute is Frame? I want to change the color of the frame.</p>
```<code>class MyFrame:
   def __init__(self, bg_color)
   self.window = tk.Frame(self.parent, bg=bg_color)

mainApp:
    frame_obj = MyFrame("blue")

    #want to change the color after the frame obj has been created
    frame_obj.window.bg = "red" #this does not work
</code>```

答:
Tkinter is based on different progamming language, named tcl and thats why things seem a bit unpythonic here.

The tk.Frame object isnt a pure python object, rather its an wrapped object in a tcl interpreter and thats why you cant address the attributes you intuitivly think you can. You need to adress the attributes in a way the tcl interpreter is abel to handle and therefor methods are created like widget.configure.

To achive what you want with your current code, it would look like:

```<code>import tkinter as tk

root = tk.Tk()

class MyFrame():
    def __init__(self, bg_color):
        self.window = tk.Frame(width=500,height=500,bg=bg_color)

frame_obj = MyFrame('blue')
frame_obj.window.pack(fill=tk.BOTH)
frame_obj.window.configure(bg='yellow')

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

In addition, the proper way for an OOP approach for a frame would look like this:

```<code>class MyFrame(tk.Frame):
    def __init__(self,master,**kwargs):
        super().__init__(master)
        self.configure(**kwargs)

frame_obj = MyFrame(root,width=500,height=500,bg='green')
frame_obj.pack(fill=tk.BOTH)
</code>```

This way your class becomes a child of the tk.Frame object and you can adress it directly. The syntax self in this context refers directly to the tk.Frame object. Also it is good practice to use the format of

def __init__(self,master,**kwargs):

while its the same for the parent/tk.Frame. It has a single positional argument, named master and keywords arguments for the configuration of the Frame.

Please take a look at a tutorial for tkinter and for OOP. If you had you would know that. Please dont feel offended, but StackOverflow requiers a brief reasearch and that includes to read documentation and take tutorials.

Body:
How can I change an attribute on the object when the attribute is Frame? I want to change the color of the frame.

class MyFrame:
   def __init__(self, bg_color)
   self.window = tk.Frame(self.parent, bg=bg_color)

mainApp:
    frame_obj = MyFrame("blue")

    #want to change the color after the frame obj has been created
    frame_obj.window.bg = "red" #this does not work

Body:
Tkinter is based on different progamming language, named tcl and thats why things seem a bit unpythonic here.

The tk.Frame object isnt a pure python object, rather its an wrapped object in a tcl interpreter and thats why you cant address the attributes you intuitivly think you can. You need to adress the attributes in a way the tcl interpreter is abel to handle and therefor methods are created like widget.configure.

To achive what you want with your current code, it would look like:

import tkinter as tk

root = tk.Tk()

class MyFrame():
    def __init__(self, bg_color):
        self.window = tk.Frame(width=500,height=500,bg=bg_color)

frame_obj = MyFrame('blue')
frame_obj.window.pack(fill=tk.BOTH)
frame_obj.window.configure(bg='yellow')

root.mainloop()

In addition, the proper way for an OOP approach for a frame would look like this:

class MyFrame(tk.Frame):
    def __init__(self,master,**kwargs):
        super().__init__(master)
        self.configure(**kwargs)

frame_obj = MyFrame(root,width=500,height=500,bg='green')
frame_obj.pack(fill=tk.BOTH)

This way your class becomes a child of the tk.Frame object and you can adress it directly. The syntax self in this context refers directly to the tk.Frame object. Also it is good practice to use the format of

def __init__(self,master,**kwargs):

while its the same for the parent/tk.Frame. It has a single positional argument, named master and keywords arguments for the configuration of the Frame.

Please take a look at a tutorial for tkinter and for OOP. If you had you would know that. Please dont feel offended, but StackOverflow requiers a brief reasearch and that includes to read documentation and take tutorials.


问:
Read dotenv from bash script
I have a bash file setting up a postgres-database.

```<code>#configure_db.sh
source ./secrets/sqlpassword.sh
createdb -U myuser mydatabase
</code>```

I have a simple bash file exporting the password

```<code>#secrets/sqlpassword.sh
export PGPASSWORD='mypassword'
</code>```

The rest of the node server uses environment variables saved in a .env-file. For the sake of order and simplicity i would want my postgres password stored in the same file:

```<code>//.env
postgrespassword='mypassword'
</code>```

How can you import a variable from a .env-file to as bash-file?

Is there another way of solving the above?

答:
Why don't you follow the same pattern?

Change

```<code>#configure_db.sh
source ./secrets/sqlpassword.sh
createdb -U myuser mydatabase
</code>```

to

```<code>#configure_db.sh
PGPASSWORD=$(grep postgrespassword /path/to/.env | cut -d "=" -f2)
createdb -U myuser mydatabase
</code>```

Title: Read dotenv from bash script

Body:
I have a bash file setting up a postgres-database.

#configure_db.sh
source ./secrets/sqlpassword.sh
createdb -U myuser mydatabase

I have a simple bash file exporting the password

#secrets/sqlpassword.sh
export PGPASSWORD='mypassword'

The rest of the node server uses environment variables saved in a .env-file. For the sake of order and simplicity i would want my postgres password stored in the same file:

//.env
postgrespassword='mypassword'

How can you import a variable from a .env-file to as bash-file?

Is there another way of solving the above?

Body:
Why don't you follow the same pattern?

Change

#configure_db.sh
source ./secrets/sqlpassword.sh
createdb -U myuser mydatabase

to

#configure_db.sh
PGPASSWORD=$(grep postgrespassword /path/to/.env | cut -d "=" -f2)
createdb -U myuser mydatabase


问:
How to propage errors from nested Eithers in Arrow-kt?
I have some code that looks like this:

```<code>data class MyStrings(val a: String, val b: String)

sealed class Error {
    object SpecificError0 : Error()
    object SpecificError1 : Error()
    object SpecificError2 : Error()
}

fun either2(): Either<Error, String> =
Either.catch { throw RuntimeException("Either 2") }.mapLeft { Error.SpecificError2 }

fun either4(): Either<Error, MyStrings> =
Either.catch {

    MyStrings(
        a = "Hello",
        b = either2().getOrElse { "" }
    )

}.mapLeft { Error.SpecificError2 }
</code>```

This will swallow the error from either2().

I'm trying to find a way to throw this error from either2 back if possible.

I know I can do something like this:

```<code>fun either5(): Either<Error, MyStrings> =
either2()
    .flatMap {
        Either.Right(
            MyStrings(
                a = "Hello",
                b = it
            )
        )
    }
</code>```

but it seems strange to call something before I need it!

Any thoughts on how I can change either4()? Sorry if this is a n00b question, but I'm still trying to wrap my head around functional programming and Arrow.

Thank you.

答:
kumbera,

In the last snippet you're not really calling it before you need it, but semantically it does look that way. Since MyStrings depends on the result of either2(), but we can rewrite it in a nicer way that scales much nicer without nesting callbacks.

You can improve these snippets by utilising Arrow's computation blocks, which allow extracting values out of Either in a safe way.

fun either5(): Either<Error, MyStrings> = either.eager {
  MyStrings(a = "Hello", b = either2().bind())
}
```
<p>What happens here is that when you call <code>bind</code> it will either return the value of <code>Either.Right</code>, or it will immediately return the <code>Either.Left</code> returned by <code>either2()</code> as the result of <code>either.eager</code>.</p>
<p>There is also a <code>suspend</code> variant of the <code>either</code> computation block that you can use directly as</p>
<pre class="lang-kotlin prettyprint-override"><code>suspend fun either6(): Either<Error, MyString> = either {
  delay(100)
  MyStrings(a = "Hello", b = either2().bind())
}
</code>```

I hope that completely answers your question!

Body:
I have some code that looks like this:

data class MyStrings(val a: String, val b: String)

sealed class Error {
    object SpecificError0 : Error()
    object SpecificError1 : Error()
    object SpecificError2 : Error()
}

fun either2(): Either<Error, String> =
Either.catch { throw RuntimeException("Either 2") }.mapLeft { Error.SpecificError2 }

fun either4(): Either<Error, MyStrings> =
Either.catch {

    MyStrings(
        a = "Hello",
        b = either2().getOrElse { "" }
    )

}.mapLeft { Error.SpecificError2 }

This will swallow the error from either2().

I'm trying to find a way to throw this error from either2 back if possible.

I know I can do something like this:

fun either5(): Either<Error, MyStrings> =
either2()
    .flatMap {
        Either.Right(
            MyStrings(
                a = "Hello",
                b = it
            )
        )
    }

but it seems strange to call something before I need it!

Any thoughts on how I can change either4()? Sorry if this is a n00b question, but I'm still trying to wrap my head around functional programming and Arrow.

Thank you.

Body:
kumbera,

In the last snippet you're not really calling it before you need it, but semantically it does look that way. Since MyStrings depends on the result of either2(), but we can rewrite it in a nicer way that scales much nicer without nesting callbacks.

You can improve these snippets by utilising Arrow's computation blocks, which allow extracting values out of Either in a safe way.

fun either5(): Either<Error, MyStrings> = either.eager {
  MyStrings(a = "Hello", b = either2().bind())
}

What happens here is that when you call bind it will either return the value of Either.Right, or it will immediately return the Either.Left returned by either2() as the result of either.eager.

There is also a suspend variant of the either computation block that you can use directly as

suspend fun either6(): Either<Error, MyString> = either {
  delay(100)
  MyStrings(a = "Hello", b = either2().bind())
}

I hope that completely answers your question!


问:
Why does the picture not show in a loop?
```<code>from PIL import Image
Pikachu=Image.open('pikachu.png')
Charizard=Image.open('charizard.png')

pokemon_list=('PIKACHU','CHARIZARD')
picture={'PIKACHU':Pikachu,'CHARIZARD':Charizard}
Pokemon=pokemon_list[Count]

Count=0
while (Count!=3):
    picture[Pokemon]
    Count+=1
</code>```

The picture does not show up when it is in a loop, how do I make it work?

答:
It is because you call it in wrong order. Notice, that you have 2 elements in list, so you cannot get more objects than [0], [1]. And you need to open files in rb mode.

And finally to show an Image, you have to use that funtion: show().

Full code here:

```<code>from PIL import Image

Pikachu = open('1.jpg', 'rb')
Charizard = open('2.jpg', 'rb')

pokemon_list = ('PIKACHU', 'CHARIZARD')
picture = {'PIKACHU': Pikachu, 'CHARIZARD': Charizard}

Count = 0
while Count < 2:
    Pokemon = pokemon_list[Count]
    Image.open(picture[Pokemon]).show()
    Count += 1
</code>```

Body:
from PIL import Image
Pikachu=Image.open('pikachu.png')
Charizard=Image.open('charizard.png')

pokemon_list=('PIKACHU','CHARIZARD')
picture={'PIKACHU':Pikachu,'CHARIZARD':Charizard}
Pokemon=pokemon_list[Count]

Count=0
while (Count!=3):
    picture[Pokemon]
    Count+=1

The picture does not show up when it is in a loop, how do I make it work?

Body:
It is because you call it in wrong order. Notice, that you have 2 elements in list, so you cannot get more objects than [0], [1]. And you need to open files in rb mode.

And finally to show an Image, you have to use that funtion: show().

Full code here:

from PIL import Image

Pikachu = open('1.jpg', 'rb')
Charizard = open('2.jpg', 'rb')

pokemon_list = ('PIKACHU', 'CHARIZARD')
picture = {'PIKACHU': Pikachu, 'CHARIZARD': Charizard}

Count = 0
while Count < 2:
    Pokemon = pokemon_list[Count]
    Image.open(picture[Pokemon]).show()
    Count += 1


问:
cannot access personal github from work laptop
I have generated an SSH key on my work laptop (ssh-keygen -t ed25519 -C "me@my-personal-email.org") and added it to the list of SSH keys of my personal repository. Yet when I try to git push to this personal repo (from my work laptop) I get the message:

```<code>ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I also added these lines to the repo .git/config:

```<code>[user]
    name = MY NAME
    email = me@my-personal-email.org
</code>```

... and I get the same error.

The repo definitely exists and I thought I had set up access... what could I be missing?

答:
Check if you have done the step to add the SSH key to the SSH agent:

```<code># start the ssh-agent in the background
$ eval "$(ssh-agent -s)"
> Agent pid 59566
</code>```

and, then

```<code>$ ssh-add ~/.ssh/id_ed25519
</code>```

Essentially, you need to inform git which private key you will be using for the git connection.

```<code>Host One
    HostName ssh.github.com
    IdentityFile ~/.ssh/id_rsa
    User git

Host Two
    HostName ssh.<enterprise>.github.com
    IdentityFile ~/.ssh/id_rsa
    User git
</code>```

References

https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#adding-your-ssh-key-to-the-ssh-agent

https://support.atlassian.com/bitbucket-cloud/docs/set-up-an-ssh-key/

Body:
I have generated an SSH key on my work laptop (ssh-keygen -t ed25519 -C "me@my-personal-email.org") and added it to the list of SSH keys of my personal repository. Yet when I try to git push to this personal repo (from my work laptop) I get the message:

ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I also added these lines to the repo .git/config:

[user]
    name = MY NAME
    email = me@my-personal-email.org

... and I get the same error.

The repo definitely exists and I thought I had set up access... what could I be missing?

Body:
Check if you have done the step to add the SSH key to the SSH agent:

# start the ssh-agent in the background
$ eval "$(ssh-agent -s)"
> Agent pid 59566

and, then

$ ssh-add ~/.ssh/id_ed25519

Essentially, you need to inform git which private key you will be using for the git connection.

Host One
    HostName ssh.github.com
    IdentityFile ~/.ssh/id_rsa
    User git

Host Two
    HostName ssh.<enterprise>.github.com
    IdentityFile ~/.ssh/id_rsa
    User git

References

https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#adding-your-ssh-key-to-the-ssh-agent

https://support.atlassian.com/bitbucket-cloud/docs/set-up-an-ssh-key/


问:
The useState is not being updated correctly in a loop
I am working on a certificate generator, where I have a list of name and i want to ithrate through those name and display them on a certificate, then download that certificate as a pdf. And then I move on to the next name and so on.

```<code>const _exportPdf = async () => {

    // if namelist is not uploaded
    if (nameList == null){
      console.log("Name List not uploaded");
      return;
    }

    // if name is uploaded
    Object.keys(nameList).forEach(async function(key){
      const name = nameList[key];
      // export the certificate as a pdf
      await html2canvas(document.querySelector("#capture")).then(canvas => {
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
    })
   });

  }
</code>```

Currently I have 5 names in my sample nameList, when I use this function, I can see the name changeing on the certificate, but all the 5 downloaded certificates have "Sample Name" written on it (Sample Name is the default value of the visible name).

Need help.

答:
Firstly you are using forEach within which promises don't work because the JS engine doesn't wait for the promise to be resolved/reject and instead puts the promise in a queue and continues executing the loop, secondly, you are using both await and then to resolve/reject the same promise.
Either, use .then syntax or await syntax.

```<code>const names = Object.keys(nameList)
for(name of names){
      // export the certificate as a pdf
        const canvas = await html2canvas(document.querySelector("#capture")) //Wait for the promise to resolve/reject. Recommend to wrap it in try-catch block to handle errors.
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
}
</code>```

Also, you haven't mentioned, where and how exactly are you making use of the state variable, but most likely you would've gotten the wrong result due to the incorrect usage of promises. Remember updates in the state cause the component to re-render.

Body:
I am working on a certificate generator, where I have a list of name and i want to ithrate through those name and display them on a certificate, then download that certificate as a pdf. And then I move on to the next name and so on.

const _exportPdf = async () => {

    // if namelist is not uploaded
    if (nameList == null){
      console.log("Name List not uploaded");
      return;
    }

    // if name is uploaded
    Object.keys(nameList).forEach(async function(key){
      const name = nameList[key];
      // export the certificate as a pdf
      await html2canvas(document.querySelector("#capture")).then(canvas => {
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
    })
   });

  }

Currently I have 5 names in my sample nameList, when I use this function, I can see the name changeing on the certificate, but all the 5 downloaded certificates have "Sample Name" written on it (Sample Name is the default value of the visible name).

Need help.

Body:
Firstly you are using forEach within which promises don't work because the JS engine doesn't wait for the promise to be resolved/reject and instead puts the promise in a queue and continues executing the loop, secondly, you are using both await and then to resolve/reject the same promise.
Either, use .then syntax or await syntax.

const names = Object.keys(nameList)
for(name of names){
      // export the certificate as a pdf
        const canvas = await html2canvas(document.querySelector("#capture")) //Wait for the promise to resolve/reject. Recommend to wrap it in try-catch block to handle errors.
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
}

Also, you haven't mentioned, where and how exactly are you making use of the state variable, but most likely you would've gotten the wrong result due to the incorrect usage of promises. Remember updates in the state cause the component to re-render.


问:
NodeJs Helmet contentSecurityPolicy blocking fonts
I am not sure why it allows other fonts from google fonts, but it always blocks material icons and fontawesome. I tried writing google fonts in different ways, but it still does not work. I am not sure what is the correct way of writing the domains that are allowed If I set add '*' to the end of the list then google material fonts loads correctly. Please let me know what I am doing wrong, here is my code

const safeToLoadFonts = [
    "'self'",
    'fonts.googleapis.com/icon?family=Material+Icons',
    'fonts.googleapis.com/*',
    'fonts.googleapis.com/',
    'googleapis.com/*',
    'googleapis.com/',

    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css',
    'cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css',
    "'unsafe-inline'",
]

app.use(
    helmet.contentSecurityPolicy({
        directives: {
            // defaultSrc: ['*', "'unsafe-inline'"],
            // "script-src": ['*', "'unsafe-inline'"],
            // "style-src": ['*', "'unsafe-inline'"],
            "font-src": safeToLoadFonts,
            // "img-src": ['*', "'unsafe-inline'"],
            // "form-action":[ '*', "'unsafe-inline'"]
        },
    })
);
```
<p>I am also getting this error for material icons:</p>
```The source list for Content Security Policy directive 'font-src' contains a source with an invalid path: '/icon?family=Material+Icons'. The query component, including the '?', will be ignored.
```
<p>I am getting this error for font-awesome:</p>
```Refused to load the font '<URL>' because it violates the following Content Security Policy directive: "font-src 'self' <URL> <URL> fonts.googleapis.com/icon?family=Material+Icons fonts.googleapis.com/* fonts.googleapis.com/ googleapis.com/* googleapis.com/ <URL> cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css 'unsafe-inline'".
```

答:
Does it work if you omit the two entries

'fonts.googleapis.com/icon?family=Material+Icons',
'fonts.googleapis.com/*',
```

from your list?

The first error is a warning that the ?family=Material+Icons part of the URL will be ignored, therefore this rule only matches fonts.googleapis.com/icon.

The rule fonts.googleapis.com/* does not match child paths, the asterisk does not have the meaning you seem to assume here.

Rules ending with a slash, like fonts.googleapis.com/, do match child paths, but since your CSP additionally contains the stricter rule ending in /icon, perhaps the stricter one is applied, blocking the child paths that you need.

Body:
I am not sure why it allows other fonts from google fonts, but it always blocks material icons and fontawesome. I tried writing google fonts in different ways, but it still does not work. I am not sure what is the correct way of writing the domains that are allowed If I set add '*' to the end of the list then google material fonts loads correctly. Please let me know what I am doing wrong, here is my code

const safeToLoadFonts = [
    "'self'",
    'fonts.googleapis.com/icon?family=Material+Icons',
    'fonts.googleapis.com/*',
    'fonts.googleapis.com/',
    'googleapis.com/*',
    'googleapis.com/',

    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css',
    'cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css',
    "'unsafe-inline'",
]

app.use(
    helmet.contentSecurityPolicy({
        directives: {
            // defaultSrc: ['*', "'unsafe-inline'"],
            // "script-src": ['*', "'unsafe-inline'"],
            // "style-src": ['*', "'unsafe-inline'"],
            "font-src": safeToLoadFonts,
            // "img-src": ['*', "'unsafe-inline'"],
            // "form-action":[ '*', "'unsafe-inline'"]
        },
    })
);

I am also getting this error for material icons:

The source list for Content Security Policy directive 'font-src' contains a source with an invalid path: '/icon?family=Material+Icons'. The query component, including the '?', will be ignored.

I am getting this error for font-awesome:

Refused to load the font '<URL>' because it violates the following Content Security Policy directive: "font-src 'self' <URL> <URL> fonts.googleapis.com/icon?family=Material+Icons fonts.googleapis.com/* fonts.googleapis.com/ googleapis.com/* googleapis.com/ <URL> cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css 'unsafe-inline'".

Body:
Does it work if you omit the two entries

'fonts.googleapis.com/icon?family=Material+Icons',
'fonts.googleapis.com/*',

from your list?

The first error is a warning that the ?family=Material+Icons part of the URL will be ignored, therefore this rule only matches fonts.googleapis.com/icon.

The rule fonts.googleapis.com/* does not match child paths, the asterisk does not have the meaning you seem to assume here.

Rules ending with a slash, like fonts.googleapis.com/, do match child paths, but since your CSP additionally contains the stricter rule ending in /icon, perhaps the stricter one is applied, blocking the child paths that you need.


问:
Using Arduino Libraries with AVR-G++
Is there a simple way to use libraries intended for the Arduino IDE with the C and assembly code I write for AVR-G++/AVR-GCC?

I'm trying to use the Adafruit Wave Shield library, but simply including the header and cpp files don't do much good. Can I compile it somehow and link it to my C code? Or perhaps just find a way to make it compile with my C code.

Currently, when I try to do something simple like:

```<code>#include "WaveHC/WaveHC.h"
SdReader card;
card.init();
</code>```

I am greeted with:

```<code>70: undefined reference to `SdReader::init(unsigned char)'
</code>```

答:
You can build the Arduino code with CMake. I have built largish Arduino projects without using the IDE this way. You can use whatever tools you want to build the Arduino code, it is just a C/C++ library. You mainly need to make sure you have all of the preprocessor settings right (F_CPU? Maybe some others).

Build using Cmake might help you. Basically, I would make a library file for the Arduino library, a library file for the shield library, and an EXE file for your code.

Title: Using Arduino Libraries with AVR-G++

Body:
Is there a simple way to use libraries intended for the Arduino IDE with the C and assembly code I write for AVR-G++/AVR-GCC?

I'm trying to use the Adafruit Wave Shield library, but simply including the header and cpp files don't do much good. Can I compile it somehow and link it to my C code? Or perhaps just find a way to make it compile with my C code.

Currently, when I try to do something simple like:

#include "WaveHC/WaveHC.h"
SdReader card;
card.init();

I am greeted with:

70: undefined reference to `SdReader::init(unsigned char)'


问:
Is the 8088 processor 8 bit or 16 bit?
In Randall Hyde's Art of Assembly it says the 8088 CPU was 8 bits whilst the 8086 was 16 bits solely because of the width of the data bus.

I have always thought that the address size determined the size of the CPU.

Please shed some light on this issue.

答:
I can't find any official definition of the property "x-bit cpu", i suppose it does not exist.

I would say that "x-bit cpu" property indicates that the cpu can manipulate the data (inside the chip) with the size of "x-bits" at once. To be more specific  it has so called general registers with the size of "x"bits. So it can add (subtract, divide, multiply, xor etc) the data of "x-bits" length at once.

```<code>8086 has 16-bit general registers = 16-bit cpu

8088 has 16-bit general registers = 16-bit cpu

80510 has 32-bit general registers = 32-bit cpu
</code>```

Again, the official definition of the property is unknown.

the wiki about ia-32  says =

The primary defining characteristic of IA-32 is the availability of
32-bit general-purpose processor registers (for example, EAX and EBX),
32-bit integer arithmetic and logical operations, 32-bit offsets
within a segment in protected mode, and the translation of segmented
addresses to 32-bit linear addresses.

I prefer to think that the bitnes of general registers is  enough to determine the x-bit cpu property.

The funny thing is intel itself defines cpu bitness by using different criteria from time to time. if you look at the official intel doc it says

8088 is 8-bit hmos microprocessor

( i suppose they defined 8-bit cpu based on 8-bit data bus interface. remember this criteria). At the same time they say at the same document that the cpu has

16-bit internal architecture

Thats funny.. 8-bit cpu with 16-bit internal architecture.

Okey. Lets look at another example Intel pentium 510.

They say it is

32-bit microprocessor

the cpu has 64-bit data bus, so based on previous example we would need to say that intel 510 is 64-bit cpu however it is wrong.

The conclusion - to determine cpu bitness look at the size of general registers.

Title: Is the 8088 processor 8 bit or 16 bit?

Body:
I can't find any official definition of the property "x-bit cpu", i suppose it does not exist.

I would say that "x-bit cpu" property indicates that the cpu can manipulate the data (inside the chip) with the size of "x-bits" at once. To be more specific  it has so called general registers with the size of "x"bits. So it can add (subtract, divide, multiply, xor etc) the data of "x-bits" length at once.

8086 has 16-bit general registers = 16-bit cpu

8088 has 16-bit general registers = 16-bit cpu

80510 has 32-bit general registers = 32-bit cpu

Again, the official definition of the property is unknown.

the wiki about ia-32  says =

The primary defining characteristic of IA-32 is the availability of
32-bit general-purpose processor registers (for example, EAX and EBX),
32-bit integer arithmetic and logical operations, 32-bit offsets
within a segment in protected mode, and the translation of segmented
addresses to 32-bit linear addresses.

I prefer to think that the bitnes of general registers is  enough to determine the x-bit cpu property.

The funny thing is intel itself defines cpu bitness by using different criteria from time to time. if you look at the official intel doc it says

8088 is 8-bit hmos microprocessor

( i suppose they defined 8-bit cpu based on 8-bit data bus interface. remember this criteria). At the same time they say at the same document that the cpu has

16-bit internal architecture

Thats funny.. 8-bit cpu with 16-bit internal architecture.

Okey. Lets look at another example Intel pentium 510.

They say it is

32-bit microprocessor

the cpu has 64-bit data bus, so based on previous example we would need to say that intel 510 is 64-bit cpu however it is wrong.

The conclusion - to determine cpu bitness look at the size of general registers.


问:
reverse geocodoing with tidygeocoder and OSM/Nominatim: How to get results in latin letters/English?
I am reverse geocoding coordinates which pertain to addresses in countries where the Cyrillic alphabet is used. I am using tidygeocoder and OSM/Nominatim as a method. How can I modify my request in tidygeocoder to get the results/addresses not in Cyrillic but in Latin letters/in English?

As far as I can tell, the relevant property in the Nominatim/OSM API is accept-language (see here and here). But adding it to a tidygeocoder request seems not to work.

```<code>library(tidygeocoder)
library(tidyverse)

df_res <- tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm")
</code>```

The resulting address reads as

Шпаркасе, Македонија, Водно, Центар, Скопје, Општина Центар, Град
Скопје, Скопски СР, 1111, Северна Македонија

Modifying the request to (as suggested here):

```<code>tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm",
                  api_options = list(osm_accept_language="en")
  )
</code>```

leads to an error:

```<code>Error: Invalid parameter "osm_accept_language" used in the api_options argument. See ?reverse_geo
</code>```

Any help? The error also occurs when using "osm_accept-language". Many thanks!

答:
Thanks to a reply from the package author on github I found the answer:</p>
```<code>df_res <- tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm",
                  custom_query  = list("accept-language"="en-US"))
</code>```

Body:
I am reverse geocoding coordinates which pertain to addresses in countries where the Cyrillic alphabet is used. I am using tidygeocoder and OSM/Nominatim as a method. How can I modify my request in tidygeocoder to get the results/addresses not in Cyrillic but in Latin letters/in English?

As far as I can tell, the relevant property in the Nominatim/OSM API is accept-language (see here and here). But adding it to a tidygeocoder request seems not to work.

library(tidygeocoder)
library(tidyverse)

df_res <- tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm")

The resulting address reads as

Шпаркасе, Македонија, Водно, Центар, Скопје, Општина Центар, Град
Скопје, Скопски СР, 1111, Северна Македонија

Modifying the request to (as suggested here):

tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm",
                  api_options = list(osm_accept_language="en")
  )

leads to an error:

Error: Invalid parameter "osm_accept_language" used in the api_options argument. See ?reverse_geo

Any help? The error also occurs when using "osm_accept-language". Many thanks!

Body:
Thanks to a reply from the package author on github I found the answer:

df_res <- tibble(
  lat=41.992073,
  long=21.429506
) %>%
  reverse_geocode(.,
                  lat=lat,
                  long=long,
                  address="address",
                  method="osm",
                  custom_query  = list("accept-language"="en-US"))


问:
Gist Vs. Repository for Tutorial
I'm publishing a tutorial that includes a lot of code interspersed with documentation. I'm considering two ways of hosting the code:

Separate git repository with code files and markdown files explaining the code

Github gist containing both of these

Are there advantages of hosting in a gist v/s a repository? When would one prefer one of these over the other?

答:
If you use markdown files for your tutorial, now there is one important difference, even if you are only creating one file (and specially if it is a long one).

Since April 2021, .md files created in github repositories now include an automatic Table of Contents which greatly improves navegability. See this related SO answer for more info.

As far as I know, this automatic ToC does not exist in gist-created .md files, so I'd rather go for a repository in this case (OP mentioned "a lot of code interspersed with documentation").

Title: Gist Vs. Repository for Tutorial


问:
How to use regex to extract a string with multiple curly braces?
I have this sample string

```<code>`{1:}{2:}{3:}{4:\r\n-}{5:}`
</code>```

and I want to extract out only {4:\r\n-}

This is my code but it is not working.

```<code>var str = "{1:}{2:}{3:}{4:\r\n-}{5:}";
var regex = new Regex(@"{4:*.*-}");
var match = regex.Match(str);
</code>```

答:
You need to escape the special regex characters (in this case the opening and closing braces and the backslashes) in the search string. This would capture just that part:

```<code>var regex = new Regex("\{4:\\r\\n-\}");
</code>```

... or if you wanted anything up to and including the slash before the closing brace (which is what it looks like you might be trying to do)...

```<code>var regex = new Regex("\{4:[^-]*-\}");
</code>```

Body:
I have this sample string

`{1:}{2:}{3:}{4:\r\n-}{5:}`

and I want to extract out only {4:\r\n-}

This is my code but it is not working.

var str = "{1:}{2:}{3:}{4:\r\n-}{5:}";
var regex = new Regex(@"{4:*.*-}");
var match = regex.Match(str);

Body:
You need to escape the special regex characters (in this case the opening and closing braces and the backslashes) in the search string. This would capture just that part:

var regex = new Regex("\{4:\\r\\n-\}");

... or if you wanted anything up to and including the slash before the closing brace (which is what it looks like you might be trying to do)...

var regex = new Regex("\{4:[^-]*-\}");


问:
confused about formatter in numpy. set_printoptions
I encountered the following piece of code:

```<code>z=np.arange(0,12)
np.set_printoptions(formatter=dict(int=lambda x: f'{x:4}'))
print(z)
</code>```

I understand what the code is doing but I am not clear as to what the quantity inside the brackets of dict() is. Without int= we have a function. In numpy docs the value of formatter should be a dict of callables. The keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. So shouldn't it be int: instead of int=? I got a synatx error when I tried that

答:
They keys for the formatter dict should be strings for the corresponding datatype.  check docs for formatter argument.

```<code>d1 = {"int":lambda x: x}
d2 = dict(int=lambda x: x)
d3 = {int:lambda x: x}

print (d1.keys(), d2.keys(), d3.keys())
</code>```

Output:

```<code>dict_keys(['int']) dict_keys(['int']) dict_keys([<class 'int'>])
</code>```

As you can see, you can use either use {"int":.....} or dict(int=...}

Body:
I encountered the following piece of code:

z=np.arange(0,12)
np.set_printoptions(formatter=dict(int=lambda x: f'{x:4}'))
print(z)

I understand what the code is doing but I am not clear as to what the quantity inside the brackets of dict() is. Without int= we have a function. In numpy docs the value of formatter should be a dict of callables. The keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. So shouldn't it be int: instead of int=? I got a synatx error when I tried that

Body:
They keys for the formatter dict should be strings for the corresponding datatype.  check docs for formatter argument.

d1 = {"int":lambda x: x}
d2 = dict(int=lambda x: x)
d3 = {int:lambda x: x}

print (d1.keys(), d2.keys(), d3.keys())

Output:

dict_keys(['int']) dict_keys(['int']) dict_keys([<class 'int'>])

As you can see, you can use either use {"int":.....} or dict(int=...}


问:
Jmeter generate HTTP TimeStampRequest RFC3161
I would like to use Jmeter to generate HTTP TimeStampRequests "application/timestamp-query" as presented in the standard RFC3161.
Currently I'm using Java program to do it but I would like to improve it by using Jmeter functionalities.

Is it possible to do it ?

答:
If you want to use JMeter's HTTP Request samplers you can:

Compile your code into .jar file

Put the .jar into JMeter Classpath

Use the function from the .jar file to generate the request body from the JSR223 PreProcessor

Set the request body to the value generated in the step 3

More information:

How to Reuse Your JMeter Code with JAR Files and Save Time

Programmatically set POST binary content to HTTP sampler in Jmeter


问:
how to keep session enabled in firebase/auth js?
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code</p>
```<code>const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}
</code>```

答:
you can use redux-persist so if reload page , redux store will persist.
this document my help you
https://react-redux-firebase.com/docs/integrations/redux-persist.html</p>

Body:
When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work.
This is my code

const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}


问:
Error message; Cannot access class 'androidx.compose.ui.Alignment.Horizontal'. Check your module classpath for missing or conflicting dependencies
I am making a QR Code Scanner app using Jetpack compose. But when I am trying to use Column, the composable function then the compiler is giving me this error:
Cannot access class 'androidx.compose.ui.Alignment.Horizontal'. Check your module classpath for missing or conflicting dependencies

Here is my app build.gradle module for the app:

```<code>    plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.plcoding.qrcodescannercompose"
        minSdk 26
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
    implementation("androidx.compose.foundation:foundation:1.0.5")
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // Activity Compose
    implementation "androidx.activity:activity-compose:1.4.0"

    // CameraX
    implementation "androidx.camera:camera-camera2:1.0.2"
    implementation "androidx.camera:camera-lifecycle:1.0.2"
    implementation "androidx.camera:camera-view:1.1.0-beta01"

    // Zxing
    implementation 'com.google.zxing:core:3.3.3'
}
</code>```

Update: This is the code that is generating the error:

I don't know what this error message is saying and how to resolve this?

答:
Make sure to upgrade your version of Compose to the latest stable version which is 1.1.0-rc03

If your project consists of multiple modules, make sure that all of them are using the same version of Compose.

Body:
I am making a QR Code Scanner app using Jetpack compose. But when I am trying to use Column, the composable function then the compiler is giving me this error:
Cannot access class 'androidx.compose.ui.Alignment.Horizontal'. Check your module classpath for missing or conflicting dependencies

Here is my app build.gradle module for the app:

    plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.plcoding.qrcodescannercompose"
        minSdk 26
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.21'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
    implementation("androidx.compose.foundation:foundation:1.0.5")
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // Activity Compose
    implementation "androidx.activity:activity-compose:1.4.0"

    // CameraX
    implementation "androidx.camera:camera-camera2:1.0.2"
    implementation "androidx.camera:camera-lifecycle:1.0.2"
    implementation "androidx.camera:camera-view:1.1.0-beta01"

    // Zxing
    implementation 'com.google.zxing:core:3.3.3'
}

Update: This is the code that is generating the error:

I don't know what this error message is saying and how to resolve this?


问:
different method of running pytorch on gpu
See the code block below (the source of the code can be found here, also you don't need to read the whole block, I will explain and highlight the important part)

```<code>def train(data_loader, model, optimizer, scheduler, total_epochs, save_interval, save_folder, sets):
    # settings
    batches_per_epoch = len(data_loader) #
    log.info('{} epochs in total, {} batches per epoch'.format(total_epochs, batches_per_epoch))
    loss_seg = nn.CrossEntropyLoss(ignore_index=-1)

    print("Current setting is:")
    print(sets)
    print("\n\n")
    if not sets.no_cuda:
        loss_seg = loss_seg.cuda()

    # change model in training mode, enable batch normalization etc
    model.train()

    # record train time
    train_time_sp = time.time()

    # loop to train the model
    for epoch in range(total_epochs):
        log.info('Start epoch {}'.format(epoch))

        scheduler.step()
        log.info('lr = {}'.format(scheduler.get_lr()))

        for batch_id, batch_data in enumerate(data_loader):
            # getting data batch
            batch_id_sp = epoch * batches_per_epoch
            volumes, label_masks = batch_data

            if not sets.no_cuda:
                volumes = volumes.cuda()

            optimizer.zero_grad()
            out_masks = model(volumes)
            # resize label
            [n, _, d, h, w] = out_masks.shape
            new_label_masks = np.zeros([n, d, h, w])
            for label_id in range(n):
                label_mask = label_masks[label_id]
                [ori_c, ori_d, ori_h, ori_w] = label_mask.shape
                label_mask = np.reshape(label_mask, [ori_d, ori_h, ori_w])
                scale = [d*1.0/ori_d, h*1.0/ori_h, w*1.0/ori_w]
                label_mask = ndimage.interpolation.zoom(label_mask, scale, order=0)
                new_label_masks[label_id] = label_mask

            new_label_masks = torch.tensor(new_label_masks).to(torch.int64)
            if not sets.no_cuda:
                new_label_masks = new_label_masks.cuda()

            # calculating loss
            loss_value_seg = loss_seg(out_masks, new_label_masks)
            loss = loss_value_seg
            loss.backward()
            optimizer.step()

            avg_batch_time = (time.time() - train_time_sp) / (1 + batch_id_sp)
            log.info(
                    'Batch: {}-{} ({}), loss = {:.3f}, loss_seg = {:.3f}, avg_batch_time = {:.3f}'\
                    .format(epoch, batch_id, batch_id_sp, loss.item(), loss_value_seg.item(), avg_batch_time))

            if not sets.ci_test:
                # save model
                if batch_id == 0 and batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                #if batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                    model_save_path = '{}_epoch_{}_batch_{}.pth.tar'.format(save_folder, epoch, batch_id)
                    model_save_dir = os.path.dirname(model_save_path)
                    if not os.path.exists(model_save_dir):
                        os.makedirs(model_save_dir)

                    log.info('Save checkpoints: epoch = {}, batch_id = {}'.format(epoch, batch_id))
                    torch.save({
                                'ecpoch': epoch,
                                'batch_id': batch_id,
                                'state_dict': model.state_dict(),
                                'optimizer': optimizer.state_dict()},
                                model_save_path)

    print('Finished training')
    if sets.ci_test:
        exit()
</code>```

This is a customised training function, the author achieve GPU running by using code loss_seg = loss_seg.cuda() where loss_seg is a instance of torch.optim.SGD. This part confused me, because according to the official documentation in pytorch, I only need to move my model and my input data to gpu is enough. I want to know why the author who write the code below also move the optimizer to the gpu and more details about running pytorch on gpu.

答:
In general, in order to harness the full power of GPUs, every stateful Module should be sent to a cuda device before the forward step. A stateful Module has an internal state, e.g. Parameter (weights).

This is not usually the case of Loss, which, in general, applies just a functional that has been already implemented for cuda devices.

In conclusion, if the loss is stateful, then it makes sense to send it to a cuda device, otherwise, it is not necessary.

Have also a look at this question in the PyTorch forum.

Body:
See the code block below (the source of the code can be found here, also you don't need to read the whole block, I will explain and highlight the important part)

def train(data_loader, model, optimizer, scheduler, total_epochs, save_interval, save_folder, sets):
    # settings
    batches_per_epoch = len(data_loader) #
    log.info('{} epochs in total, {} batches per epoch'.format(total_epochs, batches_per_epoch))
    loss_seg = nn.CrossEntropyLoss(ignore_index=-1)

    print("Current setting is:")
    print(sets)
    print("\n\n")
    if not sets.no_cuda:
        loss_seg = loss_seg.cuda()

    # change model in training mode, enable batch normalization etc
    model.train()

    # record train time
    train_time_sp = time.time()

    # loop to train the model
    for epoch in range(total_epochs):
        log.info('Start epoch {}'.format(epoch))

        scheduler.step()
        log.info('lr = {}'.format(scheduler.get_lr()))

        for batch_id, batch_data in enumerate(data_loader):
            # getting data batch
            batch_id_sp = epoch * batches_per_epoch
            volumes, label_masks = batch_data

            if not sets.no_cuda:
                volumes = volumes.cuda()

            optimizer.zero_grad()
            out_masks = model(volumes)
            # resize label
            [n, _, d, h, w] = out_masks.shape
            new_label_masks = np.zeros([n, d, h, w])
            for label_id in range(n):
                label_mask = label_masks[label_id]
                [ori_c, ori_d, ori_h, ori_w] = label_mask.shape
                label_mask = np.reshape(label_mask, [ori_d, ori_h, ori_w])
                scale = [d*1.0/ori_d, h*1.0/ori_h, w*1.0/ori_w]
                label_mask = ndimage.interpolation.zoom(label_mask, scale, order=0)
                new_label_masks[label_id] = label_mask

            new_label_masks = torch.tensor(new_label_masks).to(torch.int64)
            if not sets.no_cuda:
                new_label_masks = new_label_masks.cuda()

            # calculating loss
            loss_value_seg = loss_seg(out_masks, new_label_masks)
            loss = loss_value_seg
            loss.backward()
            optimizer.step()

            avg_batch_time = (time.time() - train_time_sp) / (1 + batch_id_sp)
            log.info(
                    'Batch: {}-{} ({}), loss = {:.3f}, loss_seg = {:.3f}, avg_batch_time = {:.3f}'\
                    .format(epoch, batch_id, batch_id_sp, loss.item(), loss_value_seg.item(), avg_batch_time))

            if not sets.ci_test:
                # save model
                if batch_id == 0 and batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                #if batch_id_sp != 0 and batch_id_sp % save_interval == 0:
                    model_save_path = '{}_epoch_{}_batch_{}.pth.tar'.format(save_folder, epoch, batch_id)
                    model_save_dir = os.path.dirname(model_save_path)
                    if not os.path.exists(model_save_dir):
                        os.makedirs(model_save_dir)

                    log.info('Save checkpoints: epoch = {}, batch_id = {}'.format(epoch, batch_id))
                    torch.save({
                                'ecpoch': epoch,
                                'batch_id': batch_id,
                                'state_dict': model.state_dict(),
                                'optimizer': optimizer.state_dict()},
                                model_save_path)

    print('Finished training')
    if sets.ci_test:
        exit()

This is a customised training function, the author achieve GPU running by using code loss_seg = loss_seg.cuda() where loss_seg is a instance of torch.optim.SGD. This part confused me, because according to the official documentation in pytorch, I only need to move my model and my input data to gpu is enough. I want to know why the author who write the code below also move the optimizer to the gpu and more details about running pytorch on gpu.


问:
How to access the UI thread?
I have a Winform APP that does a simple task.
There is an event listener for a button that create a new thread:

```<code>  ThreadStart work = (addToList);
  Thread thread = new Thread(work);
  thread.Start();

</code>```

Now I need the second part of the calculation ot be done with the UI thread (so my instruction ask)
"
Note that you need to access the list box within the UI thread (hint: you can use Control.Invoke for WinForm
"

Any idea how to do so?

答:
The Invoke method needs a delegate (reference to a function) and will schedule that on UI thread. Considering that all the elements on the form share the same thread as UI thread, you can use the Invoke method from either the form or any of its controls:

class MyForm
{
  private void Button_Click(object sender, EventArgs e)
  {
    var thread = new Thread(new ThreadStart(FullCalculation));
    thread.Start();
  }

  private void FullCalculation()
  {
    OffUIThreadCalculation();
    this.Invoke(OnUIThreadCalculation); // Schedules OnUIThreadCalculation to run on the UI thread of `this`, aka the form
  }

  private void OffUIThreadCalculation()
  {
    // UI elements should not be used here
  }

  private void OnUIThreadCalculation()
  {
    // UI elements can be used here
  }
}
```

Title: How to access the UI thread?

Body:
I have a Winform APP that does a simple task.
There is an event listener for a button that create a new thread:

  ThreadStart work = (addToList);
  Thread thread = new Thread(work);
  thread.Start();

Now I need the second part of the calculation ot be done with the UI thread (so my instruction ask)
"
Note that you need to access the list box within the UI thread (hint: you can use Control.Invoke for WinForm
"

Any idea how to do so?


问:
Converting GDIPlus::Bitmap to cv::Mat (OpenCV C++ interface)
I'm trying to convert a GDIPlus::Bitmap into an openCV Mat object, but I'm running into problems with Access Violations, which means I'm not doing something right, but I've looked over the code over and over, and I think it should work.

Does anyone see an obvious problem?

```<code>cv::Mat ConvertToOpenCV(Gdiplus::Bitmap &image) {
    cv::Mat *retval = new cv::Mat(
        image.GetWidth(), image.GetHeight(), CV_8UC3
    );

    Gdiplus::BitmapData source;

    Gdiplus::Rect rect( 0, 0, image.GetWidth(), image.GetHeight() );
    Gdiplus::Status status =
        image.LockBits( &rect, Gdiplus::ImageLockModeRead, PixelFormat24bppRGB, &source );
    if ( status != Gdiplus::Ok ) {
        // Some error condition
        return retval; // No image copied
    }

    BYTE *destination = (BYTE *)retval->data;

    for ( int y = 0; y != source.Height; ++y ) {
        BYTE *src = (BYTE *) source.Scan0 + y * source.Stride;
        BYTE *dst = (BYTE *)(destination + y * retval->step);
        memcpy( dst, src, 3 * source.Width );  // Access Violation happens here
    }

    image.UnlockBits(&source);

    return retval;
}
</code>```

答:
Here's one problem:

```<code>cv::Mat *retval = new cv::Mat(
    image.GetWidth(), image.GetHeight(), CV_8UC3
);
</code>```

The Mat constructor's first argument is rows, second is columns. So you should be doing this:

```<code>cv::Mat *retval = new cv::Mat(
    image.GetHeight(), image.GetWidth(), CV_8UC3
);
</code>```

That could cause an access violation.

Edit

Also, OpenCV images are by default BGR, not RGB. So if you get this working and then display the image with imshow, your blue and red values will be backward. You can fix this with the call cv::cvtColor(retval, retval, CV_RGB2BGR) before your return statement.

Body:
I'm trying to convert a GDIPlus::Bitmap into an openCV Mat object, but I'm running into problems with Access Violations, which means I'm not doing something right, but I've looked over the code over and over, and I think it should work.

Does anyone see an obvious problem?

cv::Mat ConvertToOpenCV(Gdiplus::Bitmap &image) {
    cv::Mat *retval = new cv::Mat(
        image.GetWidth(), image.GetHeight(), CV_8UC3
    );

    Gdiplus::BitmapData source;

    Gdiplus::Rect rect( 0, 0, image.GetWidth(), image.GetHeight() );
    Gdiplus::Status status =
        image.LockBits( &rect, Gdiplus::ImageLockModeRead, PixelFormat24bppRGB, &source );
    if ( status != Gdiplus::Ok ) {
        // Some error condition
        return retval; // No image copied
    }

    BYTE *destination = (BYTE *)retval->data;

    for ( int y = 0; y != source.Height; ++y ) {
        BYTE *src = (BYTE *) source.Scan0 + y * source.Stride;
        BYTE *dst = (BYTE *)(destination + y * retval->step);
        memcpy( dst, src, 3 * source.Width );  // Access Violation happens here
    }

    image.UnlockBits(&source);

    return retval;
}

Body:
Here's one problem:

cv::Mat *retval = new cv::Mat(
    image.GetWidth(), image.GetHeight(), CV_8UC3
);

The Mat constructor's first argument is rows, second is columns. So you should be doing this:

cv::Mat *retval = new cv::Mat(
    image.GetHeight(), image.GetWidth(), CV_8UC3
);

That could cause an access violation.

Edit

Also, OpenCV images are by default BGR, not RGB. So if you get this working and then display the image with imshow, your blue and red values will be backward. You can fix this with the call cv::cvtColor(retval, retval, CV_RGB2BGR) before your return statement.