问:
Write Ruby Test::Unit Errors & Fails to File
I am trying to write fails and errors that occur in the test to a log file, so that they don't appear on-screen, but it appears as though errors and assert failures write to STDOUT instead of STDERR. I have been unable to find information on how to redirect this output after hours of googling, and would greatly appreciate help.</p>

答:
Why should the errors not be on stdout?
Up to now I have no prepared solution to suppress the output for specific errors.

If you accept the unchanged output, I have a solution to store errors and failures in a file. It will be no problem to create a 2nd file for Notifications...

```<code>gem 'test-unit'
require 'test/unit'

module Test
  module Unit
    class TestSuite
      alias :old_run :run
      def run(result, &progress_block)
        old_run(result, &progress_block)
        File.open('test.log', 'w'){|f|
          result.faults.each{|err|
            case err
              when Test::Unit::Error, Test::Unit::Failure
                f << err.long_display
                f << "\n===========\n"
              #not in log file
              when Test::Unit::Pending, Test::Unit::Notification, Test::Unit::Omission
              end
          }
        }
      end
    end
  end
end

class MyTest < Test::Unit::TestCase

  def test_1()
    assert_equal( 3, 1+1) #failure
  end
  def test_2()
    1 / 0 #force an error
  end
  def test_3()
    notify 'sss'
  end
  def test_4()
    pend "MeineKlasse.new"
  end
  def test_5
    omit 'aaa' if RUBY_VERSION == '1.9.2'
  end

  def test_5
    assert_in_delta( 0.1, 0.00001, 1.0/10)
  end

end
</code>```

Body:
Why should the errors not be on stdout?
Up to now I have no prepared solution to suppress the output for specific errors.

If you accept the unchanged output, I have a solution to store errors and failures in a file. It will be no problem to create a 2nd file for Notifications...

gem 'test-unit'
require 'test/unit'

module Test
  module Unit
    class TestSuite
      alias :old_run :run
      def run(result, &progress_block)
        old_run(result, &progress_block)
        File.open('test.log', 'w'){|f|
          result.faults.each{|err|
            case err
              when Test::Unit::Error, Test::Unit::Failure
                f << err.long_display
                f << "\n===========\n"
              #not in log file
              when Test::Unit::Pending, Test::Unit::Notification, Test::Unit::Omission
              end
          }
        }
      end
    end
  end
end

class MyTest < Test::Unit::TestCase

  def test_1()
    assert_equal( 3, 1+1) #failure
  end
  def test_2()
    1 / 0 #force an error
  end
  def test_3()
    notify 'sss'
  end
  def test_4()
    pend "MeineKlasse.new"
  end
  def test_5
    omit 'aaa' if RUBY_VERSION == '1.9.2'
  end

  def test_5
    assert_in_delta( 0.1, 0.00001, 1.0/10)
  end

end


来源: stackexchange

问:
Range() returning different output than "list" in "for" loop
I'm a beginner trying to understand why I get a different output when I use the range function. If I use (len(arr)) the output: 5 0 3  vs using arr the output: 3 2 1

```<code> arr = [-4, 3, -9, 0, 4, 1]

 def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in range(len(arr)):
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
    print(count_pos)
    print(count_neg)
    print(count_zero)
</code>```

Comparing that version to not using range() and just arr:

```<code>def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in arr:
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)
</code>```

答:
These are two different by meaning things

```<code>range(len(arr))
</code>```

will return a list from 0 to len(arr) - 1

List is iterable so you can iterate over its elements

The default iteration construction is for loop

```<code>for i in <iterable>:
</code>```

So in the first example you are iterating over

```<code>[0, 1, 2, 3, 4, 5]
</code>```

which was created by range()

In the second example you are iterating over

```<code>[-4, 3, -9, 0, 4, 1]
</code>```

That is the difference

ContentLicense: CC BY-SA 4.0

Body:
I'm a beginner trying to understand why I get a different output when I use the range function. If I use (len(arr)) the output: 5 0 3  vs using arr the output: 3 2 1

 arr = [-4, 3, -9, 0, 4, 1]

 def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in range(len(arr)):
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
    print(count_pos)
    print(count_neg)
    print(count_zero)

Comparing that version to not using range() and just arr:

def plusMinus(arr):
    count_pos = 0
    count_neg = 0
    count_zero = 0
    for i in arr:
        if i>0:
        count_pos += 1
        if i<0:
        count_neg += 1
    else:
        count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)

Body:
These are two different by meaning things

range(len(arr))

will return a list from 0 to len(arr) - 1

List is iterable so you can iterate over its elements

The default iteration construction is for loop

for i in <iterable>:

So in the first example you are iterating over

[0, 1, 2, 3, 4, 5]

which was created by range()

In the second example you are iterating over

[-4, 3, -9, 0, 4, 1]

That is the difference


问:
Python code to randomly guess user input number
I just just finished (jk I was looking at old code and found this so) but for real this is the final code
final update: Everything now good
thanks to this odd number formula.
The sum of n odd numbers is n^2
How did we arrive to this formula

First 1 odd number = 1 Sum = 1 = 1^2

First 2 odd numbers =1,3 Sum = 4 =    2^2

First 3 odd numbers = 1,3,5 Sum = 9 = 3^2

First 4 odd numbers =1,3,5,7 Sum = 16 4^2

First 5 odd numbers = 1,3,5,7,9 Sum = 25 =5^2

Therefore sum of n odd numbers = n^2

import random,os
userI =True
os.system("cls")
def randomOddNumber(a,b):
  a = a // 2
  b = b // 2 - 1
  number = random.randint(a,b)
  number = (number * 2) + 1
  return number
while userI==True:
    userInput = int(input("Please input a 4 digit number: "))
    compNumber = random.randint(1000, 9999)

    count = 0
    while userInput != compNumber:

        if (userInput % 2) == 0:

                compNumber= random.randrange(0, 10000, 2)
                count=count+1
        else:
              compNumber = randomOddNumber(0,9999)
              count =count+1
    print("Match was created on the", count, "attempt.")
    ex = False
    while ex == False:
        userAwnser = input("Would you like to play again?: ")
        if userAwnser == "no"or userAwnser=="No":
            userI = False
            ex = True
        elif userAwnser == "yes"or userAwnser=="Yes":
            userI = True
            ex = True
            os.system("cls")
        else:
            print("Error Not a valid awnser")
            ex = False

```

答:
The main issue here is that you are trying to force input() to split your string input into four variables. Even if you wanted to convert it to integers, you would need to use a for loop or equivalent to separate it into a list. Also, having each digit split is redundant for your case, and you could just compare the integer to a 4 digit random integer (ex: randint(1000, 9999). Below is a simpler and more efficient way of doing this:

```<code>import random

userInput = int(input("Please input a 4 digit number: "))
compNumber = random.randint(1000, 9999)

count = 0
while userInput != compNumber:
    compNumber = random.randint(1000, 9999)
    count += 1
print("Match was created on the", count, "attempt.")

</code>```

Please comment if you have any questions!

Note: This does not have any user input validation and will break if given a string and will be in a forever loop if the input is a number greater then 9999 or smaller then 1000

Body:
The main issue here is that you are trying to force input() to split your string input into four variables. Even if you wanted to convert it to integers, you would need to use a for loop or equivalent to separate it into a list. Also, having each digit split is redundant for your case, and you could just compare the integer to a 4 digit random integer (ex: randint(1000, 9999). Below is a simpler and more efficient way of doing this:

import random

userInput = int(input("Please input a 4 digit number: "))
compNumber = random.randint(1000, 9999)

count = 0
while userInput != compNumber:
    compNumber = random.randint(1000, 9999)
    count += 1
print("Match was created on the", count, "attempt.")

Please comment if you have any questions!

Note: This does not have any user input validation and will break if given a string and will be in a forever loop if the input is a number greater then 9999 or smaller then 1000


问:
Flutter Circular Avatar background color while loading
I used two circular avatar (the first one with a white background just a little bigger to create a white border).
Also the second one have the background property set to white.
However before the image is loaded I see a blue background. As you can see form the code there are no one blu widget on the back...
I wold like to have a black or white background while the widget is loading the picture.</p>
```<code>return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        padding: const EdgeInsets.only(top: 30),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: appColor,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  width: 0,
                  height: 20,
                ),
                const Center(
                  child: Text(
                    'WhyBye ',
                    style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Savor',
                      fontSize: 40,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 0,
                  height: 10,
                ),
                Stack(
                  //& Stack contenente l'immagine del profilo.
                  children: [
                    _image != null
                        ? CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: MemoryImage(_image!),
                            ))
                        : CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: Variables.userPicUrl.isNotEmpty
                                  ? NetworkImage(Variables.userPicUrl)
                                  : null,
                            )),
                    Positioned(
                      //& All'interno del precedente Stack, posizionamento dei pulsanti immagine dalla galleria/fotocamera.
                      bottom: -10,
                      left: 15,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.gallery);
                        },
                        icon: const Icon(Icons.photo_library_rounded),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
                    Positioned(
                      bottom: -10,
                      left: 135,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.camera);
                        },
                        icon: const Icon(Icons.add_a_photo),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
</code>```

答:
I think you need to add

Blockquote

foregroundImage
ImageProvider?
The foreground image of the circle. [...]

you could decide to use a dark image

Body:
I used two circular avatar (the first one with a white background just a little bigger to create a white border).
Also the second one have the background property set to white.
However before the image is loaded I see a blue background. As you can see form the code there are no one blu widget on the back...
I wold like to have a black or white background while the widget is loading the picture.

return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        padding: const EdgeInsets.only(top: 30),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: appColor,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  width: 0,
                  height: 20,
                ),
                const Center(
                  child: Text(
                    'WhyBye ',
                    style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Savor',
                      fontSize: 40,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 0,
                  height: 10,
                ),
                Stack(
                  //& Stack contenente l'immagine del profilo.
                  children: [
                    _image != null
                        ? CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: MemoryImage(_image!),
                            ))
                        : CircleAvatar(
                            radius: 100,
                            backgroundColor: Colors.white,
                            child: CircleAvatar(
                              radius: 96,
                              backgroundImage: Variables.userPicUrl.isNotEmpty
                                  ? NetworkImage(Variables.userPicUrl)
                                  : null,
                            )),
                    Positioned(
                      //& All'interno del precedente Stack, posizionamento dei pulsanti immagine dalla galleria/fotocamera.
                      bottom: -10,
                      left: 15,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.gallery);
                        },
                        icon: const Icon(Icons.photo_library_rounded),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),
                    Positioned(
                      bottom: -10,
                      left: 135,
                      child: IconButton(
                        onPressed: () {
                          selectImage(ImageSource.camera);
                        },
                        icon: const Icon(Icons.add_a_photo),
                        color: Colors.white,
                        iconSize: 32,
                      ),
                    ),


问:
Use existing Static library in C++ WinRT UWP app
I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that?

I have read the documentation. But it has me confused.

Documentation talk about "Using a native C++ static library in a UWP App" what is a native c++ library?.

Also, I do not have the source code for this library.

答:
I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that? Also, I do not have the source code for this library.

Yes. You don't need the source code to use a library.

You can just use the binary library ( the final output from the source ) that is provided. It can be included as either a static or dynamic library in your final output binary.

How to include that?

Referring to some portion from the doc for your third party static library that may help.

```<code>To use a native C++ static library in a UWP project
In the project properties for the UWP project,

choose Configuration Properties > Linker > Input in the left pane.

In the right pane, add the path to the library in the Additional Dependencies property.

For example, for a library in the project that places
its output in <SolutionFolder>\Debug\MyNativeLibrary\MyNativeLibrary.lib,
add the relative path Debug\MyNativeLibrary\MyNativeLibrary.lib.

Add a include statement to reference the header file to your pch.h file (if present),
or in any .cpp file as needed, and start adding code that uses the library.

C++

Copy
#include "..\MyNativeLibrary\MyNativeLibrary.h"
</code>```

Body:
I have an existing third-party static library that I want to use in my project C++WinRT UWP app. Can I do that? Also, I do not have the source code for this library.

Yes. You don't need the source code to use a library.

You can just use the binary library ( the final output from the source ) that is provided. It can be included as either a static or dynamic library in your final output binary.

How to include that?

Referring to some portion from the doc for your third party static library that may help.

To use a native C++ static library in a UWP project
In the project properties for the UWP project,

choose Configuration Properties > Linker > Input in the left pane.

In the right pane, add the path to the library in the Additional Dependencies property.

For example, for a library in the project that places
its output in <SolutionFolder>\Debug\MyNativeLibrary\MyNativeLibrary.lib,
add the relative path Debug\MyNativeLibrary\MyNativeLibrary.lib.

Add a include statement to reference the header file to your pch.h file (if present),
or in any .cpp file as needed, and start adding code that uses the library.

C++

Copy
#include "..\MyNativeLibrary\MyNativeLibrary.h"


问:
How to know when is the github action will be started?
I am currently using the GitHub actions feature for my project CI-CD, so the pipeline listens to push on the main branch, and when I do no action gets triggered on the actions tab, also I try to run that pipeline manually since I have workflow_dispatch  and it says

```<code>Workflow run was successfully requested.
</code>```

I don't understand is there a queuing system for actions or are there some priorities? and also I would like to know when and whether the action is going to start?

Update:

The github action started after few minutes.

答:
It must depend on the Azure server load and availability.

For instance, scheduled actions come with the caveat:

Note: The schedule event can be delayed during periods of high loads of GitHub Actions workflow runs.

High load times include the start of every hour.

To decrease the chance of delay, schedule your workflow to run at a different time of the hour.

In your case, you were scheduling the job manually, but it had to wait for other jobs to complete first.

Plus, in your case, there was a GitHub Actions incident report earlier today, which could have has a side-effect regarding the scheduling your your job.

Body:
I am currently using the GitHub actions feature for my project CI-CD, so the pipeline listens to push on the main branch, and when I do no action gets triggered on the actions tab, also I try to run that pipeline manually since I have workflow_dispatch  and it says

Workflow run was successfully requested.

I don't understand is there a queuing system for actions or are there some priorities? and also I would like to know when and whether the action is going to start?

Update:

The github action started after few minutes.


问:
Ansible - Copy command output to file for multiple hosts
I run a playbook with a single command against multiple Cisco Nexus hosts. For all hosts, I want to store the output of the commands in a single file on the controller.

---
- name: Nxos
  hosts:
    - sw1
    - sw2
  gather_facts: false
  tasks:
    - name: interface counters
      cisco.nxos.nxos_command:
        commands: show interface counters errors non-zero
      register: output
```
<p>However, with this method below, only 1 host's output is saved and not the others.</p>
<pre class="lang-yaml prettyprint-override"><code>  - name: copy output to file
    copy: content="{{ output.stdout[0] }}" dest="output.txt"
</code>```

Whereas, if I use the below method, sometimes the output is stored for all hosts while other times it only stores output for a random number of hosts

  - name: Copy output to file
    local_action:
      module: lineinfile
      path: output.txt
      line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
      create: yes
```

Any idea what could be wrong or what the best way to store the output be?

Thanks

答:
If you're always writing to a file named output.txt, then of course you only see output for a single host -- for each host, Ansible re-writes the file with new data. There's no magic that tells Ansible it should be appending to the file or something.

The easiest solution is write output to files named after each host, like this:

```<code>    - name: copy output to file
      copy:
        content: "{{ output.stdout[0] }}
        dest: "output-{{ inventory_hostname }}.txt"
</code>```

If you want, you could add a task at the end of your playbook that
would concatenate all those files together.

Body:
I run a playbook with a single command against multiple Cisco Nexus hosts. For all hosts, I want to store the output of the commands in a single file on the controller.

---
- name: Nxos
  hosts:
    - sw1
    - sw2
  gather_facts: false
  tasks:
    - name: interface counters
      cisco.nxos.nxos_command:
        commands: show interface counters errors non-zero
      register: output

However, with this method below, only 1 host's output is saved and not the others.

  - name: copy output to file
    copy: content="{{ output.stdout[0] }}" dest="output.txt"

Whereas, if I use the below method, sometimes the output is stored for all hosts while other times it only stores output for a random number of hosts

  - name: Copy output to file
    local_action:
      module: lineinfile
      path: output.txt
      line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
      create: yes

Any idea what could be wrong or what the best way to store the output be?

Thanks

Body:
If you're always writing to a file named output.txt, then of course you only see output for a single host -- for each host, Ansible re-writes the file with new data. There's no magic that tells Ansible it should be appending to the file or something.

The easiest solution is write output to files named after each host, like this:

    - name: copy output to file
      copy:
        content: "{{ output.stdout[0] }}
        dest: "output-{{ inventory_hostname }}.txt"

If you want, you could add a task at the end of your playbook that
would concatenate all those files together.


问:
How to use assert_select to test for presence of a given link?
My page should contain a link that looks like Click to go.

How would you test for that using assert_select? I want to check for the presence of an a tag with href="/desired_path/1". How do you test the attributes of a tag?

Are there any resources to explain how to use assert_select? I read the Guides and API documentation, but didn't figure it out. Are there any recommended better ways of doing this?

I am working in Rails 3 and using the built-in test framework.

Thanks.

答:
You can pass any CSS selector to assert_select. So to test the attribute of a tag, you use [attrname=attrvalue]:

```<code>assert_select("a[href=/desired_path/1]") do |elements|
   # Here you can test that elements.count == 1 for instance, or anything else
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can pass any CSS selector to assert_select. So to test the attribute of a tag, you use [attrname=attrvalue]:

assert_select("a[href=/desired_path/1]") do |elements|
   # Here you can test that elements.count == 1 for instance, or anything else
end


问:
DOS: find a string, if found then run another script
I want to find  a string in a file using DOS:

For example

find "string" status.txt

And when it is found, I want to run a batch file.

What is the best way to do this?

答:
That's more straightforward:</p>
```<code>find /c "string" file
if %errorlevel% not equ 1 goto something
</code>```

Body:
That's more straightforward:

find /c "string" file
if %errorlevel% not equ 1 goto something


问:
Retrieve deleted pull request on github?
I'm overseeing a small open source project and we use github.
A contributor sent us a PR with some good work we really want to have, and would struggle to replicate, including some files that aren't code

Direct link if it's helpful: https://github.com/DS-13-Dev-Team/DS13/pull/1994

Unfortunately, this contributor got into a fight with another team member, things got out of hand, and he left the project, before I got around to reviewing and merging this work. He deleted his repo and closed the PR too.

We would still like to merge this contribution. He's given me verbal permission to do so, but has no interest in active participation anymore. Getting the files from him directly seems unlikely.

Is there any way for us to restore and reopen this pull request?

答:
Is there any way for us to restore and reopen this pull request?

You can at least check out hos PR branch locally

```<code>git fetch origin pull/ID/head:BRANCHNAME
git switch BRANCHNAME
</code>```

(Rename BRANCHNAME with a local branch name which makes sense in your case)

From there you can:

push BRANCHNAME to your repository

open a new PR from there.

Body:
Is there any way for us to restore and reopen this pull request?

You can at least check out hos PR branch locally

git fetch origin pull/ID/head:BRANCHNAME
git switch BRANCHNAME

(Rename BRANCHNAME with a local branch name which makes sense in your case)

From there you can:

push BRANCHNAME to your repository

open a new PR from there.


问:
How to rotate 2D array of characters
I'm trying to rotate this clockwise 90 degrees, but it works not as expected. Must be something to do with pointers which I'm not that familiar.

OUTPUT Before Rotation:

```<code>hiivp
nxhxd
tszeg
xdlqo
kwpae

void rotate_right(char **m, int n) {
char **temp = m;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        m[i][j] = temp[n-1-j][i];
    }
}
</code>```

}

OUTPUT After Rotation:

```<code>kxtnk
wdsdx
plzst
aqsdn
entxk
</code>```

答:
Building on LSerni's answer, adding an implementation for completeness sake.

Assuming the following matrix:

```<code>#define STRING_SIZE     (5)

char m[][STRING_SIZE+1] = { "hiivp",
                            "nxhxd",
                            "tszeg",
                            "xdlqo",
                            "kwpae" };
</code>```

You can define the rotate function like this:

```<code>char override_and_backup(char* dest, char val)
{
    char tmp = *dest;
    *dest = val;

    return tmp;
}

void rotate_right(char m[][STRING_SIZE+1], int size)
{
    // rotate layer by layer
    for (int layer = 0; layer < (size / 2); ++layer)
    {
        int current_size = size - (2*layer);    // side size of current layer
        int ncycles = current_size - 1;         // number of cycles to complete rotation

        // perform the rotating cycles
        for (int cycle = 0; cycle < ncycles; ++cycle)
        {
            char* first  = &m[layer][layer+cycle];
            char* second = &m[layer+cycle][layer+current_size-1];
            char* third  = &m[layer+current_size-1][layer+current_size-cycle-1];
            char* fourth = &m[layer+current_size-cycle-1][layer];

            char tmp = *fourth;
            tmp = override_and_backup(first, tmp);
            tmp = override_and_backup(second, tmp);
            tmp = override_and_backup(third, tmp);
            override_and_backup(fourth, tmp);
        }
    }
}
</code>```

Title: How to rotate 2D array of characters

Body:
I'm trying to rotate this clockwise 90 degrees, but it works not as expected. Must be something to do with pointers which I'm not that familiar.

OUTPUT Before Rotation:

hiivp
nxhxd
tszeg
xdlqo
kwpae

void rotate_right(char **m, int n) {
char **temp = m;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        m[i][j] = temp[n-1-j][i];
    }
}

}

OUTPUT After Rotation:

kxtnk
wdsdx
plzst
aqsdn
entxk

Body:
Building on LSerni's answer, adding an implementation for completeness sake.

Assuming the following matrix:

#define STRING_SIZE     (5)

char m[][STRING_SIZE+1] = { "hiivp",
                            "nxhxd",
                            "tszeg",
                            "xdlqo",
                            "kwpae" };

You can define the rotate function like this:

char override_and_backup(char* dest, char val)
{
    char tmp = *dest;
    *dest = val;

    return tmp;
}

void rotate_right(char m[][STRING_SIZE+1], int size)
{
    // rotate layer by layer
    for (int layer = 0; layer < (size / 2); ++layer)
    {
        int current_size = size - (2*layer);    // side size of current layer
        int ncycles = current_size - 1;         // number of cycles to complete rotation

        // perform the rotating cycles
        for (int cycle = 0; cycle < ncycles; ++cycle)
        {
            char* first  = &m[layer][layer+cycle];
            char* second = &m[layer+cycle][layer+current_size-1];
            char* third  = &m[layer+current_size-1][layer+current_size-cycle-1];
            char* fourth = &m[layer+current_size-cycle-1][layer];

            char tmp = *fourth;
            tmp = override_and_backup(first, tmp);
            tmp = override_and_backup(second, tmp);
            tmp = override_and_backup(third, tmp);
            override_and_backup(fourth, tmp);
        }
    }
}


问:
how to remove eventhandler from bootstrap carousel indicator items
I am using bootstrap5 carousel, and I want to fire a custom event when the previous or next indicators are clicked.
I want to prevent the default bootstrap event from firing.   I have tried a bunch of different techniques, but with no success.

Does anyone know how to do this?

Mtia

答: Have you tried  e.stopPropagation() or e.stopImmediatePropagation()


问:
Boost::GIL bits8* to gray8_ptr_t without reinterpret_cast?
Trying to work by the design guidelines for GIL, I use bits__ for my channel data types. I often have external data I'm wrapping into GIL image views. However, even using the bits__ types for data pointers, I have to add in a reinterpret_cast before I can create my image views. Take the following code

```<code>int width = 3;
int height = 2;

boost::gil::bits8 data8[] = {0, 1, 100, 200, 50, 51};
boost::gil::bits8* pBits8 = data8;
boost::gil::gray8_ptr_t pGray8 = pBits8;

boost::gil::gray8_view_t v = interleaved_view(width, height, pGray8, width * sizeof(boost::gil::bits8));
</code>```

Results in the error on line 6 "error C2440: 'initializing' : cannot convert from 'boost::gil::bits8 *' to 'boost::gil::gray8_ptr_t'
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast"

Delving into the source code as much as I can, it appears these types really are unreleated. bits8 is just unsigned char, but gray8_ptr_t is a pointer to a struct pixel<bits8,gray_layout_t>. The only element of this struct is a single bits8, so a reinterpret_cast looks safe. It also works fine for the tests I've thrown at it.

However, I wrap external data into image views quite often, and having a reinterpret_cast in every place feels problematic. Is there a safer way of constructing a pixel pointer for use in GIL?

Current workaround:

```<code>template<class Dest, class Src>
Dest gil_safe_ptr_cast(Src src)
{
    // this cast is unsafe, use reinterpret_cast
    BOOST_STATIC_ASSERT(false);
}
template<> boost::gil::gray8_ptr_t gil_safe_ptr_cast(boost::gil::bits8* pBits8)
{
    return reinterpret_cast<boost::gil::gray8_ptr_t>(pBits8);
}
boost::gil::bits8* pBits8 = data8;
boost::gil::gray8_ptr_t pGray8 = gil_safe_ptr_cast<boost::gil::gray8_ptr_t>(pBits8); // works
boost::gil::bits16* pBits16 = NULL;
boost::gil::gray8_ptr_t pGray82 = gil_safe_ptr_cast<boost::gil::gray8_ptr_t>(pBits16); // compile error as expected
</code>```

Body:
Trying to work by the design guidelines for GIL, I use bits__ for my channel data types. I often have external data I'm wrapping into GIL image views. However, even using the bits__ types for data pointers, I have to add in a reinterpret_cast before I can create my image views. Take the following code

int width = 3;
int height = 2;

boost::gil::bits8 data8[] = {0, 1, 100, 200, 50, 51};
boost::gil::bits8* pBits8 = data8;
boost::gil::gray8_ptr_t pGray8 = pBits8;

boost::gil::gray8_view_t v = interleaved_view(width, height, pGray8, width * sizeof(boost::gil::bits8));

Results in the error on line 6 "error C2440: 'initializing' : cannot convert from 'boost::gil::bits8 *' to 'boost::gil::gray8_ptr_t'
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast"

Delving into the source code as much as I can, it appears these types really are unreleated. bits8 is just unsigned char, but gray8_ptr_t is a pointer to a struct pixel<bits8,gray_layout_t>. The only element of this struct is a single bits8, so a reinterpret_cast looks safe. It also works fine for the tests I've thrown at it.

However, I wrap external data into image views quite often, and having a reinterpret_cast in every place feels problematic. Is there a safer way of constructing a pixel pointer for use in GIL?

Current workaround:

template<class Dest, class Src>
Dest gil_safe_ptr_cast(Src src)
{
    // this cast is unsafe, use reinterpret_cast
    BOOST_STATIC_ASSERT(false);
}
template<> boost::gil::gray8_ptr_t gil_safe_ptr_cast(boost::gil::bits8* pBits8)
{
    return reinterpret_cast<boost::gil::gray8_ptr_t>(pBits8);
}
boost::gil::bits8* pBits8 = data8;
boost::gil::gray8_ptr_t pGray8 = gil_safe_ptr_cast<boost::gil::gray8_ptr_t>(pBits8); // works
boost::gil::bits16* pBits16 = NULL;
boost::gil::gray8_ptr_t pGray82 = gil_safe_ptr_cast<boost::gil::gray8_ptr_t>(pBits16); // compile error as expected


问:
If there is no mutual exclusion then how volatile ensures happens-before relationship?
I read over here that volatile doesn't entail mutual exclusion locking, then how volatile ensures happens-before relationship or how volatile ensures that other thread reads updated value?

Please note that I have read this and this but it doesn't answer my question which is specifically about volatile and these answers in these questions really doesn't explain the point I am curious about.

答:
Volatile ensure happens-before relationship by two mechanisms:

If a variable is marked as volatile, then JVM implementation has to ensure that its value is never cache in L1/L2/L3 caches of the processor. Value of a volatile variable must be immediately flushed to main memory. It is mentioned in JVM specification section 4.5.

Updates to volatile variable happens using compare-and-swap atomic instruction.


问:
verify azure active directory token using SubtleCrypto
I am trying to verify azure active directory ID and access tokens using the described flow in the ms docs. I am doing this in the browser. I know it's pointless to do it on the frontend. I still want to know how to do it. Just out of curiosity.

There is something similar on https://jwt.io/. It's meant to debug tokens. It can tell if a signature is valid or not.

In my code, the verification always fails. I am unsure If I am using SubtleCrypto correctly in this context. I am also unsure if I am choosing the right parameter for its functions, like the algorithm.

The header of the access token looks always something like this, using RS256.

{
  "typ": "JWT",
  "nonce": "<redacted>",
  "alg": "RS256",
  "x5t": "<redacted>",
  "kid": "<redacted>"
}
```
<p>The matched JWK looks like this.</p>
<pre class="lang-json prettyprint-override"><code>{
  "kty": "RSA",
  "use": "sig",
  "kid": "<redacted>",
  "x5t": "<redacted>",
  "n": "<redacted>",
  "e": "<redacted>",
  "x5c": ["<redacted>"]
}
</code>```

I have created this function to get the JWK using the issuer URL in the claims and kid property in the header, and eventually validate the signature. crypto.subtle.verify returns always false.

async function verifyToken(rawToken) {
  // parse the token into parts
  const [encodedHeaders, encodedClaims, signature] = rawToken.split(".");
  const header = JSON.parse(atob(encodedHeaders));
  const claims = JSON.parse(atob(encodedClaims));

  // get the openid config using the issuer url
  const issuer_url = claims.iss.endsWith("/") ? claims.iss : claims.iss + "/";
  const openIdConfiguration = await (
    await fetch(`${issuer_url}.well-known/openid-configuration`)
  ).json();

  // get the jwk list
  const jwkList = await (
    await fetch(openIdConfiguration.jwks_uri)
  ).json();

  // find the jwk for the kid in the token header
  const matchedKey = jwkList.keys.find(k => k.kid === header.kid)

  // return early if no jwk is found
  if (!matchedKey) return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
  };

  // import the jwk into a a crypto key
  const pubkey = await crypto.subtle.importKey(
    "jwk",
    matchedKey,
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    true,
    ["verify"],
  );

  // verify the signature
  const verified = await crypto.subtle.verify(
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    pubkey,
    new TextEncoder().encode(signature),
    new TextEncoder().encode(encodedHeaders + "." + encodedClaims),
  );

  // return the results
  return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
    matchedKey,
    verified
  };
};
```

答:
The three parts of the JWT are Base64url encoded, so a Base64url decoding of the signature is necessary (instead of a UTF8 encoding). I.e. the line new TextEncoder().encode(signature) must be replaced accordingly.

The sample data of the following code is taken from jwt.io for RS256:

const rawToken = `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.NHVaYe26MbtOYhSKkoKYdFVomg4i8ZJd8_-RU8VNbftc4TSMb4bXP3l3YlNWACwyXPGffz5aXHc6lty1Y2t4SWRqGteragsVdZufDn5BlnJl9pdR_kdVFUsra2rWKEofkZeIC4yWytE58sMIihvo9H1ScmmVwBcQP6XETqYd0aSHp1gOa9RdUPDvoXQ5oqygTqVtxaDr6wUFKrKItgBMzWIdNZ6y7O9E0DhEPTbE9rfBo6KTFsHAZnMg4k68CDp2woYIaXbmYTWcvbzIuHO7_37GT79XdIwkm95QJ7hYC9RiwrV7mesbY4PAahERJawntho0my942XheVLmGwLMBkQ`;

const [encodedHeaders, encodedClaims, signature] = rawToken.split(".");

const matchedKey =
{
"kty":"RSA",
"e":"AQAB",
"kid":"fa05e6ef-ec59-45b4-ba43-51b8293f7f79",
"n":"u1SU1LfVLPHCozMxH2Mo4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0_IzW7yWR7QkrmBL7jTKEn5u-qKhbwKfBstIs-bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyehkd3qqGElvW_VDL5AaWTg0nLVkjRo9z-40RQzuVaE8AkAFmxZzow3x-VJYKdjykkJ0iT9wCS0DRTXu269V264Vf_3jvredZiKRkgwlL9xNAwxXFg0x_XFw005UWVRIkdgcKWTjpBP2dPwVZ4WWC-9aGVd-Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbcmw"
};

(async () => {

    const pubkey = await crypto.subtle.importKey(
        "jwk",
        matchedKey,
        { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
        true,
        ["verify"],
    );

    // verify the signature
    const verified = await crypto.subtle.verify(
        { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
        pubkey,
        new base64url_decode(signature),
        new TextEncoder().encode(encodedHeaders + "." + encodedClaims),
    );

    console.log("Verification: ", verified);

})();

// Helper for Base64url encoding, from: https://thewoods.blog/base64url/
function base64url_decode(value) {
    const m = value.length % 4;
    return Uint8Array.from(atob(
        value.replace(/-/g, '+')
            .replace(/_/g, '/')
            .padEnd(value.length + (m === 0 ? 0 : 4 - m), '=')
    ), c => c.charCodeAt(0)).buffer;
}```

With this change, the verification is successful.

Body:
I am trying to verify azure active directory ID and access tokens using the described flow in the ms docs. I am doing this in the browser. I know it's pointless to do it on the frontend. I still want to know how to do it. Just out of curiosity.

There is something similar on https://jwt.io/. It's meant to debug tokens. It can tell if a signature is valid or not.

In my code, the verification always fails. I am unsure If I am using SubtleCrypto correctly in this context. I am also unsure if I am choosing the right parameter for its functions, like the algorithm.

The header of the access token looks always something like this, using RS256.

{
  "typ": "JWT",
  "nonce": "<redacted>",
  "alg": "RS256",
  "x5t": "<redacted>",
  "kid": "<redacted>"
}

The matched JWK looks like this.

{
  "kty": "RSA",
  "use": "sig",
  "kid": "<redacted>",
  "x5t": "<redacted>",
  "n": "<redacted>",
  "e": "<redacted>",
  "x5c": ["<redacted>"]
}

I have created this function to get the JWK using the issuer URL in the claims and kid property in the header, and eventually validate the signature. crypto.subtle.verify returns always false.

async function verifyToken(rawToken) {
  // parse the token into parts
  const [encodedHeaders, encodedClaims, signature] = rawToken.split(".");
  const header = JSON.parse(atob(encodedHeaders));
  const claims = JSON.parse(atob(encodedClaims));

  // get the openid config using the issuer url
  const issuer_url = claims.iss.endsWith("/") ? claims.iss : claims.iss + "/";
  const openIdConfiguration = await (
    await fetch(`${issuer_url}.well-known/openid-configuration`)
  ).json();

  // get the jwk list
  const jwkList = await (
    await fetch(openIdConfiguration.jwks_uri)
  ).json();

  // find the jwk for the kid in the token header
  const matchedKey = jwkList.keys.find(k => k.kid === header.kid)

  // return early if no jwk is found
  if (!matchedKey) return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
  };

  // import the jwk into a a crypto key
  const pubkey = await crypto.subtle.importKey(
    "jwk",
    matchedKey,
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    true,
    ["verify"],
  );

  // verify the signature
  const verified = await crypto.subtle.verify(
    { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
    pubkey,
    new TextEncoder().encode(signature),
    new TextEncoder().encode(encodedHeaders + "." + encodedClaims),
  );

  // return the results
  return {
    rawToken,
    header,
    claims,
    signature,
    openIdConfiguration,
    jwkList,
    matchedKey,
    verified
  };
};

Body:
The three parts of the JWT are Base64url encoded, so a Base64url decoding of the signature is necessary (instead of a UTF8 encoding). I.e. the line new TextEncoder().encode(signature) must be replaced accordingly.

The sample data of the following code is taken from jwt.io for RS256:

const rawToken = `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.NHVaYe26MbtOYhSKkoKYdFVomg4i8ZJd8_-RU8VNbftc4TSMb4bXP3l3YlNWACwyXPGffz5aXHc6lty1Y2t4SWRqGteragsVdZufDn5BlnJl9pdR_kdVFUsra2rWKEofkZeIC4yWytE58sMIihvo9H1ScmmVwBcQP6XETqYd0aSHp1gOa9RdUPDvoXQ5oqygTqVtxaDr6wUFKrKItgBMzWIdNZ6y7O9E0DhEPTbE9rfBo6KTFsHAZnMg4k68CDp2woYIaXbmYTWcvbzIuHO7_37GT79XdIwkm95QJ7hYC9RiwrV7mesbY4PAahERJawntho0my942XheVLmGwLMBkQ`;

const [encodedHeaders, encodedClaims, signature] = rawToken.split(".");

const matchedKey =
{
"kty":"RSA",
"e":"AQAB",
"kid":"fa05e6ef-ec59-45b4-ba43-51b8293f7f79",
"n":"u1SU1LfVLPHCozMxH2Mo4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0_IzW7yWR7QkrmBL7jTKEn5u-qKhbwKfBstIs-bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyehkd3qqGElvW_VDL5AaWTg0nLVkjRo9z-40RQzuVaE8AkAFmxZzow3x-VJYKdjykkJ0iT9wCS0DRTXu269V264Vf_3jvredZiKRkgwlL9xNAwxXFg0x_XFw005UWVRIkdgcKWTjpBP2dPwVZ4WWC-9aGVd-Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbcmw"
};

(async () => {

    const pubkey = await crypto.subtle.importKey(
        "jwk",
        matchedKey,
        { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
        true,
        ["verify"],
    );

    // verify the signature
    const verified = await crypto.subtle.verify(
        { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
        pubkey,
        new base64url_decode(signature),
        new TextEncoder().encode(encodedHeaders + "." + encodedClaims),
    );

    console.log("Verification: ", verified);

})();

// Helper for Base64url encoding, from: https://thewoods.blog/base64url/
function base64url_decode(value) {
    const m = value.length % 4;
    return Uint8Array.from(atob(
        value.replace(/-/g, '+')
            .replace(/_/g, '/')
            .padEnd(value.length + (m === 0 ? 0 : 4 - m), '=')
    ), c => c.charCodeAt(0)).buffer;
}

With this change, the verification is successful.


问:
GameCenter Social.localUser id uniqueness on Unity
Thanks to click my question.

I'm developing a game on Unity integrated with Google Play Games and Game Center.

Recently, i transferred my app into another developer's account on AppStore.

And it looks like that Social.localUser.id has been differentiated after transferring.

The problem is, i connected Social.localUser.id with account on database.

So when the Social.localUser.id become different, they can't find their own account.

I want to know how Social.localUser.id of Game Center decided.

Do they become different on app transfer?

What should i do to get old Social.localUser.id.

Thanks.

答:
The documentation states that the id comes from teamPlayerId.

The documentation for teamPlayerId states:

For the local player, this identifier is the same across all local player instances of your games that use the same developer Team ID.

So, the short answer is that if you transfer your app to a different developer team, you should expect to get different identifiers.  Unfortunately at this point there is nothing you can do, apart from, perhaps, try transferring it back.

If you had created and persisted your own unique identifier on device and on your server then you could match the new identifier to the old, but now it is too late.


问:
Creating a CloudWatch Metrics from the Athena Query results
My Requirement

I want to create a CloudWatch-Metric from Athena query results.

Example

I want to create a metric like user_count of each day.
In Athena, I will write an SQL query like this

```<code>select date,count(distinct user) as count from users_table group by 1
</code>```

In the Athena editor I can see the result, but I want to see these results as a metric in Cloudwatch.

```<code>CloudWatch-Metric-Name ==> user_count
Dimensions ==> Date,count
</code>```

If I have this cloudwatch metric and dimensions, I can easily create a Monitoring Dashboard and send send alerts

Can anyone suggest a way to do this?

答: You can use CloudWatch custom widgets, see "Run Amazon Athena queries" in Samples.</p>

Body:
My Requirement

I want to create a CloudWatch-Metric from Athena query results.

Example

I want to create a metric like user_count of each day.
In Athena, I will write an SQL query like this

select date,count(distinct user) as count from users_table group by 1

In the Athena editor I can see the result, but I want to see these results as a metric in Cloudwatch.

CloudWatch-Metric-Name ==> user_count
Dimensions ==> Date,count

If I have this cloudwatch metric and dimensions, I can easily create a Monitoring Dashboard and send send alerts

Can anyone suggest a way to do this?


问:
Do not inserting paragraphs where should be linebreaks when copying from word
I have a clueless person as editor on a wordpress site of mine. This person creates their text using MS Word (don't ask me why) they he proceeds to copy from word into Tiny MCE Editor on Wordpress.

His big complain is that everything that was linebreaks on word becomes paragraps on wordpress.

So a text that is like that on word...

```<code>The quick brown
fox jumps over
the lazy dog
</code>```

that should be pasted as

```<code><p>The quick brown<br>
fox jumps over<br>
the lazy dog</p>
</code>```

is pasted like

```<code><p>The quick brown</p>
<p>fox jumps over</p>
<p>the lazy dog</p>
</code>```

it that something that can be done to fix that? (No, he doesn't want to paste a clean text and having to reformat the whole thing).

答:
Well wpautop might be what you're looking for. Tho in your example there is no actual difference in the end result. 3 lines in both cases.

wpautop()

Replaces double line breaks with paragraph elements.

```<code><?php

remove_filter( 'the_content', 'wpautop' );
</code>```

Body:
I have a clueless person as editor on a wordpress site of mine. This person creates their text using MS Word (don't ask me why) they he proceeds to copy from word into Tiny MCE Editor on Wordpress.

His big complain is that everything that was linebreaks on word becomes paragraps on wordpress.

So a text that is like that on word...

The quick brown
fox jumps over
the lazy dog

that should be pasted as

The quick brown

fox jumps over

the lazy dog

is pasted like

The quick brown

fox jumps over

the lazy dog

it that something that can be done to fix that? (No, he doesn't want to paste a clean text and having to reformat the whole thing).

Body:
Well wpautop might be what you're looking for. Tho in your example there is no actual difference in the end result. 3 lines in both cases.

wpautop()

Replaces double line breaks with paragraph elements.

<?php

remove_filter( 'the_content', 'wpautop' );


问:
ASP.NET Web App CORE: the HttpPost Edit Method in Controller not being called
When i redirect to the Edit.cshtml page, only the HttpGet seems to be working. The HttpPost is not working. Which means that when I make changes and click on the Edit button on the Edit form, the HttpPost Edit is supposed to be invoked to call the PUT API. But the HttpGet Edit is called instead... What have I done wrong?

The HttpGet to retrieve the existing info

```<code>    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        await ViewBags();

        HttpResponseMessage response = await GlobalVariables.WebApiClient.GetAsync("article/detail/" + id.ToString());
        if (response.IsSuccessStatusCode)
        {
            var authorTagArticle = new AuthorTagArticle();
            authorTagArticle = response.Content.ReadAsAsync<AuthorTagArticle>().Result;
            var articleForm = new ArticleForm();
            articleForm.ArticleId = authorTagArticle.Article.ArticleId;
            articleForm.ArticleTitle = authorTagArticle.Article.ArticleTitle;
            articleForm.ArticleContent = authorTagArticle.Article.ArticleContent;
            articleForm.CreatedOn = authorTagArticle.Article.CreatedOn;
            articleForm.ImagePath = authorTagArticle.Article.ImagePath;
            articleForm.AuthorIds = authorTagArticle.Author.Select(e => e.UserId).ToArray();
            articleForm.TagIds = authorTagArticle.Tag.Select(e => e.TagId).ToArray();

            return View(articleForm);
        }
        else
        {
            TempData["error"] = "Error - Unable to open Edit Article Menu";
            return RedirectToAction("Index", "Home");
        }
    }
</code>```

The HttpPost Edit method: to call the PUT API

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ArticleForm articleForm)
{
    if (id != articleForm.ArticleId)
    {
        return NotFound();
    }

    //If Image is Updated
    var content = Request.Form.Files;
    const long MaxLength = 10485760; // 10MB
    string oldImagePath = articleForm.ImagePath;

    if (content.Count() > 0 && content.First().ContentType.Contains("image") && content.First().Length < MaxLength)
    {
        articleForm.ImagePath = "article/" + content.First().FileName;
    }
    else
    {
        ModelState.AddModelError("Image", "Please select a valid image less than 10MB");
    }

    if (ModelState.IsValid)
    {
        try
        {
            Article article = new Article();
            article.ArticleId = articleForm.ArticleId;
            article.ArticleTitle = articleForm.ArticleTitle;
            article.ArticleContent = articleForm.ArticleContent;
            article.CreatedOn = articleForm.CreatedOn;
            article.ImagePath = articleForm.ImagePath;

            HttpResponseMessage response = await GlobalVariables.WebApiClient.PutAsJsonAsync("article/edit/" + id, article);

            if (response.IsSuccessStatusCode)
            {
                TempData["success"] = "Article Updated!";
                return RedirectToAction("Index", "Article");
            }

            else
            {
                TempData["error"] = "Error - Unable to edit article!";
                return RedirectToAction("Index", "Home");
            }
        }
        catch (DbUpdateConcurrencyException) { }

    }
    return View(articleForm);
}
</code>```

Edit.cshtml

```<code>@model SCANews_UI.Models.ArticleForm

@{ ViewData["Title"] = "Edit"; }

<h1>Edit Article</h1>

<div class="card" style="width: 70rem;">
    <div class="card-body">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ArticleId" />
            <div class="form-group">
                <label asp-for="ArticleTitle" class="control-label"></label>
                <input asp-for="ArticleTitle" class="form-control">
                <span asp-validation-for="ArticleTitle" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ArticleContent" class="control-label"></label>
                <textarea asp-for="ArticleContent" id="testCK" class="form-control"></textarea>
                <span asp-validation-for="ArticleContent" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="ImagePath" class="control-label"></label>
                <br />
                <img style="max-width: 100%; height: 200px;" src="@Model.ImagePath" class="rounded img-thumbnail" alt="Article Image" id="existingImage">
                <input hidden asp-for="ImagePath" class="form-control" />
                <div class="custom-file">
                    <input type="file" asp-for="ImagePath" onchange="readURL(this)" class="custom-file-input form-control" name="Image" id="customFile">
                    <label class="custom-file-label" for="customFile">Choose file</label>
                </div>
                <span asp-validation-for="ImagePath" class="text-danger"></span>
                <!-- Uploaded image area-->
                <div class="image-area mt-4"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
            </div>
            <div class="form-group">
                <input type="submit" value="Edit" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/ckeditor/ckeditor.js"></script>

<script>
    var contentTextArea = document.getElementById("testCK")
    CKEDITOR.replace(contentTextArea);
</script>

<script type="text/javascript">
    $(".custom-file-input").on("change", function () {
        var fileName = $(this).val().split("\\").pop();
        $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
    });
</script>

<script>
    //Show Image
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imageResult')
                    .attr('src', e.target.result);
            };
            reader.readAsDataURL(input.files[0]);
        }
        var beforeImage = document.getElementById('existingImage');
        beforeImage.style.display = 'none';
    }

    $(function () {
        $('#customFile').on('change', function () {
            readURL(input);
        });
    });
</script>

<script type="text/javascript">
    //Show Image Name
    document.querySelector('.custom-file-input').addEventListener('change', function (e) {
        var name = document.getElementById("customFile").files[0].name;
        var nextSibling = e.target.nextElementSibling
        nextSibling.innerText = name
    })
</script>
</code>```

ArticleForm model

```<code>public class ArticleForm
{
    public int ArticleId { get; set; }

    [Required, Column(TypeName = "varchar(150)")]
    [DisplayName("Article Title")]
    public string ArticleTitle { get; set; }

    [Required, Column(TypeName = "text")]
    [DisplayName("Article Content")]
    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    [Column(TypeName = "text")]
    [DisplayName("Image")]
    public string ImagePath { get; set; }

    public int[] AuthorIds { get; set; }

    public int[] TagIds { get; set; }
}
</code>```

Article Model

```<code>public class Article
{
    public int ArticleId { get; set; }

    public string ArticleTitle { get; set; }

    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    public string ImagePath { get; set; }
}
</code>```

AuthorTagArticle Model

```<code>public class AuthorTagArticle
{
    public Article Article { get; set; }

    public List<User> Author { get; set; }

    public List<Tag> Tag { get; set; }
}
</code>```

GlobalVariables

```<code>public class GlobalVariables
{
    public static HttpClient WebApiClient = new HttpClient();

    static GlobalVariables()
    {
        //local testing
        WebApiClient.BaseAddress = new Uri("https://localhost:44361/api/");

        //lambda APIs

        WebApiClient.DefaultRequestHeaders.Clear();
        WebApiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    }
}
</code>```

答:
Try to edit your code as following: <form asp-controller="{Your controller}" asp-action="Edit" method="post">

Also you can read some info about Tag Helpers here

Body:
When i redirect to the Edit.cshtml page, only the HttpGet seems to be working. The HttpPost is not working. Which means that when I make changes and click on the Edit button on the Edit form, the HttpPost Edit is supposed to be invoked to call the PUT API. But the HttpGet Edit is called instead... What have I done wrong?

The HttpGet to retrieve the existing info

    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        await ViewBags();

        HttpResponseMessage response = await GlobalVariables.WebApiClient.GetAsync("article/detail/" + id.ToString());
        if (response.IsSuccessStatusCode)
        {
            var authorTagArticle = new AuthorTagArticle();
            authorTagArticle = response.Content.ReadAsAsync<AuthorTagArticle>().Result;
            var articleForm = new ArticleForm();
            articleForm.ArticleId = authorTagArticle.Article.ArticleId;
            articleForm.ArticleTitle = authorTagArticle.Article.ArticleTitle;
            articleForm.ArticleContent = authorTagArticle.Article.ArticleContent;
            articleForm.CreatedOn = authorTagArticle.Article.CreatedOn;
            articleForm.ImagePath = authorTagArticle.Article.ImagePath;
            articleForm.AuthorIds = authorTagArticle.Author.Select(e => e.UserId).ToArray();
            articleForm.TagIds = authorTagArticle.Tag.Select(e => e.TagId).ToArray();

            return View(articleForm);
        }
        else
        {
            TempData["error"] = "Error - Unable to open Edit Article Menu";
            return RedirectToAction("Index", "Home");
        }
    }

The HttpPost Edit method: to call the PUT API

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ArticleForm articleForm)
{
    if (id != articleForm.ArticleId)
    {
        return NotFound();
    }

    //If Image is Updated
    var content = Request.Form.Files;
    const long MaxLength = 10485760; // 10MB
    string oldImagePath = articleForm.ImagePath;

    if (content.Count() > 0 && content.First().ContentType.Contains("image") && content.First().Length < MaxLength)
    {
        articleForm.ImagePath = "article/" + content.First().FileName;
    }
    else
    {
        ModelState.AddModelError("Image", "Please select a valid image less than 10MB");
    }

    if (ModelState.IsValid)
    {
        try
        {
            Article article = new Article();
            article.ArticleId = articleForm.ArticleId;
            article.ArticleTitle = articleForm.ArticleTitle;
            article.ArticleContent = articleForm.ArticleContent;
            article.CreatedOn = articleForm.CreatedOn;
            article.ImagePath = articleForm.ImagePath;

            HttpResponseMessage response = await GlobalVariables.WebApiClient.PutAsJsonAsync("article/edit/" + id, article);

            if (response.IsSuccessStatusCode)
            {
                TempData["success"] = "Article Updated!";
                return RedirectToAction("Index", "Article");
            }

            else
            {
                TempData["error"] = "Error - Unable to edit article!";
                return RedirectToAction("Index", "Home");
            }
        }
        catch (DbUpdateConcurrencyException) { }

    }
    return View(articleForm);
}

Edit.cshtml

@model SCANews_UI.Models.ArticleForm

@{ ViewData["Title"] = "Edit"; }

Edit Article

        <form asp-action="Create" enctype="multipart/form-data">

            <input type="hidden" asp-for="ArticleId" />

                <input asp-for="ArticleTitle" class="form-control">

                <textarea asp-for="ArticleContent" id="testCK" class="form-control"></textarea>

                <input hidden asp-for="ImagePath" class="form-control" />

                    <input type="file" asp-for="ImagePath" onchange="readURL(this)" class="custom-file-input form-control" name="Image" id="customFile">
                    Choose file

                <input type="submit" value="Edit" class="btn btn-primary" />

        </form>

ArticleForm model

public class ArticleForm
{
    public int ArticleId { get; set; }

    [Required, Column(TypeName = "varchar(150)")]
    [DisplayName("Article Title")]
    public string ArticleTitle { get; set; }

    [Required, Column(TypeName = "text")]
    [DisplayName("Article Content")]
    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    [Column(TypeName = "text")]
    [DisplayName("Image")]
    public string ImagePath { get; set; }

    public int[] AuthorIds { get; set; }

    public int[] TagIds { get; set; }
}

Article Model

public class Article
{
    public int ArticleId { get; set; }

    public string ArticleTitle { get; set; }

    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    public string ImagePath { get; set; }
}

AuthorTagArticle Model

public class AuthorTagArticle
{
    public Article Article { get; set; }

    public List<User> Author { get; set; }

    public List<Tag> Tag { get; set; }
}

GlobalVariables

public class GlobalVariables
{
    public static HttpClient WebApiClient = new HttpClient();

    static GlobalVariables()
    {
        //local testing
        WebApiClient.BaseAddress = new Uri("https://localhost:44361/api/");

        //lambda APIs

        WebApiClient.DefaultRequestHeaders.Clear();
        WebApiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    }
}


问:
Drag vs link modes in GoJS
Is it possible to explicitly switch between dragging and linking modes in GoJS? I am trying to achieve a behavior similar to other diagram editors out there:

Have 2 buttons in a toolbar outside of the diagram: an Link and a Hand.

Clicking on Link button switches diagram into linking mode. Clicking any part of any node initiates LinkingTool on that node so it can be linked to another node. Node dragging is disabled.

Clicking on Hand button switches diagram into dragging mode. Now mouse click on any node initiates DraggingTool, ResizingTool etc., anything but LinkingTool.

I believe I've seen such example but now cannot find it after couple hours of searching. An attempt to set diagram.toolManager.xxxTool.enabled to "false" in JavaScript does not seem to have any effect on tool activation behavior.

答:
I suspect your problem is just a typo, the property is isEnabled, not enabled.

For completeness: First you must set fromLinkable: true, toLinkable:true (or at least one) on your Node or port to enable the linking tool. Then you can conditionally disable the tool via your button:

myDiagram.toolManager.linkingTool.isEnabled = false; // false to drag, true to link
```

You can actually write that line in the console and see it live on a sample like Basic

Title: Drag vs link modes in GoJS

Body:
I suspect your problem is just a typo, the property is isEnabled, not enabled.

For completeness: First you must set fromLinkable: true, toLinkable:true (or at least one) on your Node or port to enable the linking tool. Then you can conditionally disable the tool via your button:

myDiagram.toolManager.linkingTool.isEnabled = false; // false to drag, true to link

You can actually write that line in the console and see it live on a sample like Basic


问:
MWMCR::EvaluateFunction Error - Cannot find mwvision_builtinimpl.dll when calling MATLAB function from ASP.NET
I am getting the below error when calling my MATLAB function from ASP.NET. I compiled my function using the library compiler and have added the dll as an assembly to my ASP project. See error -

... MWMCR::EvaluateFunction error ...
Loading C:\Program Files\MATLAB\R2021b\bin\win64\builtins\vision_builtins\mwvision_builtinimpl.dll failed with error: The specified procedure could not be found.
: state not recoverable: state not recoverable.

My MATLAB function includes functions from the Computer Vision Toolbox and the Statistics + ML toolbox. These functions are: base64decoder, bagOfFeatures, imread, predict. From what I have read these functions should be compliable.

Am I missing a step during the compilations to add the built in functions? Any suggestions would be great!

答:
So, that "MWMCR" error is coming from the Matlab Runtime, which is the "headless" Matlab runtime library that executes "compiled" Matlab code. ("MWMCR" stands for "MathWorks Matlab Component Runtime", the old name for the Matlab Runtime.) But that path to C:\Program Files\MATLAB\R2021b\bin\win64\builtins\vision_builtins\mwvision_builtinimpl.dll is the path to the regular Matlab installation's Vision Toolbox.

You'll probably need to modify your ASP project to reference the library in its location in the Matlab Runtime, such that at run time it tries to load and call it from there instead of regular Matlab. Not sure exactly how to do that with ASP.NET.

It seems unusual to have your ASP.NET custom code directly referencing a Matlab Toolbox DLL. Do you really need to do that? Usually one has your M-code call normal Matlab Toolbox M-code-level functions, and rely on the Matlab or Matlab runtime execution engines to link to the toolbox's internal DLLs.


问:
How to format selected/copied html content without javascript?
In my particular case, I have a reusable component that displays a formatted weight (e.g. "12 kg 560 g").

The html that makes that up exists in DOM without any whitespace.  But when formatted looks something like:

  12
  kg
  560
  g

```

That gets styled with CSS to add spacing to what's rendered.  But when I copy that text from chrome and paste it as text, it comes out as "12kg560g".

I'm aware I can add whitespace to solve this particular issue, but what if I want an entirely alternate representation?  For example: "12 KG. 560 G. (123.123 LBS.)".

The img tag has the alt attribute which browsers treat as the text representation.  Why isn't this a global attribute? Is there any way (without using javascript) to help the browser format the selected elements when copied?

Edit: After reviewing the html spec and thinking on this, it's pretty safe to say it's not possible.  Selecting arbitrary portions of a web page and copying/pasting as text just sucks

答:
This should work, set the clipboard event data.
More info: How to add extra info to copied web text

function changeContent(elem, content) {
  elem.addEventListener("copy", evt => {
    evt.clipboardData.setData("text/html", content(elem.innerHTML));
    evt.preventDefault();
  });
}

changeContent(document.querySelector("p"), content => `${content} foo bar 123 abcd <br> more multiline stuff <br> <h1> html yay </h1>`);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 1px solid black;
}</code>```

Test copy content

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Try to paste here

```

Body:
In my particular case, I have a reusable component that displays a formatted weight (e.g. "12 kg 560 g").

The html that makes that up exists in DOM without any whitespace.  But when formatted looks something like:

  12
  kg
  560
  g

That gets styled with CSS to add spacing to what's rendered.  But when I copy that text from chrome and paste it as text, it comes out as "12kg560g".

I'm aware I can add whitespace to solve this particular issue, but what if I want an entirely alternate representation?  For example: "12 KG. 560 G. (123.123 LBS.)".

The img tag has the alt attribute which browsers treat as the text representation.  Why isn't this a global attribute? Is there any way (without using javascript) to help the browser format the selected elements when copied?

Edit: After reviewing the html spec and thinking on this, it's pretty safe to say it's not possible.  Selecting arbitrary portions of a web page and copying/pasting as text just sucks

Body:
This should work, set the clipboard event data.
More info: How to add extra info to copied web text

function changeContent(elem, content) {
  elem.addEventListener("copy", evt => {
    evt.clipboardData.setData("text/html", content(elem.innerHTML));
    evt.preventDefault();
  });
}

changeContent(document.querySelector("p"), content => `${content} foo bar 123 abcd <br> more multiline stuff <br> <h1> html yay </h1>`);

div {
  border: 1px solid black;
}

<h1>Test copy content</h1>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h1>Try to paste here</h1>
<div contenteditable></div>


问:
How to remove intersecting String[] arrays from a nested ArrayList of String arrays?
Lets say i have an
ArrayList<ArrayList<String[]>> variable named ListToProcess where in each arrayList i have the following ArrayLists of String[]:

```<code>    String[] arr1 = {"1","2","3"};
    String[] arr2 = {"7","5","3"};
    String[] arr3 = {"8","2","6"};
    String[] arr4 = {"0","4","9"};
</code>```

ArrayList<String[]> arrString1 contains arr1 and arr2 and ArrayList<String[]> arrString1 constains arr3 and arr4
I want to process ListToProcess in such a way that removes arr2 & arr3 since intersect with arr1(or keep arr2and remove arr1 and arr3...) from it.
I try through flattening ListToProcess to a List<String[]> and remove intersecting elements through the below method removeIntersectingArrays

```<code>    List<String[]> flatList =
            partitionsOfClustersIds.stream()
                    .flatMap(ListToProcess::stream)
                    .collect(Collectors.toList());
    ArrayList<String[]> flattenedArrayElements=  new ArrayList<String[]>(flatList);
    flattenedArrayElements= removeIntersectingArrays(flattenedArrayElements);
</code>```

The removeIntersectingArrays method is the following :

```<code>Public static ArrayList<String[]> removeIntersectingArrays(ArrayList<String[]> totalArrays) {
        List<Integer> idx = new ArrayList<Integer>();
        for (int i = 0; i < totalArrays.size(); i++)
            for (int j = i + 1; j < totalArrays.size(); j++) {
                String[] tmpArr = totalArrays.get(j);
                if (Arrays.stream(totalArrays.get(i)).distinct().filter(x -> Arrays.stream(tmpArr).anyMatch(y -> y.equals(x))).toArray().length != 0) {

                    idx.add(j);
                }
            }
        Collections.reverse(idx);
        for (int k : idx)
            totalArrays.remove(k); // this line raises an indexOutOfBound exception
        return totalArrays;
    }
</code>```

But i get and indexOutOfBound error, any idea how to fix this ?

答:
Don't use concrete implementation (like ArrayList) instead of abstractions (like List) when it doesn't buy you anything. And that is often the case, the only exception is when you need to be able to invoke methods that are not defined in the List interface and only accessible through ArrayList class like ensureCapacity() or trimToSize().

Side note:

Collectors.toList() uses ArrayList as implementation of the List interface by default;

whenever you need a specific implementation use of Collector.toCollection().

The time complexity of the removeIntersectingArrays() method is reduced by maintaining a HashSet which stores strings from all the arrays that are encountered before. And every array has to be checked against this set.

```<code>    public static void main(String[] args) {
        List<List<String[]>> list= List.of(
                List.of(new String[]{"1","2","3"},
                        new String[]{"7","5","3"}),
                List.of(new String[]{"8","2","6"},
                        new String[]{"0","4","9"})
        );

        List<String[]> flatList = flatten(list);

        for (String[] arr: removeIntersectingArrays(flatList)) {
            System.out.println(Arrays.toString(arr));
        }
    }
</code>```
```<code>    public static List<String[]> flatten(List<List<String[]>> source) {
        return source.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }
</code>```
```<code>    public static List<String[]> removeIntersectingArrays(List<String[]> source) {
        List<String[]> result = new ArrayList<>();
        Set<String> seen = new HashSet<>();
        for (String[] arr: source) {
            boolean notSeenPreviously = true;
            for (String next: arr) {
                if (seen.contains(next)) {
                    notSeenPreviously = false;
                    break;
                }
            }
            if (notSeenPreviously) {
                result.add(arr);
                Collections.addAll(seen, arr);
            }
        }
        return result;
    }
</code>```

output (arr2 & arr3 are removed)

```<code>[1, 2, 3]
[0, 4, 9]
</code>```

Body:
Lets say i have an
ArrayList<ArrayList<String[]>> variable named ListToProcess where in each arrayList i have the following ArrayLists of String[]:

    String[] arr1 = {"1","2","3"};
    String[] arr2 = {"7","5","3"};
    String[] arr3 = {"8","2","6"};
    String[] arr4 = {"0","4","9"};

ArrayList<String[]> arrString1 contains arr1 and arr2 and ArrayList<String[]> arrString1 constains arr3 and arr4
I want to process ListToProcess in such a way that removes arr2 & arr3 since intersect with arr1(or keep arr2and remove arr1 and arr3...) from it.
I try through flattening ListToProcess to a List<String[]> and remove intersecting elements through the below method removeIntersectingArrays

    List<String[]> flatList =
            partitionsOfClustersIds.stream()
                    .flatMap(ListToProcess::stream)
                    .collect(Collectors.toList());
    ArrayList<String[]> flattenedArrayElements=  new ArrayList<String[]>(flatList);
    flattenedArrayElements= removeIntersectingArrays(flattenedArrayElements);

The removeIntersectingArrays method is the following :

Public static ArrayList<String[]> removeIntersectingArrays(ArrayList<String[]> totalArrays) {
        List<Integer> idx = new ArrayList<Integer>();
        for (int i = 0; i < totalArrays.size(); i++)
            for (int j = i + 1; j < totalArrays.size(); j++) {
                String[] tmpArr = totalArrays.get(j);
                if (Arrays.stream(totalArrays.get(i)).distinct().filter(x -> Arrays.stream(tmpArr).anyMatch(y -> y.equals(x))).toArray().length != 0) {

                    idx.add(j);
                }
            }
        Collections.reverse(idx);
        for (int k : idx)
            totalArrays.remove(k); // this line raises an indexOutOfBound exception
        return totalArrays;
    }

But i get and indexOutOfBound error, any idea how to fix this ?

Body:
Don't use concrete implementation (like ArrayList) instead of abstractions (like List) when it doesn't buy you anything. And that is often the case, the only exception is when you need to be able to invoke methods that are not defined in the List interface and only accessible through ArrayList class like ensureCapacity() or trimToSize().

Side note:

Collectors.toList() uses ArrayList as implementation of the List interface by default;

whenever you need a specific implementation use of Collector.toCollection().

The time complexity of the removeIntersectingArrays() method is reduced by maintaining a HashSet which stores strings from all the arrays that are encountered before. And every array has to be checked against this set.

    public static void main(String[] args) {
        List<List<String[]>> list= List.of(
                List.of(new String[]{"1","2","3"},
                        new String[]{"7","5","3"}),
                List.of(new String[]{"8","2","6"},
                        new String[]{"0","4","9"})
        );

        List<String[]> flatList = flatten(list);

        for (String[] arr: removeIntersectingArrays(flatList)) {
            System.out.println(Arrays.toString(arr));
        }
    }

    public static List<String[]> flatten(List<List<String[]>> source) {
        return source.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }

    public static List<String[]> removeIntersectingArrays(List<String[]> source) {
        List<String[]> result = new ArrayList<>();
        Set<String> seen = new HashSet<>();
        for (String[] arr: source) {
            boolean notSeenPreviously = true;
            for (String next: arr) {
                if (seen.contains(next)) {
                    notSeenPreviously = false;
                    break;
                }
            }
            if (notSeenPreviously) {
                result.add(arr);
                Collections.addAll(seen, arr);
            }
        }
        return result;
    }

output (arr2 & arr3 are removed)

[1, 2, 3]
[0, 4, 9]


问:
pvk2pfx.exe - can not find
Could tell me where to find the file pvk2pfx.exe?
It is supposed to be located in <programfile>/Visual Studio 8/Common7/Tools/bin/pvk2pfx.exe, but not on my machine.
I don't seem to be able to find it online either. I tried installing the SDK, but it didn't work.

答: You can also run the "Developer Powershell for VS 2022" (or the latest equivalent) and it will already know where to look.</p>

Title: pvk2pfx.exe - can not find


问:
Can I get git stat to show me proper-lines-of-code?
The git stat subcommand (or git log --stat etc.) shows us the numbers of lines added and removed. This is obviously useful, but - sometimes you don't care about whitespace and comment additions and removals.

Is it possible to get git to compute its addition and removal statistics - for display purposes only naturally - other than as lines removed and added? e.g. perhaps run something like cloc on the relevant files?

答:
You would not be able to use native Git commands.

Only a third-party could have that kind of additional feature, like cloc you mention.

It was used here, with two checkouts (one for each commits).


问:
How to gather score values from perspective api in python?
I have this JSON data:

```<code>{
  "attributeScores": {
    "SEXUALLY_EXPLICIT": {
      "spanScores": [
        {
          "begin": 0,
          "end": 12,
          "score": {
            "value": 0.058843683,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.058843683,
        "type": "PROBABILITY"
      }
    },
    "IDENTITY_ATTACK_EXPERIMENTAL": {
      "spanScores": [
        {
          "begin": 0,
          "end": 12,
          "score": {
            "value": 0.012206113,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.012206113,
        "type": "PROBABILITY"
      }
    }
  },
  "languages": [
    "en"
  ],
  "detectedLanguages": [
    "en"
  ]
}
</code>```

How can I extract the score values from this data, such as this?

```<code>value1 = 0.058843683
value2 = 0.012206113
</code>```

答:
Well, I don't know how you identify if it is toxic, but you can get those values through:</p>
```<code>for k,v in data['attributeScores'].items():
    print( k, v['summaryScore']['value'] )
</code>```

Body:
I have this JSON data:

{
  "attributeScores": {
    "SEXUALLY_EXPLICIT": {
      "spanScores": [
        {
          "begin": 0,
          "end": 12,
          "score": {
            "value": 0.058843683,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.058843683,
        "type": "PROBABILITY"
      }
    },
    "IDENTITY_ATTACK_EXPERIMENTAL": {
      "spanScores": [
        {
          "begin": 0,
          "end": 12,
          "score": {
            "value": 0.012206113,
            "type": "PROBABILITY"
          }
        }
      ],
      "summaryScore": {
        "value": 0.012206113,
        "type": "PROBABILITY"
      }
    }
  },
  "languages": [
    "en"
  ],
  "detectedLanguages": [
    "en"
  ]
}

How can I extract the score values from this data, such as this?

value1 = 0.058843683
value2 = 0.012206113

Body:
Well, I don't know how you identify if it is toxic, but you can get those values through:

for k,v in data['attributeScores'].items():
    print( k, v['summaryScore']['value'] )


问:
for loop IR generation in Bison
Consider the following grammar rule:

```<code>forstmt: for openparentheses nexpr semicolon expr semicolon nexpr closeparentheses stmt {}

nexpr: expr { }
    | %empty { }

expr: .
      .
      .
      // something huge
      .
      .
      .
</code>```

It is a parser rul for a for loop like below (a usual C like for loop):

```<code>for(i=0; i<10; i++){
    Print("hello world");
}
</code>```

I got to generate IR for this C like for loop (forstmt).

The IR for expr is already written.

The point is that the last nexpr's IR should go after the stmt.

I know about mid-rule actions and I thought that somehow I could solve this using a stack, but my thoughts didn't lead to any conclusions.

Precisely is there a way to stop bison from generating IR for the last nexpr and make it generate after the stmt ?

In other words, how to make all action of the last nexpr go after the stmt ?

Has anyone had a problem like this ?

答:
Generally you generate IR (internal represention) in memory, so you can manipulate it after you're parsed your program, which allows you to analyse the whole program and reorder things as you see fit.  So the order in which you generate the IR is irrelevant.

If you are instead trying to generate code directly in your actions as they are parsed, you need to set things up so that that works, generally by branching around.  So you might do something like:

```<code>forexpr:
    FOR '(' expr ';' {
        $$.l1 = create_label();   // creates a unique label
        output_label($$.l1);  // the label is at this point in the code
    } expr ';' {
        $$.l1 = create_label();
        $$.l2 = create_label();
        $$.l3 = create_lable();
        output_jump_if_true($6, $$.l1);  // conditional branch
        output_jump($$.l2);              // unconditional branch
        output_label($$.l3);
    } expr ')' {
        output_jump($5.l1);
        output_label($8.l1);
    } stmt {
        output_jump($8.l3);
        output_label($8.l2);
    }
</code>```

Needless to say, this is quite suboptimal.

Title: for loop IR generation in Bison

Body:
Consider the following grammar rule:

forstmt: for openparentheses nexpr semicolon expr semicolon nexpr closeparentheses stmt {}

nexpr: expr { }
    | %empty { }

expr: .
      .
      .
      // something huge
      .
      .
      .

It is a parser rul for a for loop like below (a usual C like for loop):

for(i=0; i<10; i++){
    Print("hello world");
}

I got to generate IR for this C like for loop (forstmt).

The IR for expr is already written.

The point is that the last nexpr's IR should go after the stmt.

I know about mid-rule actions and I thought that somehow I could solve this using a stack, but my thoughts didn't lead to any conclusions.

Precisely is there a way to stop bison from generating IR for the last nexpr and make it generate after the stmt ?

In other words, how to make all action of the last nexpr go after the stmt ?

Has anyone had a problem like this ?

Body:
Generally you generate IR (internal represention) in memory, so you can manipulate it after you're parsed your program, which allows you to analyse the whole program and reorder things as you see fit.  So the order in which you generate the IR is irrelevant.

If you are instead trying to generate code directly in your actions as they are parsed, you need to set things up so that that works, generally by branching around.  So you might do something like:

forexpr:
    FOR '(' expr ';' {
        $$.l1 = create_label();   // creates a unique label
        output_label($$.l1);  // the label is at this point in the code
    } expr ';' {
        $$.l1 = create_label();
        $$.l2 = create_label();
        $$.l3 = create_lable();
        output_jump_if_true($6, $$.l1);  // conditional branch
        output_jump($$.l2);              // unconditional branch
        output_label($$.l3);
    } expr ')' {
        output_jump($5.l1);
        output_label($8.l1);
    } stmt {
        output_jump($8.l3);
        output_label($8.l2);
    }

Needless to say, this is quite suboptimal.


问:
react typescript how to correctly type a SetStateAction
https://codesandbox.io/s/dazzling-gates-ruxzr?file=/src/TodoAdder.tsx

so I have a simple todo app and I am tying to type the action that update the state of the todos, I am getting the following error , the error does not happen if I change my Todo type declaration to string instead of o union.
is this happening because of the union type on my Todo interface, I notice that error disappears when i use a String for my status object proprety

```<code>export type Todo ={
    name: String;
    id: Number;
    status: 'Created' | 'Completed' | 'Archived';
}
</code>```

答:
Just set a type for payload:

const payload: Todo = {
```

Body:
https://codesandbox.io/s/dazzling-gates-ruxzr?file=/src/TodoAdder.tsx

so I have a simple todo app and I am tying to type the action that update the state of the todos, I am getting the following error , the error does not happen if I change my Todo type declaration to string instead of o union.
is this happening because of the union type on my Todo interface, I notice that error disappears when i use a String for my status object proprety

export type Todo ={
    name: String;
    id: Number;
    status: 'Created' | 'Completed' | 'Archived';
}


答:
The magic happens in hardware: Most modern processor architectures have special memory barrier instructions that user-mode programs can use to ensure the consistency of memory operations as seen by different CPUs when it is important.

Enforcing memory consistency is expensive. If the caches had to always contain consistent data, programs would run much more slowly. The purpose of the memory barrier instructions is to mark the parts of the program where consistency really matters, and outside of those code regions, the CPUs are free to cache data independently of each other.

Reading and writing any volatile variable causes your program to execute memory barrier instructions that force the hardware to obey the "happens before" requirements (the memory consistency model) laid out by the Java Language Spec. And, locking and unlocking any mutex also causes your program to execute the same or similar instructions.

Title: If there is no mutual exclusion then how volatile ensures happens-before relationship?

Body:
I read over here that volatile doesn't entail mutual exclusion locking, then how volatile ensures happens-before relationship or how volatile ensures that other thread reads updated value?

Please note that I have read this and this but it doesn't answer my question which is specifically about volatile and these answers in these questions really doesn't explain the point I am curious about.


问:
React doesn't show errors in terminal and browser
I've created a new app with react-create-app.
Here's my code:

```<code>function App() {
  let m;
  console.log(m); // undefined
  console.log(m.prop); // should throw an error
  return (
    <div className="App">
        App
    </div>
  );
}
</code>```

My app compiles successfully and I can see this error only in the chrome devtools console, but not in the IDE terminal or in the browser's page. Browser shows me an empty page, how can I change this behavior?

答:
You can use - try catch -, and if something happen you could render the text of the error in the browser.

Example:

```<code>function App() {
  let m;
  console.log(m); // undefined
  try {
    console.log(m.prop); // should throw an error
  } catch (e) {
    return (<h1>{e.toString()}</h1>);
  }
  return (
    <div className="App">
        App
    </div>
  );
}
</code>```

or

```<code>function App() {
  const [error, setError] = React.useState();
  let m;
  console.log(m); // undefined
  try {
    console.log(m.prop); // should throw an error
  } catch (e) {
    setError(e.toString());
  }
  return (
    <div className="App">
        App
        { error && <h1>{error}</h1> }
    </div>
  );
}
</code>```

Body:
I've created a new app with react-create-app.
Here's my code:

function App() {
  let m;
  console.log(m); // undefined
  console.log(m.prop); // should throw an error
  return (

        App

  );
}

My app compiles successfully and I can see this error only in the chrome devtools console, but not in the IDE terminal or in the browser's page. Browser shows me an empty page, how can I change this behavior?

Body:
You can use - try catch -, and if something happen you could render the text of the error in the browser.

Example:

function App() {
  let m;
  console.log(m); // undefined
  try {
    console.log(m.prop); // should throw an error
  } catch (e) {
    return (<h1>{e.toString()}</h1>);
  }
  return (
    <div className="App">
        App
    </div>
  );
}

or

function App() {
  const [error, setError] = React.useState();
  let m;
  console.log(m); // undefined
  try {
    console.log(m.prop); // should throw an error
  } catch (e) {
    setError(e.toString());
  }
  return (
    <div className="App">
        App
        { error && <h1>{error}</h1> }
    </div>
  );
}


问:
Command pabot not found in docker version of Robotframework browser
I'm trying to run Pabot / robot framework-browser script in Docker.

I have tryed to use command:

```<code>docker run --rm -v "$(pwd):/test" --ipc=host --user pwuser --security-opt seccomp=Docker/seccomp_profile.json -e "enviroment=***" -e "ROBOT_THREADS=10" -e PABOT_OPTIONS="--testlevelsplit" marketsquare/robotframework-browser:latest bash -c "pabot . -i smoke --outputdir /test/output /test"
</code>```

Result:  bash: pabot: command not found

Whats wrong in that syntax??
If i use "robot -i Smoke --outputdir /test/output /test"" then execution works ok (no errors).

答:
I checked and confirmed that the image does not have pabot installed. You can build an image locally with docker build -f Dockerfile ..

Here is an example of the execution with that image, but installing missing dependencies:

```<code>sudo docker run --rm -v $(pwd)/atest:/atest -v /tmp:/tmp -e "ROBOT_THREADS=10" -e PABOT_OPTIONS="--testlevelsplit" --ipc=host --user pwuser --security-opt seccomp=seccomp_profile.json marketsquare/robotframework-browser:latest bash -c "pip install robotframework-pabot psutil && pabot --outputdir /tmp/test/output atest/test"
</code>```

Body:
I'm trying to run Pabot / robot framework-browser script in Docker.

I have tryed to use command:

docker run --rm -v "$(pwd):/test" --ipc=host --user pwuser --security-opt seccomp=Docker/seccomp_profile.json -e "enviroment=***" -e "ROBOT_THREADS=10" -e PABOT_OPTIONS="--testlevelsplit" marketsquare/robotframework-browser:latest bash -c "pabot . -i smoke --outputdir /test/output /test"

Result:  bash: pabot: command not found

Whats wrong in that syntax??
If i use "robot -i Smoke --outputdir /test/output /test"" then execution works ok (no errors).

Body:
I checked and confirmed that the image does not have pabot installed. You can build an image locally with docker build -f Dockerfile ..

Here is an example of the execution with that image, but installing missing dependencies:

sudo docker run --rm -v $(pwd)/atest:/atest -v /tmp:/tmp -e "ROBOT_THREADS=10" -e PABOT_OPTIONS="--testlevelsplit" --ipc=host --user pwuser --security-opt seccomp=seccomp_profile.json marketsquare/robotframework-browser:latest bash -c "pip install robotframework-pabot psutil && pabot --outputdir /tmp/test/output atest/test"


问:
postgresql: how can i create a new server in postgres addational to another server?
I have a server in my postgres and I want to develop a new project, for that project I want to create a new server, and I didn't seccess, How can I do that?</p>

答:
Your question is somewhat ambiguous but hopefully this will help. You either want one of two things, a new database on the same instance/server or a new instance/server entirely. I"m assuming they are running on the same box.

You can issue a create database command on a running database and you will have a separate one. This share the same instance as any existing databases you have running. You would connect with psql -d [databasename] -h host -p port

create database docs

or

You create a new instance with the initdb command, change the config to use a different port. This way you can have more than one instance running on the same box. You would connect as above just changing the port number.

initdb from the docs

postgresql.conf examplefile


问:
Add script according to architecture in electron NSIS
I have an electron app that includes a NSIS script to install an extra app during the installation. But that app has different exe files for 32bit and 64bit. So how can I mention which exe to include in the installer. So can I mention which nsh file to include according to version or select file to be included in the nsh script.</p>

答:
In normal NSIS you would just do

```<code>!include x64.nsh

Section
SetOutPath $InstDir
${If} ${IsNativeAMD64}
  File x64\myapp.exe
${Else}
  File x86\myapp.exe
${EndIf}
SectionEnd
</code>```

I don't know anything about elecron-builder.

Body:
In normal NSIS you would just do

!include x64.nsh

Section
SetOutPath $InstDir
${If} ${IsNativeAMD64}
  File x64\myapp.exe
${Else}
  File x86\myapp.exe
${EndIf}
SectionEnd

I don't know anything about elecron-builder.