问:
(XMLHTTP60) no longer returning required data
Help gratefully received on this one. I have some VBA running in Excel that inspects a series of webpages displaying betting odds for football matches and puts the odds into my spreadsheet. It has been working perfectly for months and has stopped working in the last few weeks. Here is a simplified version of the code I'm using:

```<code>Sub TestImport()

Dim http As New MSXML2.XMLHTTP60
Dim html As New MSHTML.HTMLDocument
Dim htmlEle1 As MSHTML.IHTMLElement
Dim columncounter As Integer
Dim rowccounter As Integer
Dim targetwebpage As String
Dim ColumnHeader As Variant

On Error GoTo ErrorStop

trowNum = 1

    targetwebpage = "https://www.oddschecker.com/football/english/premier-league"
        With http
            .Open "get", targetwebpage, False
            .send
        End With

Set table_data = html.getElementsByTagName("tr")

If table_data.Length = 0 Then GoTo SkipLeague

For Each trow In table_data

    For Each tcell In trow.Children

      If tcell.innerText <> "TIP" Then 'Ignore this
        tcellNum = tcellNum + 1
        Cells(trowNum, tcellNum) = tcell.innerText
      End If

    Next tcell

    Cells(trowNum, 1) = Worksheets("Leagues").Cells(j, 1)
    trowNum = trowNum + 1
    tcellNum = 1

Next trow

SkipLeague:

ErrorStop:

End Sub
</code>```

No data gets returned because [table_data] is always null. It's always null because there are no  tags in my variable, [html]. Instead, [html] seems to be simply this:

```<code>"<HEAD></HEAD>
<BODY>
<P> </P></BODY>"
</code>```

Why would [html] return this value when the actual webpage (https://www.oddschecker.com/football/english/premier-league) is much more complex when displayed in my browser? And why has this problem only started in the last few weeks?

I'd be grateful for any help on this.

答:
I did a quick test and had no issue.  Some page, like Google require the User-Agent to be sent, but not the oddschecker page.</p>
```<code>Sub TestURL()
    Debug.Print GetResult("https://www.oddschecker.com/football/english/premier-league")
End Sub

Function GetResult(url As String) As String
    Dim XMLHTTP As Object, ret As String
    Set XMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    XMLHTTP.Open "GET", url, False
    XMLHTTP.setRequestHeader "Content-Type", "text/xml"
    XMLHTTP.setRequestHeader "Cache-Control", "no-cache"
    XMLHTTP.setRequestHeader "Pragma", "no-cache"
    XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
    XMLHTTP.send
    ret = XMLHTTP.responseText
    GetResult = ret
End Function
</code>```

Body:
Help gratefully received on this one. I have some VBA running in Excel that inspects a series of webpages displaying betting odds for football matches and puts the odds into my spreadsheet. It has been working perfectly for months and has stopped working in the last few weeks. Here is a simplified version of the code I'm using:

Sub TestImport()

Dim http As New MSXML2.XMLHTTP60
Dim html As New MSHTML.HTMLDocument
Dim htmlEle1 As MSHTML.IHTMLElement
Dim columncounter As Integer
Dim rowccounter As Integer
Dim targetwebpage As String
Dim ColumnHeader As Variant

On Error GoTo ErrorStop

trowNum = 1

    targetwebpage = "https://www.oddschecker.com/football/english/premier-league"
        With http
            .Open "get", targetwebpage, False
            .send
        End With

Set table_data = html.getElementsByTagName("tr")

If table_data.Length = 0 Then GoTo SkipLeague

For Each trow In table_data

    For Each tcell In trow.Children

      If tcell.innerText <> "TIP" Then 'Ignore this
        tcellNum = tcellNum + 1
        Cells(trowNum, tcellNum) = tcell.innerText
      End If

    Next tcell

    Cells(trowNum, 1) = Worksheets("Leagues").Cells(j, 1)
    trowNum = trowNum + 1
    tcellNum = 1

Next trow

SkipLeague:

ErrorStop:

End Sub

No data gets returned because [table_data] is always null. It's always null because there are no  tags in my variable, [html]. Instead, [html] seems to be simply this:

"

"

Why would [html] return this value when the actual webpage (https://www.oddschecker.com/football/english/premier-league) is much more complex when displayed in my browser? And why has this problem only started in the last few weeks?

I'd be grateful for any help on this.

Body:
I did a quick test and had no issue.  Some page, like Google require the User-Agent to be sent, but not the oddschecker page.

Sub TestURL()
    Debug.Print GetResult("https://www.oddschecker.com/football/english/premier-league")
End Sub

Function GetResult(url As String) As String
    Dim XMLHTTP As Object, ret As String
    Set XMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    XMLHTTP.Open "GET", url, False
    XMLHTTP.setRequestHeader "Content-Type", "text/xml"
    XMLHTTP.setRequestHeader "Cache-Control", "no-cache"
    XMLHTTP.setRequestHeader "Pragma", "no-cache"
    XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
    XMLHTTP.send
    ret = XMLHTTP.responseText
    GetResult = ret
End Function


来源: stackexchange

问:
react autocomplete how to stop first call and complete the second
I have an autocomplete form that receives a list, I would like that when I type in the search field every time I insert a letter the previous call is canceled and continues with the new call, I have tried with throttling but nothing to do ... I am using react with mui how could I do?

this is my function:

```<code>const myFunction= throttle(350, false, (value) => {
  axios.get(url, {
    params: {
      q: value,
    }
  })
  .then((response) => {
    doSomething(response.data);
  })
})
</code>```

I would like to achieve this result

Thank you so much

答:
that's the diff between debounce and throttle

Try changing for debounce, you will complete at least one request in the bunch of events

ContentLicense: CC BY-SA 4.0

Body:
I have an autocomplete form that receives a list, I would like that when I type in the search field every time I insert a letter the previous call is canceled and continues with the new call, I have tried with throttling but nothing to do ... I am using react with mui how could I do?

this is my function:

const myFunction= throttle(350, false, (value) => {
  axios.get(url, {
    params: {
      q: value,
    }
  })
  .then((response) => {
    doSomething(response.data);
  })
})

I would like to achieve this result

Thank you so much


问:
Is it possible to set up two mosquitto brokers on the same machine with different access to them?
Is it possible to set up two brokers on the same machine with different access to them? Or one broker - one machine, the second - the second?</p>

答:
Yes - it is possible. You will want to point each instance at a different configuration files (-c / --config-file command line option) and ensure that the configuration files do not have listener's on the same the same port.

The different instances will be independent (so something with a connection to one broker will not receive any messages published to a second broker unless you establish a bridge between them).


问:
Custom SQL Query in Tableau produces incorrect output when same query in SSMS runs as expected
I built SQL query that works as expected when I execute it in Microsoft SQL Server Management Studio, however when I use same query in Tableau (Custom SQL query), some columns (where aggregation was performed) are showing incorrect output (always 0).

Issue is in the lines of code shown here. I guess @@ROWCOUNT could be an issue.

```<code>SUM(CASE WHEN a.LocationName = 'Home' THEN @@ROWCOUNT ELSE 0 END) AS CountHomeServices,
SUM(CASE WHEN a.LocationName = 'Office' THEN @@ROWCOUNT ELSE 0 END) AS CountOfficeServices
</code>```

Is there a way to make it work in Tableau?

答: Assuming you're just counting the rows with each LocationName, replace @@ROWCOUNT with 1.

Body:
I built SQL query that works as expected when I execute it in Microsoft SQL Server Management Studio, however when I use same query in Tableau (Custom SQL query), some columns (where aggregation was performed) are showing incorrect output (always 0).

Issue is in the lines of code shown here. I guess @@ROWCOUNT could be an issue.

SUM(CASE WHEN a.LocationName = 'Home' THEN @@ROWCOUNT ELSE 0 END) AS CountHomeServices,
SUM(CASE WHEN a.LocationName = 'Office' THEN @@ROWCOUNT ELSE 0 END) AS CountOfficeServices

Is there a way to make it work in Tableau?


问:
Ionic grid 2 columns where left column in fixed and right column is scrollable
I'm having trouble finding any documentation on how exactly this works. In it's simplest form I want to get the code below to have the left column be stationary (or possibly also scroll independently) and the right column to scroll. This is an Ionic 4 / Angular 11 app.</p>
```<code><ion-content>
<ion-grid>
  <ion-row>
    <ion-col size="6">

This column does not scroll

    </ion-col>
     <ion-col size="6">

This column does scroll when it exceeds screen height

    </ion-col>
  </ion-row>
</ion-grid>
</ion-content>
</code>```

答:
Something like this https://stackblitz.com/edit/ionic-angular-v5-3yiyi7?
In a nutshell, it's all in the css: play with overflow-y property and add see if you'd want scrollbar to show or not with display. Also, note the difference between browsers in css.

Body:
I'm having trouble finding any documentation on how exactly this works. In it's simplest form I want to get the code below to have the left column be stationary (or possibly also scroll independently) and the right column to scroll. This is an Ionic 4 / Angular 11 app.

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col size="6">

This column does not scroll

    </ion-col>
     <ion-col size="6">

This column does scroll when it exceeds screen height

    </ion-col>
  </ion-row>
</ion-grid>
</ion-content>


问:
Textfield with arial regular and arial bold does not work together in flashcs5?
I have two dynamic classic TextFields in a  MovieClip, one with Arial Regular embedded and the other with Arial Bold, but the second TextField is not showing the bold text. It shows regular text. Here is how I am doing it:

a busy cat http://cubixshade.com/textz/sample.jpg

I change the text of two fields using

```<code>mc.txt1.text="changed text90";

mc.txt2.text="changed text90";
</code>```

Both are shown in Arial Regular style.

答: I found that depending on the font, the bold version isn't a different font-face. To get bold you only need to use  tags around your html text that uses your regular font</p>

ContentLicense: CC BY-SA 3.0

Body:
I have two dynamic classic TextFields in a  MovieClip, one with Arial Regular embedded and the other with Arial Bold, but the second TextField is not showing the bold text. It shows regular text. Here is how I am doing it:

a busy cat http://cubixshade.com/textz/sample.jpg

I change the text of two fields using

mc.txt1.text="changed text90";

mc.txt2.text="changed text90";

Both are shown in Arial Regular style.


问:
Call a method from another class without initialization in java
I’m a bit confused by the code below. From my understanding, private ListElement<E> headis just the same thing as saying int head. If this is true, then one cannot call a method from an outside class without initializing it, so head.setPrev() won’t work before you say ListElment<E> head = new ListElment<>(). which contradicts the code below. I must have misunderstood something about java. Cloud someone points it out? Thanks in advance

```<code>public class DoublyLinkedList<E> {

private ListElement<E> head;
private ListElement<E> tail;

public DoublyLinkedList() {
    head = null;
    tail = null;
}

public void addToHead(E value) {
    ListElement<E> e = new ListElement<>(value);

    if (!isEmpty()) {
        e.setNext(head);
        head.setPrev(e);
    } else { // empty
        tail = e;
    }

    head = e;
}
</code>```

答:
You omitted the code for isEmpty().

Assuming a reasonable implementation, then if isEmpty() returns false, then it is guaranteed that head is not null, because there has to be at least one element in the list if it's not empty.

head is a reference to a ListElement object.  It starts out initialized to null.  On the very first call to addToHead() the call to isEmpty() returns true, so the else branch of the if-then-else executes.  The end result is that after that first call, both head and tail now refer to the element just created.

The "then" branch executes only if the list is not empty, in which case, by definition, head cannot be null.

Body:
I’m a bit confused by the code below. From my understanding, private ListElement<E> headis just the same thing as saying int head. If this is true, then one cannot call a method from an outside class without initializing it, so head.setPrev() won’t work before you say ListElment<E> head = new ListElment<>(). which contradicts the code below. I must have misunderstood something about java. Cloud someone points it out? Thanks in advance

public class DoublyLinkedList<E> {

private ListElement<E> head;
private ListElement<E> tail;

public DoublyLinkedList() {
    head = null;
    tail = null;
}

public void addToHead(E value) {
    ListElement<E> e = new ListElement<>(value);

    if (!isEmpty()) {
        e.setNext(head);
        head.setPrev(e);
    } else { // empty
        tail = e;
    }

    head = e;
}


问:
Deep Insert with web services
I need to insert headers and lines at the same time using the Business Central web services. The header gets inserted successfully but not the lines. (They just don't insert)

While looking online for this problem, I came across a few posts mentioning that Deep Inserts are only possible with the APIs.

I tried to find an article or a part of Microsoft's documentation that would mention this, but I can't seem to find anything. This makes me wonder whether it really is only possible with the APIs.

So my question is: Are the Deep Inserts really only possible using the Business Central APIs ?

答:
I had an experience in make a deep insert only using APIs, by simply publishing an API page (with the source table set to the header) having also a page-part for the lines.

I think this could be a good example on how to do it: https://www.kauffmann.nl/2020/07/01/deep-insert-with-business-central-apis-part-2/

Title: Deep Insert with web services


问:
Python: Read specific element from a matrix written in a file with string
I would like to read data from a matrix in a file, the problem is the data is float with string, however, I am interested only in reading the float element,
I tried with several options including pandas dataframe, however, I could not so I am kindly asking for help.

I am attaching the file as picture as I could not upload the file itself, and the code:

```<code>with open('data.dat', 'r') as f:
output_data = f.readlines()
element =  [(d+' ')[:d.find(':')].rstrip() for d in output_data] # trying to read only number after ":"
print(output_data[0])
 # EXPECTED OUTPUT is:
  0.162239678E+01
 # CURRENT OUTPUT IS: ['  data  1:           0.162239678E+01\n', '  data  2:           0.413951524E+01']

## data.dat    is as the following:
  data  1:           0.162239678E+01
  data  2:           0.413951524E+01
</code>```

答:
It seems like you have the correct approach, but somehow you're targeting the first part of each line instead of the actual number. The problem is this: [:d.find(':')], you want the other side of the string: [d.find(':'):]. Also, you'll be capturing the ":" character, so add 1 to the position. Then, use str.strip instead of str.rstrip to apply the function on both sides of the string. This is the resulting code (with some simplifications):

```<code>with open('data.dat', 'r') as f:
    output_data = f.readlines()
    elements =  [d[d.find(':')+1:].strip() for d in output_data]
    print(elements)
</code>```

Body:
I would like to read data from a matrix in a file, the problem is the data is float with string, however, I am interested only in reading the float element,
I tried with several options including pandas dataframe, however, I could not so I am kindly asking for help.

I am attaching the file as picture as I could not upload the file itself, and the code:

with open('data.dat', 'r') as f:
output_data = f.readlines()
element =  [(d+' ')[:d.find(':')].rstrip() for d in output_data] # trying to read only number after ":"
print(output_data[0])
 # EXPECTED OUTPUT is:
  0.162239678E+01
 # CURRENT OUTPUT IS: ['  data  1:           0.162239678E+01\n', '  data  2:           0.413951524E+01']

## data.dat    is as the following:
  data  1:           0.162239678E+01
  data  2:           0.413951524E+01

Body:
It seems like you have the correct approach, but somehow you're targeting the first part of each line instead of the actual number. The problem is this: [:d.find(':')], you want the other side of the string: [d.find(':'):]. Also, you'll be capturing the ":" character, so add 1 to the position. Then, use str.strip instead of str.rstrip to apply the function on both sides of the string. This is the resulting code (with some simplifications):

with open('data.dat', 'r') as f:
    output_data = f.readlines()
    elements =  [d[d.find(':')+1:].strip() for d in output_data]
    print(elements)


问:
Selenium and ChromeDriverManager doesn't downloads the latest version of ChromeDriver
I have an error:

```<code>Error: Type: <class 'selenium.common.exceptions.SessionNotCreatedException'>
Message: session not created: This version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path .....
</code>```

To get latest driver I'm using this code:

```<code>browser = webdriver.Chrome(ChromeDriverManager().install(),options=options)
</code>```

Why on my local machine and one of the VMs, it will get the latest (version 98...) and on one of the VM, it will get only version 96.

Is it something that need to be changed on VM to make it work correctly?

P.S. Two VMs are identical copies.

答:
If you are using Chrome version 98, download ChromeDriver 98.0.4758.80

https://chromedriver.chromium.org/downloads

Download Option 2.

Body:
I have an error:

Error: Type: <class 'selenium.common.exceptions.SessionNotCreatedException'>
Message: session not created: This version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path .....

To get latest driver I'm using this code:

browser = webdriver.Chrome(ChromeDriverManager().install(),options=options)

Why on my local machine and one of the VMs, it will get the latest (version 98...) and on one of the VM, it will get only version 96.

Is it something that need to be changed on VM to make it work correctly?

P.S. Two VMs are identical copies.


问:
Fix header in a table
I am developing a small page that is necessary to fix the header of a table, when the user scrolls, the header is still there. I wrote a small piece of code, a sample of my page, in jsfiddle and it isn't working and I don't know why. What am I doing wrong?

You can see what I have done so far here.

Follow this example

答:
Add the following to your stylesheet:</p>

```<code>.PersistentHeader{
      position:fixed;
 }
</code>```

Title: Fix header in a table

Body:
Add the following to your stylesheet:

.PersistentHeader{
      position:fixed;
 }


问:
Python oci sdk question regarding boot volume backup
How do we find boot volume backups of the particular instance using python oci package

list_boot_volume_backups function will return all the backups in the compartment.

ref: https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/BootVolumeBackup/ListBootVolumeBackups

if we need to pass source_boot_volume_backup_id then where do we find this value

we can use boot_volume_id but in that case as well ListBootVolumes function will list all the boot volumes in the compartment.

ref:  https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/BootVolume/ListBootVolumes

Thank you in advance!!

答:
You would have to utilize the ListBootVolumeAttachments API, you can filter by Instance OCID, boot volume OCID, or both. ref: https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/BootVolumeAttachment/ListBootVolumeAttachments

The above would return you the Boot Volume Attachment OCID which can then be used with the GetBootVolumeAttachment API to get details of the attachment between a boot volume and an instance.

ref: https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/BootVolumeAttachment/GetBootVolumeAttachment

Hope this helps solve your issue!


问:
How to find a common variable in a large number of databases using Stata
So I have a large number of databases (82) in Stata, that each contain around 1300 variables and several thousand observations. Some of these databases contain variables that give the mean or standard deviation of certain concepts. For example, a variable in such a dataset could be called "leverage_mean". Now, I want to know which datasets contain variables called concept_mean or concept_sd, without having to go through every dataset by hand.

I was thinking that maybe there is a way to loop through the databases looking for variables containing "mean" or "sd", unfortunately I have idea how to do this. I'm using R and Stata datafiles.

答:
The lookfor_all package (SSC) is there for that purpose:

```<code>cd "pathtodirectory"

lookfor_all leverage_mean
</code>```

Just make sure the file extensions are in lowercase(.dta) and not upper.

Body:
The lookfor_all package (SSC) is there for that purpose:

cd "pathtodirectory"

lookfor_all leverage_mean

Just make sure the file extensions are in lowercase(.dta) and not upper.


问:
Day/Night mode changes from fragment starts from the first fragment
I faced a problem at the time of day/night mode change from fragment that without recreate the parent activity the mode not change but I want to change the mode from fragment without move from the current fragment.</p>
```<code>public void setNightMode(Context target, boolean state){

    //UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);
    UiModeManager uiManager = (UiModeManager) getActivity().getSystemService(Context.UI_MODE_SERVICE);

    if (state) {
        //setTheme(R.style.DarkTheme);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            //setting up Night Mode...
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        }
        //uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        night_mode = false;
        //homeBinding.toolbar.setHeaderColour(HomeActivity.this, false);
    } else {
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
        }
        night_mode = true;
    }
}
</code>```

答:
for change to night mode :

```<code>delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
</code>```

and change to the light mode:

```<code>delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
</code>```

also for use this feature you must implement the androidX appcompat library

```<code>implementation 'androidx.appcompat:appcompat:1.4.0'
</code>```

Body:
I faced a problem at the time of day/night mode change from fragment that without recreate the parent activity the mode not change but I want to change the mode from fragment without move from the current fragment.

public void setNightMode(Context target, boolean state){

    //UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);
    UiModeManager uiManager = (UiModeManager) getActivity().getSystemService(Context.UI_MODE_SERVICE);

    if (state) {
        //setTheme(R.style.DarkTheme);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            //setting up Night Mode...
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        }
        //uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        night_mode = false;
        //homeBinding.toolbar.setHeaderColour(HomeActivity.this, false);
    } else {
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
        }
        night_mode = true;
    }
}

Body:
for change to night mode :

delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES

and change to the light mode:

delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO

also for use this feature you must implement the androidX appcompat library

implementation 'androidx.appcompat:appcompat:1.4.0'


问:
Check if number is prime number
I would just like to ask if this is a correct way of checking if number is prime or not? because I read that 0 and 1 are NOT a prime number.    </p>

```<code>int num1;

Console.WriteLine("Accept number:");
num1 = Convert.ToInt32(Console.ReadLine());
if (num1 == 0 || num1 == 1)
{
    Console.WriteLine(num1 + " is not prime number");
    Console.ReadLine();
}
else
{
    for (int a = 2; a <= num1 / 2; a++)
    {
        if (num1 % a == 0)
        {
            Console.WriteLine(num1 + " is not prime number");
            return;
        }

    }
    Console.WriteLine(num1 + " is a prime number");
    Console.ReadLine();
}
</code>```

答:
Here's one with an explenation:</p>
```<code>// Checks whether the provided number is a prime number.
  public static bool IsPrime(int num) {
    if (num <= 1)
      return false; // 1 or less is never prime.
    if (num==2)
      return true; // 2 is always a prime number.

    // Trial Division: Tries to divide number with all of the numbers in range 1-to-square-root(number).
    // If the number did not divide with the numbers in this range it will not divide with any other number therefore it's prime.
    int bound = (int)Math.Floor(Math.Sqrt(num));

    for (int i = 2; i<=bound; i ++) {
      if (num % i == 0)
        return false;
    }

    return true;
  }
</code>```

Title: Check if number is prime number

Body:
I would just like to ask if this is a correct way of checking if number is prime or not? because I read that 0 and 1 are NOT a prime number.

int num1;

Console.WriteLine("Accept number:");
num1 = Convert.ToInt32(Console.ReadLine());
if (num1 == 0 || num1 == 1)
{
    Console.WriteLine(num1 + " is not prime number");
    Console.ReadLine();
}
else
{
    for (int a = 2; a <= num1 / 2; a++)
    {
        if (num1 % a == 0)
        {
            Console.WriteLine(num1 + " is not prime number");
            return;
        }

    }
    Console.WriteLine(num1 + " is a prime number");
    Console.ReadLine();
}

Body:
Here's one with an explenation:

// Checks whether the provided number is a prime number.
  public static bool IsPrime(int num) {
    if (num <= 1)
      return false; // 1 or less is never prime.
    if (num==2)
      return true; // 2 is always a prime number.

    // Trial Division: Tries to divide number with all of the numbers in range 1-to-square-root(number).
    // If the number did not divide with the numbers in this range it will not divide with any other number therefore it's prime.
    int bound = (int)Math.Floor(Math.Sqrt(num));

    for (int i = 2; i<=bound; i ++) {
      if (num % i == 0)
        return false;
    }

    return true;
  }


问:
SVG pie chart (donut) slice selection via javascript, html, css
I have my css hover working correctly and I can hard code the css class and get the html to use .active but I cannot get my pie slices to switch to active state upon click.  Additionally, after I get this working, I want to be able to select multiple pie slices and capture the id's.  I'm not that great with javascript so... be gentle with me :)
page header

```<code><!DOCTYPE html>
<html >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/css/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>

<style>

</style>
<script language="javascript" type="text/javascript">

/* this is for selecting and deselecting svg pie pieces
$('group_path').click(function() {
  $(this).addClass('active').siblings().removeClass('active');
}); */

/* This is the javascript to select pie pieces */
// Get the container element
var group_pathContainer = document.getElementById("4");
var group_paths = group_pathContainer.querySelectorAll(".group_path");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < group_paths.length; i++) {
  group_paths[i].addEventListener("click", function(e) {
    var current = e.currentTarget;
    // toggle active class to the current/clicked button
    current.classList.toggle('active');
    getActive();
  });
}

// list all active pie segemnts
function getActive(){
  let actives = document.querySelectorAll('.active');
  let idArray = [];
  actives.forEach(function(el,i){
    let id = el.id;
    idArray.push(id)
  })
  console.log(idArray)
}

</script>
</code>```

svg

```<code> <svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)';>
                <g id="4" >
                      <g id="4.01" class="active" fill='rgb(84,161,229)' >
                      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
                      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
                      </g>
                       <g id="4.02" class="active" fill='rgb(242,162,84)'>
                      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
                      </g>
                       <g id="4.03" class="group_path" fill='rgb(237,110,133)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
                    </g>
                       <g id="4.04" class="group_path" fill='rgb(173,205,225)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
                    </g>
                       <g id="4.05" class="group_path" fill='rgb(187,221,147)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.915241 0.402907 A 1 1 0 0 1 -0.946085 0.323917 L 0 0 '></path>
                    </g>
                       <g id="4.06" class="group_path" fill='rgb(238,158,155)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.946085 0.323917 A 1 1 0 0 1 -0.978581 -0.205863 L 0 0 '></path>
                    </g>
                       <g id="4.07" class="group_path active" fill='rgb(84,161,229)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.978581 -0.205863 A 1 1 0 0 1 -0.879316 -0.476238 L 0 0 '></path>
                    </g>
                       <g id="4.08" class="group_path" fill='rgb(108,190,191)'>
                   <path stroke='white' stroke-width='.0125px' d='M -0.879316 -0.476238 A 1 1 0 0 1 -0.527846 -0.849340 L 0 0 '></path>
                   </g>
                       <g id="4.09" class="group_path" fill='rgb(242,162,84)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.527846 -0.849340 A 1 1 0 0 1 0.056518 -0.998402 L 0 0 '></path>
                    </g>
                       <g id="4.10" class="group_path" fill='rgb(237,110,133)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.056518 -0.998402 A 1 1 0 0 1 0.543760 -0.839241 L 0 0 '></path>
                    </g>
                       <g id="4.11" class="group_path" fill='rgb(173,205,225)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.543760 -0.839241 A 1 1 0 0 1 0.711535 -0.702650 L 0 0 '></path>
                    </g>
                       <g id="4.12" class="group_path" fill='rgb(187,221,147)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.711535 -0.702650 A 1 1 0 0 1 0.724653 -0.689114 L 0 0 '></path>
                    </g>
                       <g id="4.13" class="group_path" fill='rgb(42,228,229)'>
                    <path stroke='white' stroke-width='.00625px' d='M 0.724653 -0.689114 A 1 1 0 0 1 1.000000 -0.000000 L 0 0 '></path>
                    </g>
                    <circle fill='#fff' cx='0' cy='0' r='0.80'/>
                </g>
</code>```

css

```<code>.group_path:hover{
 /* fill: purple; */
  transform: scale(.95, .95);
}
.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}
</code>```

答:
Both examples that @herrstrietzel provided work.

I had my javascript tags in the wrong location (in the header).  Once I moved them to just above  near the bottom of the page everything worked perfect!

Body:
I have my css hover working correctly and I can hard code the css class and get the html to use .active but I cannot get my pie slices to switch to active state upon click.  Additionally, after I get this working, I want to be able to select multiple pie slices and capture the id's.  I'm not that great with javascript so... be gentle with me :)
page header

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/css/style.css" rel="stylesheet" type="text/css" />

svg

 <svg viewBox='-1 -1 2 2' style='transform: scale(1.0); rotate(-90deg)';>
                <g id="4" >
                      <g id="4.01" class="active" fill='rgb(84,161,229)' >
                      <path stroke='white' stroke-width='.0125px' d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 '></path>
                      <text d='M 1.000000 0.000000 A 1 1 0 0 1 0.873262 0.487250 L 0 0 ' fill="none" x="0.9">Project</text>
                      </g>
                       <g id="4.02" class="active" fill='rgb(242,162,84)'>
                      <path  stroke='white' stroke-width='.0125px' d='M 0.873262 0.487250 A 1 1 0 0 1 -0.147119 0.989119 L 0 0 '></path>
                      </g>
                       <g id="4.03" class="group_path" fill='rgb(237,110,133)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.147119 0.989119 A 1 1 0 0 1 -0.689114 0.724653 L 0 0 '></path>
                    </g>
                       <g id="4.04" class="group_path" fill='rgb(173,205,225)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.689114 0.724653 A 1 1 0 0 1 -0.915241 0.402907 L 0 0 '></path>
                    </g>
                       <g id="4.05" class="group_path" fill='rgb(187,221,147)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.915241 0.402907 A 1 1 0 0 1 -0.946085 0.323917 L 0 0 '></path>
                    </g>
                       <g id="4.06" class="group_path" fill='rgb(238,158,155)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.946085 0.323917 A 1 1 0 0 1 -0.978581 -0.205863 L 0 0 '></path>
                    </g>
                       <g id="4.07" class="group_path active" fill='rgb(84,161,229)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.978581 -0.205863 A 1 1 0 0 1 -0.879316 -0.476238 L 0 0 '></path>
                    </g>
                       <g id="4.08" class="group_path" fill='rgb(108,190,191)'>
                   <path stroke='white' stroke-width='.0125px' d='M -0.879316 -0.476238 A 1 1 0 0 1 -0.527846 -0.849340 L 0 0 '></path>
                   </g>
                       <g id="4.09" class="group_path" fill='rgb(242,162,84)' >
                    <path stroke='white' stroke-width='.0125px' d='M -0.527846 -0.849340 A 1 1 0 0 1 0.056518 -0.998402 L 0 0 '></path>
                    </g>
                       <g id="4.10" class="group_path" fill='rgb(237,110,133)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.056518 -0.998402 A 1 1 0 0 1 0.543760 -0.839241 L 0 0 '></path>
                    </g>
                       <g id="4.11" class="group_path" fill='rgb(173,205,225)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.543760 -0.839241 A 1 1 0 0 1 0.711535 -0.702650 L 0 0 '></path>
                    </g>
                       <g id="4.12" class="group_path" fill='rgb(187,221,147)'>
                    <path stroke='white' stroke-width='.0125px' d='M 0.711535 -0.702650 A 1 1 0 0 1 0.724653 -0.689114 L 0 0 '></path>
                    </g>
                       <g id="4.13" class="group_path" fill='rgb(42,228,229)'>
                    <path stroke='white' stroke-width='.00625px' d='M 0.724653 -0.689114 A 1 1 0 0 1 1.000000 -0.000000 L 0 0 '></path>
                    </g>
                    <circle fill='#fff' cx='0' cy='0' r='0.80'/>
                </g>

css

.group_path:hover{
 /* fill: purple; */
  transform: scale(.95, .95);
}
.group_path.active {
  fill: purple;
  transform: scale(.92, .92);
}

Body:
Both examples that @herrstrietzel provided work.

I had my javascript tags in the wrong location (in the header).  Once I moved them to just above </body> near the bottom of the page everything worked perfect!


问:
React native can't scroll when using TouchableWithoutFeedback to dismiss keyboard
I am using the follow code to dismiss my keyboard when I click outside of the text box. It works however I have different issue where I can't scroll my flatlist components. I also have issue with my scrollview no longer working. how can I fix this</p>
```<code><TouchableWithoutFeedback onPress={Keyboard.dismiss}
                          accessible={false}>
     <ScrollView style={{flex: 1}}>
         ...Rest of the Application Code...
     </ScrollView>
</TouchableWithoutFeedback>
</code>```

答:
based on https://reactnative.dev/docs/view you can wrap your ScrollView inside <View onStartShouldSetResponder={() => true}>

<TouchableWithoutFeedback
 onPress={Keyboard.dismiss}
 accessible={false}
>
 <View onStartShouldSetResponder={() => true}>
     <ScrollView style={{flex: 1}}>
         ...Rest of the Application Code...
     </ScrollView>
 </View>
</TouchableWithoutFeedback>
```

Body:
I am using the follow code to dismiss my keyboard when I click outside of the text box. It works however I have different issue where I can't scroll my flatlist components. I also have issue with my scrollview no longer working. how can I fix this

<TouchableWithoutFeedback onPress={Keyboard.dismiss}
                          accessible={false}>
     <ScrollView style={{flex: 1}}>
         ...Rest of the Application Code...
     </ScrollView>
</TouchableWithoutFeedback>


问:
Set Preceding and Succeeding rows
I want all the values in column values prior to string "%" should be flagged as "YES". Else "NO". It should be checked by each unique values of column Id.

```<code>df=data.frame('Id'=c(101,101,101,101,102,102,102,102),
              'values'=c('a','%','a','c','a','d','%','c'))
</code>```

All the preceding rows should be flagged as "YES". For example, In Id = 102, YES should be appeared against values "a", "d".

答:
With tidyverse, we can use str_detect with lead to determine if % is the next value, and if so, then return 1 and if not, NA. Then, we can group by Id and use fill to add 1 to the previous rows. Then, we can convert to YES and NO.

```<code>library(tidyverse)

df %>%
  mutate(flag = ifelse(str_detect(lead(values), "%"), 1, NA)) %>%
  group_by(Id) %>%
  fill(flag, .direction = "up") %>%
  mutate(flag = ifelse(is.na(flag), "NO", "YES"))

     Id values flag
  <dbl> <chr>  <chr>
1   101 a      YES
2   101 %      NO
3   101 a      NO
4   101 c      NO
5   102 a      YES
6   102 d      YES
7   102 %      NO
8   102 c      NO
</code>```

Title: Set Preceding and Succeeding rows

Body:
I want all the values in column values prior to string "%" should be flagged as "YES". Else "NO". It should be checked by each unique values of column Id.

df=data.frame('Id'=c(101,101,101,101,102,102,102,102),
              'values'=c('a','%','a','c','a','d','%','c'))

All the preceding rows should be flagged as "YES". For example, In Id = 102, YES should be appeared against values "a", "d".

Body:
With tidyverse, we can use str_detect with lead to determine if % is the next value, and if so, then return 1 and if not, NA. Then, we can group by Id and use fill to add 1 to the previous rows. Then, we can convert to YES and NO.

library(tidyverse)

df %>%
  mutate(flag = ifelse(str_detect(lead(values), "%"), 1, NA)) %>%
  group_by(Id) %>%
  fill(flag, .direction = "up") %>%
  mutate(flag = ifelse(is.na(flag), "NO", "YES"))

     Id values flag
  <dbl> <chr>  <chr>
1   101 a      YES
2   101 %      NO
3   101 a      NO
4   101 c      NO
5   102 a      YES
6   102 d      YES
7   102 %      NO
8   102 c      NO


问:
Delphi: Store data in somekind of structure
For a simulation program I'm working in Delphi 2010. The simulation isn't a problem but I need to use large collection of data which gives a problem. The data is available in excel sheets, so there is no need to edit this data in Delphi, but collecting this data from the excel sheets takes around 10min. This isn't a problem as long as you don't need to collect the data  every time the program runs. So I made a program which collects all the data makes it visible, not problems here,and then store it. However I can't store it to a "Delphi format" , without losing the structure, so it can be loaded in a few seconds.

I'm not that experienced in Delphi and I searched a long time for the solution but couldn't understand what was best. I think my way of structuring the data is wrong but it was simple and worked. However if there are better ways of storing the data please say so, but remember that I need some more explanation than just use 'a xml file', 'generict, or 'Ttreeview'. (have read it but wasn't able to use it).

The data is for: I made this product, The next product I make is this, so do I need to clean? True or false.

The data is stores as a class(TObject) with Productnumber (integer) and a List which contains all products that could be made next.This list contains another class(TObject) with an Productnumber (integer) and a do I need to clean(boolean). I want to save this structure in a file, without losing the data and read it back to the same structure.

I hope someone could help. Thank you in advance.

Update: The code to provide a little more information (modified to English)

```<code>Clean_from = class(TObject)
public
  myfromNumber      : Integer;
  mylist            : TList;
published
  constructor Create;
End

Clean_To = class(TObject)
public
  myToNumber        : Integer;
  Clean             : Boolean;
End;

constructor Clean_from.Create;
begin
  inherited Create;
  myList := Tlist.Create;
end;

For i = 0 to 100 do
begin
  From:= Clean_from.create;
  for j := 0 to 10 do
  begin
    To := Clean_To.create;
    To.clean := true or false;
    From.myList.add(To);
  end;
  GlobalList.add(from);
end;
</code>```

And now I want to save the global list with all the content so I could load it with the same structure.

答:
What you need is the so-called "serialization" mechanism.

1. The standard way

1.1 SaveToStream

In Delphi, we usually implement a SaveToStream method, which will save the content of each object in a destination TStream (either a TFileStream or a TMemoryStream).

You'll have to write the serialization by hand.

1.2 DFM-like streaming

See TWriter / TReader classes.

If you define your data in published properties, you are able to serialize them using those standard Delphi classes.

For some methods able to serialize any TCollection to and from JSON content, see this blog article.

2. The RTTI

See for instance this SO question.

In particular, the new enhanced RTTI (available since Delphi 2010) opens new opportunities to serialization.

3. Use records instead of classes

If each item does not store a lot of content (some integer/boolean), it may make sense to use records instead of objects. For speed and memory consumption/fragmentation, it may be worth it.

Here is some wrapper able to serialize any dynamic array, even containing nested records or dynamic arrays.

4. Use a database engine

Perhaps the better approach is not to have your data stuck in a non-evolving binary form, proprietary to your application. If you want to add a property, you'll have to manage it by hand. Or if you want to access your data from other applications, it may be difficult.

There are a lot of database solutions around - instead of using an external database (like MS SQL, FireBird or Oracle), it could be a good idea to embed the database inside your application (much easier to install). Worth mentioning SQLite which has a lot of wrappers, including our version (which will allow you to change to any other database if you want to use MS SQL or Oracle instead).

You have other solutions around - see this SO question - and if you need performance, take a look at our Big Table library.

Body:
For a simulation program I'm working in Delphi 2010. The simulation isn't a problem but I need to use large collection of data which gives a problem. The data is available in excel sheets, so there is no need to edit this data in Delphi, but collecting this data from the excel sheets takes around 10min. This isn't a problem as long as you don't need to collect the data  every time the program runs. So I made a program which collects all the data makes it visible, not problems here,and then store it. However I can't store it to a "Delphi format" , without losing the structure, so it can be loaded in a few seconds.

I'm not that experienced in Delphi and I searched a long time for the solution but couldn't understand what was best. I think my way of structuring the data is wrong but it was simple and worked. However if there are better ways of storing the data please say so, but remember that I need some more explanation than just use 'a xml file', 'generict, or 'Ttreeview'. (have read it but wasn't able to use it).

The data is for: I made this product, The next product I make is this, so do I need to clean? True or false.

The data is stores as a class(TObject) with Productnumber (integer) and a List which contains all products that could be made next.This list contains another class(TObject) with an Productnumber (integer) and a do I need to clean(boolean). I want to save this structure in a file, without losing the data and read it back to the same structure.

I hope someone could help. Thank you in advance.

Update: The code to provide a little more information (modified to English)

Clean_from = class(TObject)
public
  myfromNumber      : Integer;
  mylist            : TList;
published
  constructor Create;
End

Clean_To = class(TObject)
public
  myToNumber        : Integer;
  Clean             : Boolean;
End;

constructor Clean_from.Create;
begin
  inherited Create;
  myList := Tlist.Create;
end;

For i = 0 to 100 do
begin
  From:= Clean_from.create;
  for j := 0 to 10 do
  begin
    To := Clean_To.create;
    To.clean := true or false;
    From.myList.add(To);
  end;
  GlobalList.add(from);
end;

And now I want to save the global list with all the content so I could load it with the same structure.


答:
With dplyr you can use lead in conjunction with a vector of values YES and NO. This assumes you only have one % per group. It does not search for last occurrence of %.

```<code>library(dplyr)

df %>%
  group_by(Id) %>%
  mutate(flag=values=="%", flag=c("YES", "NO")[cumsum(flag)+1]) %>%
  ungroup()
# A tibble: 8 × 3
     Id values flag
  <dbl> <chr>  <chr>
1   101 a      YES
2   101 %      NO
3   101 a      NO
4   101 c      NO
5   102 a      YES
6   102 d      YES
7   102 %      NO
8   102 c      NO
</code>```

Title: Set Preceding and Succeeding rows

Body:
With dplyr you can use lead in conjunction with a vector of values YES and NO. This assumes you only have one % per group. It does not search for last occurrence of %.

library(dplyr)

df %>%
  group_by(Id) %>%
  mutate(flag=values=="%", flag=c("YES", "NO")[cumsum(flag)+1]) %>%
  ungroup()
# A tibble: 8 × 3
     Id values flag
  <dbl> <chr>  <chr>
1   101 a      YES
2   101 %      NO
3   101 a      NO
4   101 c      NO
5   102 a      YES
6   102 d      YES
7   102 %      NO
8   102 c      NO


问:
Restrict list for table - Flutter
I want to limit the number of rows in the table, because I get about 40 rows from the API, and I need to make 5 rows. Tell me, what method should be applied in List.generate to show only the first 5 elements from the list? Thanks in advance.

DataTable

```<code>child: FutureBuilder<List<BlockModel>>(
              future: futureBlock,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return DataTable(
                      columns: const [
                        DataColumn(label: Text('Height')),
                        DataColumn(label: Text('Hash')),
                        DataColumn(label: Text('Time')),
                      ],
                      rows: List.generate(snapshot.data!.length, (index) {
                        return DataRow(cells: [
                          DataCell(Text('${snapshot.data![index].height}')),
                          DataCell(Text(snapshot.data![index].hash)),
                          DataCell(Text('${snapshot.data![index].time}')),
                        ]);
                      })
                      );
                } else {
</code>```

答: The first parameter of List.generate is the length. You currently wrote snapshot.data!.length, if you want the first 5, just put 5 there.

Title: Restrict list for table - Flutter

Body:
I want to limit the number of rows in the table, because I get about 40 rows from the API, and I need to make 5 rows. Tell me, what method should be applied in List.generate to show only the first 5 elements from the list? Thanks in advance.

DataTable

child: FutureBuilder<List<BlockModel>>(
              future: futureBlock,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return DataTable(
                      columns: const [
                        DataColumn(label: Text('Height')),
                        DataColumn(label: Text('Hash')),
                        DataColumn(label: Text('Time')),
                      ],
                      rows: List.generate(snapshot.data!.length, (index) {
                        return DataRow(cells: [
                          DataCell(Text('${snapshot.data![index].height}')),
                          DataCell(Text(snapshot.data![index].hash)),
                          DataCell(Text('${snapshot.data![index].time}')),
                        ]);
                      })
                      );
                } else {


问:
Cookie problem with knockoutjs and ASP.NET MVC application on .NET 4.6.1
A few days ago, my test environment does not work as expected, because my cookie LanguageIdCookie which is updated when I change the language in my dropdown list, stopped working, and on change of any language it has default value 1.

Error in my console that I could see in Edge explorer:

Cookies marked with SameSite=None must also be marked with Secure to allow setting them in a cross-site context. This behavior protects user data from being sent over an insecure connection.

Resolve this issue by updating the attributes of the cookie:

Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts. Note that only cookies sent over HTTPS may use the Secure attribute.

Specify SameSite=Strict or SameSite=Lax if the cookie should not be set by cross-site requests.

I would like to stress out that my website works perfectly fine in Firefox.

Application does not updating cookie value in Chrome and Edge.

I think everything is fine with my code/db (since it works ok in firefox), so can you please tell me what I need to do in my web.config file or to put something in the part in my code where I setup my cookie:

```<code>public int CurrentLanguageId
{
    get
    {
        if (HttpContext.Current != null &&
            HttpContext.Current.Request != null &&
            HttpContext.Current.Request.Cookies != null)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["LanguageIdCookie"];
            if (cookie != null)
                return int.Parse(cookie.Value);
        }

       return 1;
    }
    set
    {
        if (HttpContext.Current != null &&
                    HttpContext.Current.Request != null &&
                    HttpContext.Current.Response != null &&
                    HttpContext.Current.Request.Cookies != null)
        {

            HttpCookie cookie = HttpContext.Current.Request.Cookies["LanguageIdCookie"];
            if (cookie == null)
            {
                cookie = new HttpCookie("LanguageIdCookie");
            }

            cookie.Value = value.ToString();
            cookie.Expires = DateTime.UtcNow.AddDays(10);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
</code>```

I tried to put this in my web.config, but still I don't get updating the value to cookie:

```<code><system.web>
    ...
    <httpCookies sameSite="Strict"/>
</system.web>
</code>```

答:
Interestingly, it seems that:

Microsoft does not support .NET versions lower that 4.7.2 for writing
the same-site cookie attribute.

...and the reasons listed are:

We have not found a reliable way to:

Ensure the attribute is written correctly based on browser version.

Intercept and adjust authentication and session cookies on older
framework versions.

This information comes from the following MS Docs page:
Work with SameSite cookies in ASP.NET under the heading .NET versions earlier than 4.7.2.

You may be able to get the result you expect, with your current source code, across the various browsers by using .NET 4.7.2 or higher.

Body:
A few days ago, my test environment does not work as expected, because my cookie LanguageIdCookie which is updated when I change the language in my dropdown list, stopped working, and on change of any language it has default value 1.

Error in my console that I could see in Edge explorer:

Cookies marked with SameSite=None must also be marked with Secure to allow setting them in a cross-site context. This behavior protects user data from being sent over an insecure connection.

Resolve this issue by updating the attributes of the cookie:

Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts. Note that only cookies sent over HTTPS may use the Secure attribute.

Specify SameSite=Strict or SameSite=Lax if the cookie should not be set by cross-site requests.

I would like to stress out that my website works perfectly fine in Firefox.

Application does not updating cookie value in Chrome and Edge.

I think everything is fine with my code/db (since it works ok in firefox), so can you please tell me what I need to do in my web.config file or to put something in the part in my code where I setup my cookie:

public int CurrentLanguageId
{
    get
    {
        if (HttpContext.Current != null &&
            HttpContext.Current.Request != null &&
            HttpContext.Current.Request.Cookies != null)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["LanguageIdCookie"];
            if (cookie != null)
                return int.Parse(cookie.Value);
        }

       return 1;
    }
    set
    {
        if (HttpContext.Current != null &&
                    HttpContext.Current.Request != null &&
                    HttpContext.Current.Response != null &&
                    HttpContext.Current.Request.Cookies != null)
        {

            HttpCookie cookie = HttpContext.Current.Request.Cookies["LanguageIdCookie"];
            if (cookie == null)
            {
                cookie = new HttpCookie("LanguageIdCookie");
            }

            cookie.Value = value.ToString();
            cookie.Expires = DateTime.UtcNow.AddDays(10);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}

I tried to put this in my web.config, but still I don't get updating the value to cookie:

<system.web>
    ...
    <httpCookies sameSite="Strict"/>
</system.web>


问:
Bug in SAXON? It generates two adjacent text nodes for a leaf element
On the xml-dev list Michael Kay wrote:

In the XDM model the content of the Test element
is a single text node. XDM does not allow two
adjacent text nodes.

I believe SAXON uses the XDM model.

Consider this leaf element:

```<code><Test>
    abc<!-- aaa -->def
</Test>
</code>```

I ran SAXON with this XSLT program:

```<code><xsl:template match="Test">
    <xsl:message>count = <xsl:value-of select="count(text())"/></xsl:message>
</xsl:template>
</code>```

The output is:

```<code>count = 2
</code>```

That is not correct as it says the leaf element contains two adjacent text nodes, which clearly contradicts what Michael said on the xml-dev list. Do you agree?

答:
Where do you test that these two text nodes are adjacent? The Test element in the XDM has three child nodes, the first a text node, the second a comment node, the third another text node. So count(text()) is 2.

Once you had count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]]) giving more than 0 there would be a wrong representation in the XDM.

It is possible with Saxon-JS and a JavaScript created DOM tree where you are able to create two separate text child nodes:

const doc1 = new DOMParser().parseFromString('<root/>', 'application/xml');
doc1.documentElement.appendChild(doc1.createTextNode('Text child 1.'));
doc1.documentElement.appendChild(doc1.createTextNode('Text child 2.'));
console.log(doc1.documentElement.childNodes.length);

var result = SaxonJS.XPath.evaluate(`/*/count(text())`, doc1);

console.log(result);

var result2 = SaxonJS.XPath.evaluate(`/*/count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]])`, doc1);

console.log(result2);

doc1.normalize();

result = SaxonJS.XPath.evaluate(`/*/count(text())`, doc1);

console.log(result);

result2 = SaxonJS.XPath.evaluate(`/*/count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]])`, doc1);

console.log(result2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.saxonica.com/saxon-js/documentation2/SaxonJS/SaxonJS2.rt.js"></script></code>```

But the normalize call on the document fixes that problem.

Body:
On the xml-dev list Michael Kay wrote:

In the XDM model the content of the Test element
is a single text node. XDM does not allow two
adjacent text nodes.

I believe SAXON uses the XDM model.

Consider this leaf element:

<Test>
    abcdef
</Test>

I ran SAXON with this XSLT program:

<xsl:template match="Test">
    <xsl:message>count = <xsl:value-of select="count(text())"/></xsl:message>
</xsl:template>

The output is:

count = 2

That is not correct as it says the leaf element contains two adjacent text nodes, which clearly contradicts what Michael said on the xml-dev list. Do you agree?

Body:
Where do you test that these two text nodes are adjacent? The Test element in the XDM has three child nodes, the first a text node, the second a comment node, the third another text node. So count(text()) is 2.

Once you had count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]]) giving more than 0 there would be a wrong representation in the XDM.

It is possible with Saxon-JS and a JavaScript created DOM tree where you are able to create two separate text child nodes:

const doc1 = new DOMParser().parseFromString('<root/>', 'application/xml');
doc1.documentElement.appendChild(doc1.createTextNode('Text child 1.'));
doc1.documentElement.appendChild(doc1.createTextNode('Text child 2.'));
console.log(doc1.documentElement.childNodes.length);

var result = SaxonJS.XPath.evaluate(`/*/count(text())`, doc1);

console.log(result);

var result2 = SaxonJS.XPath.evaluate(`/*/count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]])`, doc1);

console.log(result2);

doc1.normalize();

result = SaxonJS.XPath.evaluate(`/*/count(text())`, doc1);

console.log(result);

result2 = SaxonJS.XPath.evaluate(`/*/count(text()[following-sibling::node()[1][self::text()]|preceding-sibling::node()[1][self::text()]])`, doc1);

console.log(result2);

<script src="https://www.saxonica.com/saxon-js/documentation2/SaxonJS/SaxonJS2.rt.js"></script>

But the normalize call on the document fixes that problem.


问:
How to calculate the distance vector from texel to the closest triangle edge to be saved in a FBO texture
I have a triangle which I pass through a vertex and fragment shader. I want to draw per texel a correction vector u (encoded in r and b channel) that points onto the closest edge (or even one pixel further) in the coordinate space of the vertices (not texture coordinates): u is the distance between the texel (center?) and the edge.

This texture is later used as a look up table for particles to calculate a reaction. I will use u for a position correction and determining the reflection vector. This already works for hardcoded values. The texel depending u is the last piece. The shader must be OpenGL ES friendly.

For each vertex v which I pass to the vertex shader I (if it helps) could also pass the normal of each connected edge and the center of the triangle.

Any idea how this can be done?

答:
A signed distance from a point P to a segment (A,B) is given by:

```<code>d = area(A, B, P) / length(B - A)
</code>```

where

```<code>area(A, B, C) = (B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x)
</code>```

Thus the distance you're looking for is given by:

```<code>dist0 = area(P, B, C) / length(C - B)
dist1 = area(A, P, C) / length(A - C)
dist2 = area(A, B, P) / length(B - A)
minimum distance = min(dist0, dist1, dist2)
</code>```

The remaining question is how to map this into the GPU pipeline.

One way is to calculate vec3 dist at each vertex of a triangle, then let OpenGL interpolate it across:

```<code>dist at A = vec3( area(A, B, C)/length(C - B), 0, 0 )
dist at B = vec3( 0, area(A, B, C)/length(A - C), 0 )
dist at C = vec3( 0, 0, area(A, B, C)/length(B - A) )
</code>```

Then in the fragment shader you only need to calculate the minimum of the interpolated dist components:

```<code>in vec3 dist; // interpolated from the above
minimum distance = min(dist.x, min(dist.y, dist.z))
</code>```

Alternatively, if you already have the barycentric coordinates available (e.g. through the NV_fragment_shader_barycentric extension), you can piggyback on that. Notice that the barycentric coordinates formula is identical to the above, up to the scaling factors:

```<code>bary0 = area(P, B, C) / area(A, B, C)
bary1 = area(A, P, C) / area(A, B, C)
bary2 = area(A, B, P) / area(A, B, C)
</code>```

Thus, if bary is already available, we only need to scale it by:

```<code>dist0 = bary0 * area(A, B, C) / length(C - B)
dist1 = bary1 * area(A, B, C) / length(A - C)
dist2 = bary2 * area(A, B, C) / length(B - A)
</code>```

Since the scaling factors are constant across the triangle, this can shave off a few FLOPs.

EDIT: I missed that you asked for the actual vector rather than just the distance. The concept remains the same though: you'll need to pass either the normals or the vertices into the shader and based on the computed distances (using either of the above methods), select the normal of the closest edge, scale, and return it. Let's say that n0, n1, n2 are the normals opposite to vertices A, B, C correspondingly; then you'd do the following in the fragment shader:

```<code>in vec3 dist; // interpolated from the above
in vec2 n0, n1, n2; // normals
...

vec2 result;
if(dist.x < min(dist.y, dist.z))
    result = dist.x*n0;
else if(dist.y < dist.z)
    result = dist.y*n1;
else
    result = dist.z*n2;
</code>```

Body:
A signed distance from a point P to a segment (A,B) is given by:

d = area(A, B, P) / length(B - A)

where

area(A, B, C) = (B.x - A.x)*(C.y - A.y) - (B.y - A.y)*(C.x - A.x)

Thus the distance you're looking for is given by:

dist0 = area(P, B, C) / length(C - B)
dist1 = area(A, P, C) / length(A - C)
dist2 = area(A, B, P) / length(B - A)
minimum distance = min(dist0, dist1, dist2)

The remaining question is how to map this into the GPU pipeline.

One way is to calculate vec3 dist at each vertex of a triangle, then let OpenGL interpolate it across:

dist at A = vec3( area(A, B, C)/length(C - B), 0, 0 )
dist at B = vec3( 0, area(A, B, C)/length(A - C), 0 )
dist at C = vec3( 0, 0, area(A, B, C)/length(B - A) )

Then in the fragment shader you only need to calculate the minimum of the interpolated dist components:

in vec3 dist; // interpolated from the above
minimum distance = min(dist.x, min(dist.y, dist.z))

Alternatively, if you already have the barycentric coordinates available (e.g. through the NV_fragment_shader_barycentric extension), you can piggyback on that. Notice that the barycentric coordinates formula is identical to the above, up to the scaling factors:

bary0 = area(P, B, C) / area(A, B, C)
bary1 = area(A, P, C) / area(A, B, C)
bary2 = area(A, B, P) / area(A, B, C)

Thus, if bary is already available, we only need to scale it by:

dist0 = bary0 * area(A, B, C) / length(C - B)
dist1 = bary1 * area(A, B, C) / length(A - C)
dist2 = bary2 * area(A, B, C) / length(B - A)

Since the scaling factors are constant across the triangle, this can shave off a few FLOPs.

EDIT: I missed that you asked for the actual vector rather than just the distance. The concept remains the same though: you'll need to pass either the normals or the vertices into the shader and based on the computed distances (using either of the above methods), select the normal of the closest edge, scale, and return it. Let's say that n0, n1, n2 are the normals opposite to vertices A, B, C correspondingly; then you'd do the following in the fragment shader:

in vec3 dist; // interpolated from the above
in vec2 n0, n1, n2; // normals
...

vec2 result;
if(dist.x < min(dist.y, dist.z))
    result = dist.x*n0;
else if(dist.y < dist.z)
    result = dist.y*n1;
else
    result = dist.z*n2;


问:
how can i get specific data between div with file_get_content
suppose i echo out

```<code>$url = "http://www.mydomain.com";
echo file_get_content($url);
</code>```

and http://www.mydomain.com has a div i.e

```<code><title>sitename</title>
</head><body>
Lorem Ipsum.......
<div id="divname">and here is div content</div>
Copyright bla bla bla
</code>```

no i want to only fetch content between div with id="divname" how can i do that

答:
$html = file_get_html('http://www.mydomain.com');

foreach($html->find('div#divname') as $e)

    echo $e->innertext;

Here as "divname" is an id so we have used # so if you have any class then you may use .(dot)

ContentLicense: CC BY-SA 2.5

Body:
suppose i echo out

$url = "http://www.mydomain.com";
echo file_get_content($url);

and http://www.mydomain.com has a div i.e

<title>sitename</title>

Lorem Ipsum.......

and here is div content

Copyright bla bla bla

no i want to only fetch content between div with id="divname" how can i do that


问:
Converting object class to numeric class in pandas data frame
First time using python and can't seem to figure this out. I'm scraping data from a website and it's reading it as object class even though the values are numbers. I've tried all the ways described here but keep getting errors. I want the precip column to be numeric. I keep getting the following error code: ValueError: invalid literal for int() with base 10: '4.364.36'

Script with data scraping from website

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import requests
from bs4 import BeautifulSoup
# Get URL where data we want is located
URL ="https://climate.rutgers.edu/stateclim_v1/nclimdiv/"
#Scrape data from website
result= requests.get(URL)
soup = BeautifulSoup(result.content,'lxml')
table = soup.find_all('table')[0]
df = pd.read_html(str(table))
df = pd.concat(df) #Converts list to dataframe
# Reshape data from wide to long
df= pd.melt(df, id_vars = 'Year', var_name='Month',value_name="precip")
# Get rid of missing data
df.dropna(subset=["precip","Year"], inplace=True)
# Filter dataframe to clean up for plotting
df = df[df["precip"].str.contains("M")==False]
df = df[df["Year"].str.contains("Max|Min|Count|Median|Normal|POR") == False]
</code>```

Body:
First time using python and can't seem to figure this out. I'm scraping data from a website and it's reading it as object class even though the values are numbers. I've tried all the ways described here but keep getting errors. I want the precip column to be numeric. I keep getting the following error code: ValueError: invalid literal for int() with base 10: '4.364.36'

Script with data scraping from website

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import requests
from bs4 import BeautifulSoup
# Get URL where data we want is located
URL ="https://climate.rutgers.edu/stateclim_v1/nclimdiv/"
#Scrape data from website
result= requests.get(URL)
soup = BeautifulSoup(result.content,'lxml')
table = soup.find_all('table')[0]
df = pd.read_html(str(table))
df = pd.concat(df) #Converts list to dataframe
# Reshape data from wide to long
df= pd.melt(df, id_vars = 'Year', var_name='Month',value_name="precip")
# Get rid of missing data
df.dropna(subset=["precip","Year"], inplace=True)
# Filter dataframe to clean up for plotting
df = df[df["precip"].str.contains("M")==False]
df = df[df["Year"].str.contains("Max|Min|Count|Median|Normal|POR") == False]

Body:
So the tables from your URL are kind of funky which is why the parser is struggling. You can just copy the upper table to your clipboard (as seen in image) and use this.

df = pd.read_clipboard(header=None)

df = df.iloc[0:128, 1:]

df.columns = ['Year', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Annual']

df = df.replace('M', 0)

for c in df.columns:

    df[c] = pd.to_numeric(df[c])

print(df)

Year        Jan     Feb     Mar     Apr     May     Jun     Jul     Aug Sep Oct Nov Dec Annual
0   1895    4.36    1.24    3.28    5.08    3.13    3.09    4.15    2.06    1.06    3.56    3.07    2.78    36.86
1   1896    1.61    6.88    5.65    1.35    3.54    5.49    5.38    1.68    4.25    2.41    3.12    1.21    42.57
2   1897    2.65    3.67    2.74    3.92    5.37    3.37    11.37   4.89    1.76    2.26    4.87    4.48    51.35
3   1898    4.10    3.45    3.15    3.58    6.77    2.07    4.63    5.45    2.05    5.51    6.60    3.63    50.99
4   1899    3.75    5.71    6.32    1.67    1.94    2.57    5.74    3.91    5.40    2.44    2.29    2.07    43.81
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
123 2018    2.72    6.08    4.64    4.17    5.80    3.30    5.91    5.56    7.57    4.46    8.65    5.90    64.76
124 2019    4.49    3.26    3.84    3.97    6.75    5.15    6.14    3.73    1.25    5.71    1.94    5.32    51.55
125 2020    2.29    2.79    3.61    3.98    2.47    3.05    6.69    6.09    4.41    5.03    4.09    5.35    49.85
126 2021    1.86    4.72    3.82    2.35    3.84    3.37    7.62    6.59    6.45    5.06    0.98    1.28    47.94
127 2022    3.45    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00


问:
Storing data inside GraphicsBuffer after computeShader code runs always are (0,0,0)
Environment of work: Unity3D 2021.2.7.f1
Direct3D11

I try to make Laplacian Smoothing working on GPU
For this case I set up Compute Shader among others VertexBuffer(input Graphics Buffer) and outVertexBuffer( output Grpahics Buffer), unfortunatelly I have a weird problem with storing data into GraphicsBuffer (storing vertices Vector3) which i use as "output" of compute shader.

Assigning of ComputeShader component:

```<code>public void RunSmoothingShader(int kernel,int verticesNo)
{
    ComputeBuffer connectionsBuffer = new
ComputeBuffer(_builder._triangleBudget*6,sizeof(int));

    ComputeBuffer offsetsBuffer = new ComputeBuffer(_builder._triangleBudget, sizeof(int));
    ComputeBuffer _counterBuffer = new ComputeBuffer(1, 4, ComputeBufferType.Counter);
    connectionsBuffer.SetData(VertexConnection.connectionsTable);
    offsetsBuffer.SetData(VertexConnection.offsetsTable);
    smoothingShader.SetBuffer(0,"ConnectionsBuffer",connectionsBuffer);
    smoothingShader.SetBuffer(0,"OffsetsBuffer",offsetsBuffer);
    smoothingShader.SetBuffer(0, "Counter", _counterBuffer);
    smoothingShader.SetBuffer(0,"OutVertexBuffer",outVertexBuffer);
    smoothingShader.SetInt("MaxVerticesNumber", verticesNo);
    smoothingShader.SetBuffer(0,"VertexBuffer", _builder._vertexBuffer);

    smoothingShader.Dispatch(kernel,64,64,64);
}
</code>```

Initialization of outVertexBuffer: (stride is equal 12 because type of float3)

```<code> outVertexBuffer =
            new GraphicsBuffer(GraphicsBuffer.Target.Vertex, 5000000, 12);
</code>```

In LaplacianSmoothing ComputeShader I want to recalculate positions of vertices and store them into outVertexBuffer using Store3 function.
Below is code for LaplacianSmoothing in ComputeShader (HLSL style):

```<code>#pragma kernel LaplacianSmooth

RWTexture2D<float4> Result;
RWByteAddressBuffer VertexBuffer;
RWStructuredBuffer<uint> Counter; // used only for counting
RWByteAddressBuffer ConnectionsBuffer;
RWByteAddressBuffer OffsetsBuffer;
RWByteAddressBuffer OutVertexBuffer;
int MaxVerticesNumber;

#define SIZEOF_UINT 4
#define SIZEOF_FLOAT3 12

[numthreads(8,8,8)]
void LaplacianSmooth (uint3 id : SV_DispatchThreadID)
{
    uint currentIndex = 512*512*id.z + 512*id.y+id.x;
    if (currentIndex < MaxVerticesNumber)
    {
        float3 currentVertex = asfloat(VertexBuffer.Load3(2*currentIndex*SIZEOF_FLOAT3));
        float3 sumNeighVertex = 0;
        uint neighborAdrr=0;
        int currentOffset = OffsetsBuffer.Load(currentIndex*SIZEOF_UINT);
        int nextOffset = OffsetsBuffer.Load((currentIndex+1)*SIZEOF_UINT);
        int connectionCount = nextOffset-currentOffset;
        for (int i=0; i<connectionCount;i++)

        {
            neighborAdrr = ConnectionsBuffer.Load((currentOffset+i)*SIZEOF_UINT);// Adress of neighbor;

            sumNeighVertex += asfloat(VertexBuffer.Load3(neighborAdrr*2*SIZEOF_FLOAT3));
        }

        sumNeighVertex = sumNeighVertex / connectionCount;

        float3 newVert = sumNeighVertex+currentVertex;
        OutVertexBuffer.Store3(currentIndex*SIZEOF_FLOAT3,asuint(currentVertex));
    }
}
</code>```

In next step I want to get data from outVertexBuffer and assing them into vertexArray GraphicsBuffer.GetData(Vector3[] array) function.

```<code>public void OnSmoothMeshLaplacian()
{

PrepareSmoothing();
var mesh = GetComponent<MeshFilter>().mesh;
Mesh testMesh = Instantiate(mesh);
GameObject.Find("Laplacian").GetComponent<MeshFilter>().sharedMesh = testMesh;
//testMesh = LaplacianFilter(testMesh, 5,1f);

Vector3[] vertexArray;
vertexArray = new Vector3[2*testMesh.vertices.Length];
var network = VertexConnection.BuildNetwork(testMesh.triangles);
RunSmoothingShader(smoothingShader.FindKernel("LaplacianSmooth"), testMesh.vertexCount);
outVertexBuffer.GetData(vertexArray);
testMesh.SetVertexBufferData(vertexArray, 0, 0, vertAndPosList.Length);
testMesh.RecalculateBounds();
Debug.Log("Mesh:" + mesh.bounds.size);
Debug.Log("Test Mesh:" + testMesh.bounds.size);
Debug.Log($"Shrinkage: {(mesh.bounds.size - testMesh.bounds.size).magnitude / mesh.bounds.size.magnitude * 100f}%");
    }
</code>```

I set up the breakpoint after getData function and checked the data, all of them are (0,0,0).
I use RenderDoc for checking how buffers works, googled documentations for all function used in shader and main program, but nothing explain this lack of assigning data.
I want to add that when I use inputBuffer also as output then I get data (logicaly incorrect, but still not (0,0,0).

答:
Try this:

outVertexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 5000000, 12);

Notice the changed Target. Graphics buffer needs at least one of the Compute target flags to be able to be bound to a compute kernel. Target.Vertex is not such a flag. You could still add it but in your case it's not needed.

In fact outVertexBuffer could just be a ComputeBuffer. No need to use GraphicsBuffer since you just copy it to the mesh on the CPU side.

EDIT---

Another thing:
SetVertexBufferData() requires you to configure all vertex attributes first and the data you pass should basically be raw vertex data: positions, normals, uvs (if any) and so on.

If you only want to set vertices perhaps it would be easier to just use Mesh.SetVertices().

Body:
Environment of work: Unity3D 2021.2.7.f1
Direct3D11

I try to make Laplacian Smoothing working on GPU
For this case I set up Compute Shader among others VertexBuffer(input Graphics Buffer) and outVertexBuffer( output Grpahics Buffer), unfortunatelly I have a weird problem with storing data into GraphicsBuffer (storing vertices Vector3) which i use as "output" of compute shader.

Assigning of ComputeShader component:

public void RunSmoothingShader(int kernel,int verticesNo)
{
    ComputeBuffer connectionsBuffer = new
ComputeBuffer(_builder._triangleBudget*6,sizeof(int));

    ComputeBuffer offsetsBuffer = new ComputeBuffer(_builder._triangleBudget, sizeof(int));
    ComputeBuffer _counterBuffer = new ComputeBuffer(1, 4, ComputeBufferType.Counter);
    connectionsBuffer.SetData(VertexConnection.connectionsTable);
    offsetsBuffer.SetData(VertexConnection.offsetsTable);
    smoothingShader.SetBuffer(0,"ConnectionsBuffer",connectionsBuffer);
    smoothingShader.SetBuffer(0,"OffsetsBuffer",offsetsBuffer);
    smoothingShader.SetBuffer(0, "Counter", _counterBuffer);
    smoothingShader.SetBuffer(0,"OutVertexBuffer",outVertexBuffer);
    smoothingShader.SetInt("MaxVerticesNumber", verticesNo);
    smoothingShader.SetBuffer(0,"VertexBuffer", _builder._vertexBuffer);

    smoothingShader.Dispatch(kernel,64,64,64);
}

Initialization of outVertexBuffer: (stride is equal 12 because type of float3)

 outVertexBuffer =
            new GraphicsBuffer(GraphicsBuffer.Target.Vertex, 5000000, 12);

In LaplacianSmoothing ComputeShader I want to recalculate positions of vertices and store them into outVertexBuffer using Store3 function.
Below is code for LaplacianSmoothing in ComputeShader (HLSL style):

#pragma kernel LaplacianSmooth

RWTexture2D<float4> Result;
RWByteAddressBuffer VertexBuffer;
RWStructuredBuffer<uint> Counter; // used only for counting
RWByteAddressBuffer ConnectionsBuffer;
RWByteAddressBuffer OffsetsBuffer;
RWByteAddressBuffer OutVertexBuffer;
int MaxVerticesNumber;

#define SIZEOF_UINT 4
#define SIZEOF_FLOAT3 12

[numthreads(8,8,8)]
void LaplacianSmooth (uint3 id : SV_DispatchThreadID)
{
    uint currentIndex = 512*512*id.z + 512*id.y+id.x;
    if (currentIndex < MaxVerticesNumber)
    {
        float3 currentVertex = asfloat(VertexBuffer.Load3(2*currentIndex*SIZEOF_FLOAT3));
        float3 sumNeighVertex = 0;
        uint neighborAdrr=0;
        int currentOffset = OffsetsBuffer.Load(currentIndex*SIZEOF_UINT);
        int nextOffset = OffsetsBuffer.Load((currentIndex+1)*SIZEOF_UINT);
        int connectionCount = nextOffset-currentOffset;
        for (int i=0; i<connectionCount;i++)

        {
            neighborAdrr = ConnectionsBuffer.Load((currentOffset+i)*SIZEOF_UINT);// Adress of neighbor;

            sumNeighVertex += asfloat(VertexBuffer.Load3(neighborAdrr*2*SIZEOF_FLOAT3));
        }

        sumNeighVertex = sumNeighVertex / connectionCount;

        float3 newVert = sumNeighVertex+currentVertex;
        OutVertexBuffer.Store3(currentIndex*SIZEOF_FLOAT3,asuint(currentVertex));
    }
}

In next step I want to get data from outVertexBuffer and assing them into vertexArray GraphicsBuffer.GetData(Vector3[] array) function.

public void OnSmoothMeshLaplacian()
{

PrepareSmoothing();
var mesh = GetComponent<MeshFilter>().mesh;
Mesh testMesh = Instantiate(mesh);
GameObject.Find("Laplacian").GetComponent<MeshFilter>().sharedMesh = testMesh;
//testMesh = LaplacianFilter(testMesh, 5,1f);

Vector3[] vertexArray;
vertexArray = new Vector3[2*testMesh.vertices.Length];
var network = VertexConnection.BuildNetwork(testMesh.triangles);
RunSmoothingShader(smoothingShader.FindKernel("LaplacianSmooth"), testMesh.vertexCount);
outVertexBuffer.GetData(vertexArray);
testMesh.SetVertexBufferData(vertexArray, 0, 0, vertAndPosList.Length);
testMesh.RecalculateBounds();
Debug.Log("Mesh:" + mesh.bounds.size);
Debug.Log("Test Mesh:" + testMesh.bounds.size);
Debug.Log($"Shrinkage: {(mesh.bounds.size - testMesh.bounds.size).magnitude / mesh.bounds.size.magnitude * 100f}%");
    }

I set up the breakpoint after getData function and checked the data, all of them are (0,0,0).
I use RenderDoc for checking how buffers works, googled documentations for all function used in shader and main program, but nothing explain this lack of assigning data.
I want to add that when I use inputBuffer also as output then I get data (logicaly incorrect, but still not (0,0,0).


问:
logging DDE conversations in windows 10
I need to trace where a DDE conversation is failing in windows 10. This is handing a file path to

I always used DDESpy, but it crashes under win10 when monitoring events. I have tried running under all legacy modes.

Can the event viewer be configured to log DDE commands?

答:
I also had a need to trace/debug DDE traffic.
Same experience as reported by others: old Spy++ crashes.
However, I located a working Spy++ and Spy++ (64 bit) in my
installation of Visual Studio 2010 - on Windows 10 Pro
The Spy++ and Spy++ (64) have much more tracing capabilities.
But most important, they do not crash (so far).

Regards, Max

Screenshot from using Spy++ from Visual Studio 2010:

Title: logging DDE conversations in windows 10


问:
Getting please set the query parameter changesNotSentForReview to true while releasing Android App from appcenter.ms
I am trying to build and distribute android app from appcenter.ms. Initially I got rejection after rolling out 3rd update and I tried to rebuild changes. But while distributing to store I got following issue.

Edit could not be committed due to an error. Changes cannot be sent
for review automatically. Please set the query parameter
changesNotSentForReview to true. Once committed, the changes in this
edit can be sent for review from the Google Play Console UI.

I don't want to make changes from Google Play Console UI and want to make changes from appcenter.ms only.
How to set that parameter in code.
Help will be really appreciable!

答:
Had this same issue from AppCenter. There are some sites suggesting this is a setting in the API that is posting the app but AppCenter does not offer the setting.

The solution for me was to use 'Archive for Publishing' in Visual Studio for mac. If I then chose to 'sign and distribute' direct to Google play I would get the same issue as above.

By choosing 'Ad Hoc' distribution, then saving locally I would get a signed .aab file. This file can be manually uploaded to Google when editing a release.

I created a new track, manually uploaded, promoted it to testing then production without any issue.


问:
SQL Create new column based on self join
Here is the Data below:

Name
Parent
Age

John
Mary
12

Mary
None
23

I want to create a new column called Parent's Age so that John's row will now have a column called Parent's age and it would be 23. Mary would have none as Parent's age.

I've tried joining the table to itself on Name = Parent but the wrong age is pulled.

答:
First of all you should use ID's as primary and foreign keys as it's high likely, that there are more people with the name Mary and that will end up in wrong joins.

Afterwards you can create a view where every person with the related parent data is shown. It's bad practice to store that as physical column in the person table.

An example for MS SQL Server:

```<code>CREATE TABLE [dbo].[tblPerson](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentID] [int] NULL,
    [Name] [nvarchar](255) NULL,
    [Age] [int] NULL
 CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

insert into tblPerson(ParentID, [Name], Age) values(NULL, 'Marry', 23);
insert into tblPerson(ParentID, [Name], Age) values(1, 'John', 12);

select
    child.[Name] as [Child Name],
    child.Age as [Child Age],
    parent.[Name] as [Parent Name],
    parent.Age as [Parent Age]
from tblPerson child
left join tblPerson parent on child.ParentID = parent.ID
</code>```

In addition it's also bad practise to store the age ... much better is to store the birthdate and calculate the age out of that.

Body:
First of all you should use ID's as primary and foreign keys as it's high likely, that there are more people with the name Mary and that will end up in wrong joins.

Afterwards you can create a view where every person with the related parent data is shown. It's bad practice to store that as physical column in the person table.

An example for MS SQL Server:

CREATE TABLE [dbo].[tblPerson](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ParentID] [int] NULL,
    [Name] [nvarchar](255) NULL,
    [Age] [int] NULL
 CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

insert into tblPerson(ParentID, [Name], Age) values(NULL, 'Marry', 23);
insert into tblPerson(ParentID, [Name], Age) values(1, 'John', 12);

select
    child.[Name] as [Child Name],
    child.Age as [Child Age],
    parent.[Name] as [Parent Name],
    parent.Age as [Parent Age]
from tblPerson child
left join tblPerson parent on child.ParentID = parent.ID

In addition it's also bad practise to store the age ... much better is to store the birthdate and calculate the age out of that.


问:
Minimum order amount depending on postcode and shipping method on WooCommerce
How can I set a minimum order amount only for Delivery/Shipments (but not for local pickup) and depending on specific post codes?

Use Case: A Restaurant delivers in the local village without minimum amount. But the neighbor villages should have an order amount. Pickup is always without any minimum amount.

Based on Minimum order amount except for specific shipping method in WooCommerce answer code, this is my attempt:

```<code>add_action( 'woocommerce_check_cart_items', 'wc_minimum_required_order_amount' );
function wc_minimum_required_order_amount() {

// HERE Your settings
$minimum_amount     = 50; // The minimum cart total amount
$shipping_method_id = 'local_pickup'; // The targeted shipping method Id (exception)
$postcodes = array('82065', '82057', '82067'); // Define your targeted postcodes in the array
$postcode  = '82069'; // Initializing

// Get some variables
$cart_total     = (float) WC()->cart->total; // Total cart amount
$chosen_methods = (array) WC()->session->get( 'chosen_shipping_methods' ); // Chosen shipping method rate Ids (array)

// Only when a shipping method has been chosen
if ( ! empty($chosen_methods) ) {
    $chosen_method  = explode(':', reset($chosen_methods)); // Get the chosen shipping method Id (array)
    $chosen_method_id = reset($chosen_method); // Get the chosen shipping method Id
}

// If "Local pickup" shipping method is chosen, exit (no minimun is required)
if ( isset($chosen_method_id) && $chosen_method_id === $shipping_method_id ) {
    return; // exit
}

if ( isset($_POST['shipping_postcode']) && ! empty($_POST['shipping_postcode']) ) {
    $postcode = $_POST['shipping_postcode'];
    if ( empty($postcode) && isset($_POST['billing_postcode']) && ! empty($_POST['billing_postcode']) ) {
        $postcode = $_POST['billing_postcode'];
    }
} elseif ( $postcode = WC()->customer->get_shipping_postcode() ) {
    if ( empty($postcode) ) {
        $postcode = WC()->customer->get_billing_postcode();
    }
}

// Add an error notice is cart total is less than the minimum required
if ( $cart_total < $minimum_amount && ! empty($postcode) && in_array( $postcode, $postcodes ) ) {
    wc_add_notice( sprintf(
        __("The minimum required order amount is %s (your current order amount is %s).", "woocommerce"), // Text message
        wc_price( $minimum_amount ),
        wc_price( $cart_total )
    ), 'error' );
}
}
</code>```

答:
You are close with your solution, what is missing, however, is the use of in_array(), with which you can check the postcode

So you get:

function action_woocommerce_check_cart_items() {
    // HERE Your settings
    $minimum_amount = 50; // The minimum cart total amount
    $shipping_method_id = 'local_pickup'; // The targeted shipping method Id (exception)
    $postcodes = array( 82065, 82057, 82067, 9800 ); // Define your targeted postcodes in the array

    // Get some variables
    $cart_total     = (float) WC()->cart->total; // Total cart amount
    $chosen_methods = (array) WC()->session->get( 'chosen_shipping_methods' ); // Chosen shipping method rate Ids (array)

    // Initialize
    $postcode = '';

    // Only when a shipping method has been chosen
    if ( ! empty($chosen_methods) ) {
        $chosen_method  = explode( ':', reset( $chosen_methods ) ); // Get the chosen shipping method Id (array)
        $chosen_method_id = reset( $chosen_method ); // Get the chosen shipping method Id
    }

    // If "Local pickup" shipping method is chosen, exit (no minimun is required)
    if ( isset($chosen_method_id) && $chosen_method_id === $shipping_method_id ) {
        return; // exit
    }

    // Get shipping postode
    $postcode = WC()->customer->get_shipping_postcode();

    // When empty
    if ( empty ( $postcode ) ) {
        if ( isset( $_POST['shipping_postcode'] ) ) {
            $postcode = $_POST['shipping_postcode'];
        } else {
            if ( isset( $_POST['billing_postcode'] ) ) {
                $postcode = $_POST['billing_postcode'];
            } else {
                $postcode = WC()->customer->get_billing_postcode();
            }
        }
    }

    // Still empty, exit
    if ( empty ( $postcode ) ) return;

    // Add an error notice is cart total is less than the minimum required and postcode occurs in the array
    if ( $cart_total < $minimum_amount && in_array( $postcode, $postcodes ) ) {
        // Your error message
        wc_add_notice( sprintf(
            __( 'The minimum required order amount is %s (your current order amount is %s).', 'woocommerce' ), // Text message
            wc_price( $minimum_amount ),
            wc_price( $cart_total )
        ), 'error' );

        // Optional: remove proceed to checkout button
        remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
    }
}
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
```

Body:
How can I set a minimum order amount only for Delivery/Shipments (but not for local pickup) and depending on specific post codes?

Use Case: A Restaurant delivers in the local village without minimum amount. But the neighbor villages should have an order amount. Pickup is always without any minimum amount.

Based on Minimum order amount except for specific shipping method in WooCommerce answer code, this is my attempt:

add_action( 'woocommerce_check_cart_items', 'wc_minimum_required_order_amount' );
function wc_minimum_required_order_amount() {

// HERE Your settings
$minimum_amount     = 50; // The minimum cart total amount
$shipping_method_id = 'local_pickup'; // The targeted shipping method Id (exception)
$postcodes = array('82065', '82057', '82067'); // Define your targeted postcodes in the array
$postcode  = '82069'; // Initializing

// Get some variables
$cart_total     = (float) WC()->cart->total; // Total cart amount
$chosen_methods = (array) WC()->session->get( 'chosen_shipping_methods' ); // Chosen shipping method rate Ids (array)

// Only when a shipping method has been chosen
if ( ! empty($chosen_methods) ) {
    $chosen_method  = explode(':', reset($chosen_methods)); // Get the chosen shipping method Id (array)
    $chosen_method_id = reset($chosen_method); // Get the chosen shipping method Id
}

// If "Local pickup" shipping method is chosen, exit (no minimun is required)
if ( isset($chosen_method_id) && $chosen_method_id === $shipping_method_id ) {
    return; // exit
}

if ( isset($_POST['shipping_postcode']) && ! empty($_POST['shipping_postcode']) ) {
    $postcode = $_POST['shipping_postcode'];
    if ( empty($postcode) && isset($_POST['billing_postcode']) && ! empty($_POST['billing_postcode']) ) {
        $postcode = $_POST['billing_postcode'];
    }
} elseif ( $postcode = WC()->customer->get_shipping_postcode() ) {
    if ( empty($postcode) ) {
        $postcode = WC()->customer->get_billing_postcode();
    }
}

// Add an error notice is cart total is less than the minimum required
if ( $cart_total < $minimum_amount && ! empty($postcode) && in_array( $postcode, $postcodes ) ) {
    wc_add_notice( sprintf(
        __("The minimum required order amount is %s (your current order amount is %s).", "woocommerce"), // Text message
        wc_price( $minimum_amount ),
        wc_price( $cart_total )
    ), 'error' );
}
}


问:
How to tell Jenkins build Console Logs to obfuscate passwords, preferably without a plugIn?
We need for Jenkins to stop displaying passwords in the Console Build Logs.

We are not using the Jenkins Vault to store passwords, and neither are we using environment variables. Instead we get credentials from our own central location and get then to build 'bat' commands to run in our build pipelines.

The problem is that Jenkins posts all the passwords naked in the build logs.

Is there a way to intervene in the Jenkins Console Logging process, grab the text about to be logged and replace strings with "XXXXX", on the fly?

Barring that, is there a plugin to do this easily?

I have seen some plugins that mask the password, but they require the passwords be stored in Jenkins build environment parameters, which we do  not use.

答:
1 - Install plugin: mask-passwords

2 - In your jenkinsFile folow this example:

```<code>// Example code:

node {
  withSecretEnv([[var: 'VAULT_TOKEN', password: 'toosekret']]) {
    sh '''#!/bin/bash -eu
    echo "with env use:      ${VAULT_TOKEN}"
    sleep 1
    echo "without env use:   toosekret"
    sleep 1
    echo "just the var name: VAULT_TOKEN"
    '''
    sleep 1
    echo "Outside SH: VAULT_TOKEN=${VAULT_TOKEN}"
  }
}

// Dont forgot this def
def withSecretEnv(List<Map> varAndPasswordList, Closure closure) {
  wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: varAndPasswordList]) {
    withEnv(varAndPasswordList.collect { "${it.var}=${it.password}" }) {
      closure()
    }
  }
}
</code>```

3 - The result wil:

```<code>// Example output:
'''
[Pipeline] node
Running on magic-agent in /a/workspace/with-secret-env
[Pipeline] {
[Pipeline] wrap
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
[with-secret-env] Running shell script
with env use:      ********
without env use:   ********
just the var name: VAULT_TOKEN
[Pipeline] sleep
Sleeping for 1 sec
[Pipeline] echo
Outside SH: VAULT_TOKEN=********
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
'''
</code>```

Body:
1 - Install plugin: mask-passwords

2 - In your jenkinsFile folow this example:

// Example code:

node {
  withSecretEnv([[var: 'VAULT_TOKEN', password: 'toosekret']]) {
    sh '''#!/bin/bash -eu
    echo "with env use:      ${VAULT_TOKEN}"
    sleep 1
    echo "without env use:   toosekret"
    sleep 1
    echo "just the var name: VAULT_TOKEN"
    '''
    sleep 1
    echo "Outside SH: VAULT_TOKEN=${VAULT_TOKEN}"
  }
}

// Dont forgot this def
def withSecretEnv(List<Map> varAndPasswordList, Closure closure) {
  wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: varAndPasswordList]) {
    withEnv(varAndPasswordList.collect { "${it.var}=${it.password}" }) {
      closure()
    }
  }
}

3 - The result wil:

// Example output:
'''
[Pipeline] node
Running on magic-agent in /a/workspace/with-secret-env
[Pipeline] {
[Pipeline] wrap
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
[with-secret-env] Running shell script
with env use:      ********
without env use:   ********
just the var name: VAULT_TOKEN
[Pipeline] sleep
Sleeping for 1 sec
[Pipeline] echo
Outside SH: VAULT_TOKEN=********
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
'''