问:
Problem with preparing array with attendance for team
I got Users, Absences and Reasons tables:

```<code>Users
id | name

Absences
id | user_id:foreignKey | reason_id:foreignKey | deputy_id:foreignKey | start:date | end:date

Reasons
id | name
</code>```

I got attendance calendar which looks like:

```<code>Day   | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
-----------------------------------------------|
User1 | o | o | V | V | S | S | o | o | o | V  |
-----------------------------------------------|
User2 | T | o | o | o | H | V | o | V | o | V  |
-----------------------------------------------|
</code>```

Where "V" is Vacation, "S" sick etc. I want to print each User attendance report in that table.

```<code>@foreach ($users as $user )
   <tr>
      <td> {{ $user->name }} </td>
   @if($user->absences != null)
      @foreach($days as $day)
         @foreach ($user->absences as $absence)
           @if($day >= $absence->start->format('d') && $day <= $absence->end->format('d'))
              // there check if $user->absence->reason_id == something ...
           @else

           @endif
         @endforeach
       @endforeach
    @endif
  </tr>
@endforeach
</code>```

Also I want to have a tooltip, where I print specific data for each day (reason name, deputy name).

I have no idea how to get the range between two dates in each absence, merge it to got f.e table of user absence days with another array with reason.:

```<code>[
  2 => ['reason_id => 1, deputy_id = 3],
  3 => ['reason_id => 1, deputy_id = 3],
  7 => ['reason_id => 2, deputy_id = 1]
]
</code>```

Where keys [2,3,7] are the days of the absence.

Is there easier way to achieve that or should I rebuild the database structure?

答:
Here is my working solution :

```<code><table>
    <thead>
        <th>Day</th>
        @foreach (App\Models\User::all() as $user)
            <th>{{ $user->name }}</th>
        @endforeach
    </thead>
    <tbody>
        @for ($i = 1; $i <= Carbon\Carbon::now()->daysInMonth; $i++ )
        <tr>
            <td> {{ $i }} </td>
            @foreach (App\Models\User::with('absence')->get() as $user)
                <td>
                    @foreach ( $user->absence as $absence )
                        @if ($i>= Carbon\Carbon::parse($absence->start)->day && $i<=Carbon\Carbon::parse($absence->end)->day)
                            <span>{{$absence->reason->symbol}} - {{ $absence->deputy->name }}</span>
                        @endif
                    @endforeach
                </td>
            @endforeach
        </tr>
        @endfor
    </tbody>
</table>
</code>```

I also created repo for you so you can test this easy.

https://github.com/djokicpn/vacation-calendar

git clone https://github.com/djokicpn/vacation-calendar vacation-project

npm install

composer install

php artisan key:generate

php artisan migrate:fresh --seed

php artisan serve

Results preview :

Body:
I got Users, Absences and Reasons tables:

Users
id | name

Absences
id | user_id:foreignKey | reason_id:foreignKey | deputy_id:foreignKey | start:date | end:date

Reasons
id | name

I got attendance calendar which looks like:

Day   | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
-----------------------------------------------|
User1 | o | o | V | V | S | S | o | o | o | V  |
-----------------------------------------------|
User2 | T | o | o | o | H | V | o | V | o | V  |
-----------------------------------------------|

Where "V" is Vacation, "S" sick etc. I want to print each User attendance report in that table.

@foreach ($users as $user )

       {{ $user->name }}
   @if($user->absences != null)
      @foreach($days as $day)
         @foreach ($user->absences as $absence)
           @if($day >= $absence->start->format('d') && $day <= $absence->end->format('d'))
              // there check if $user->absence->reason_id == something ...
           @else

           @endif
         @endforeach
       @endforeach
    @endif

@endforeach

Also I want to have a tooltip, where I print specific data for each day (reason name, deputy name).

I have no idea how to get the range between two dates in each absence, merge it to got f.e table of user absence days with another array with reason.:

[
  2 => ['reason_id => 1, deputy_id = 3],
  3 => ['reason_id => 1, deputy_id = 3],
  7 => ['reason_id => 2, deputy_id = 1]
]

Where keys [2,3,7] are the days of the absence.

Is there easier way to achieve that or should I rebuild the database structure?

Body:
Here is my working solution :

<table>
    <thead>
        <th>Day</th>
        @foreach (App\Models\User::all() as $user)
            <th>{{ $user->name }}</th>
        @endforeach
    </thead>
    <tbody>
        @for ($i = 1; $i <= Carbon\Carbon::now()->daysInMonth; $i++ )
        <tr>
            <td> {{ $i }} </td>
            @foreach (App\Models\User::with('absence')->get() as $user)
                <td>
                    @foreach ( $user->absence as $absence )
                        @if ($i>= Carbon\Carbon::parse($absence->start)->day && $i<=Carbon\Carbon::parse($absence->end)->day)
                            <span>{{$absence->reason->symbol}} - {{ $absence->deputy->name }}</span>
                        @endif
                    @endforeach
                </td>
            @endforeach
        </tr>
        @endfor
    </tbody>
</table>

I also created repo for you so you can test this easy.

https://github.com/djokicpn/vacation-calendar

git clone https://github.com/djokicpn/vacation-calendar vacation-project

npm install

composer install

php artisan key:generate

php artisan migrate:fresh --seed

php artisan serve

Results preview :


来源: stackexchange

问:
Github Action: update existing comment if one exist or create a new comment
I built a pylint git action, for pull request, which actually works really well:

```<code>name: Python Linting

on:
  pull_request:
    branches: [ main, dev ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Setup action
      uses: actions/checkout@v2
      with:
        ref: ${{github.event.pull_request.head.ref}}
        repository: ${{github.event.pull_request.head.repo.full_name}}
    - name: Set up Python 3.10
      uses: actions/setup-python@v2
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Changed Files Exporter
      id: files
      uses: umani/changed-files@v3.3.0
      with:
        repo-token: ${{ github.token }}
        pattern: '^src.*\.(py)$'
        result-encoding: 'string'
    - name: Lint with pylint
      working-directory: ./
      run: |
        echo  '${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }}'
        pip install pylint
        OUTPUT=$(pylint ${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }} --exit-zero)
        echo 'MESSAGE<<EOF' >> $GITHUB_ENV
        echo  "$OUTPUT"  >> $GITHUB_ENV
        echo 'EOF' >> $GITHUB_ENV
    - name: Post result to PR
      uses: mshick/add-pr-comment@v1
      with:
        message: |
          ** Pylint Result**
          ```
          ${{ env.MESSAGE }}
          ```
          Please aim to have a quality of score of at least 5.0 or higher
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default
</code>```

The main problem with this is that it create a new message every time the PR is updated, is it possible to just update the existing comment that is already created?  Here is what the comment look like:

Is it possible to edit for an existing comment?  How can I tell which comment is the one to update?

答:
Yes it's doable.

I am using combination of 2 actions:

one to find comment id

second one to update or create comment

Here you have a working example coming from an action I use for comments editing and creation: https://github.com/peter-evans/create-or-update-comment#where-to-find-the-id-of-a-comment

```<code>- name: Find Comment
      uses: peter-evans/find-comment@v1
      id: fc
      with:
        issue-number: ${{ github.event.pull_request.number }}
        comment-author: 'github-actions[bot]'
        body-includes: This comment was written by a bot!

    - name: Create comment
      if: steps.fc.outputs.comment-id == ''
      uses: peter-evans/create-or-update-comment@v1
      with:
        issue-number: ${{ github.event.pull_request.number }}
        body: |
          This comment was written by a bot!
        reactions: rocket

    - name: Update comment
      if: steps.fc.outputs.comment-id != ''
      uses: peter-evans/create-or-update-comment@v1
      with:
        comment-id: ${{ steps.fc.outputs.comment-id }}
        body: |
          This comment has been updated!
        reactions: hooray
</code>```

Of course you need to adapt the filtering for finding comments - you can also use just comment-author and direction: last if your bot will have just one comment each thread.

ContentLicense: CC BY-SA 4.0

Body:
I built a pylint git action, for pull request, which actually works really well:

name: Python Linting

on:
  pull_request:
    branches: [ main, dev ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Setup action
      uses: actions/checkout@v2
      with:
        ref: ${{github.event.pull_request.head.ref}}
        repository: ${{github.event.pull_request.head.repo.full_name}}
    - name: Set up Python 3.10
      uses: actions/setup-python@v2
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Changed Files Exporter
      id: files
      uses: umani/changed-files@v3.3.0
      with:
        repo-token: ${{ github.token }}
        pattern: '^src.*\.(py)$'
        result-encoding: 'string'
    - name: Lint with pylint
      working-directory: ./
      run: |
        echo  '${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }}'
        pip install pylint
        OUTPUT=$(pylint ${{ steps.files.outputs.files_updated }} ${{ steps.files.outputs.files_created }} --exit-zero)
        echo 'MESSAGE<<EOF' >> $GITHUB_ENV
        echo  "$OUTPUT"  >> $GITHUB_ENV
        echo 'EOF' >> $GITHUB_ENV
    - name: Post result to PR
      uses: mshick/add-pr-comment@v1
      with:
        message: |
          ** Pylint Result**
          ```
          ${{ env.MESSAGE }}
          ```
          Please aim to have a quality of score of at least 5.0 or higher
        repo-token: ${{ secrets.GITHUB_TOKEN }}
        repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
        allow-repeats: false # This is the default

The main problem with this is that it create a new message every time the PR is updated, is it possible to just update the existing comment that is already created?  Here is what the comment look like:

Is it possible to edit for an existing comment?  How can I tell which comment is the one to update?

Body:
Yes it's doable.

I am using combination of 2 actions:

one to find comment id

second one to update or create comment

Here you have a working example coming from an action I use for comments editing and creation: https://github.com/peter-evans/create-or-update-comment#where-to-find-the-id-of-a-comment

- name: Find Comment
      uses: peter-evans/find-comment@v1
      id: fc
      with:
        issue-number: ${{ github.event.pull_request.number }}
        comment-author: 'github-actions[bot]'
        body-includes: This comment was written by a bot!

    - name: Create comment
      if: steps.fc.outputs.comment-id == ''
      uses: peter-evans/create-or-update-comment@v1
      with:
        issue-number: ${{ github.event.pull_request.number }}
        body: |
          This comment was written by a bot!
        reactions: rocket

    - name: Update comment
      if: steps.fc.outputs.comment-id != ''
      uses: peter-evans/create-or-update-comment@v1
      with:
        comment-id: ${{ steps.fc.outputs.comment-id }}
        body: |
          This comment has been updated!
        reactions: hooray

Of course you need to adapt the filtering for finding comments - you can also use just comment-author and direction: last if your bot will have just one comment each thread.


问:
python - Using pandas structures with large csv(iterate and chunksize)
I have a large csv file, about 600mb with 11 million rows and I want to create statistical data like pivots, histograms, graphs etc. Obviously trying to just to read it normally:

```<code>df = pd.read_csv('Check400_900.csv', sep='\t')
</code>```

Doesn't work so I found iterate and chunksize in a similar post so I used:

```<code>df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)
</code>```

All good, i can for example print df.get_chunk(5)  and search the whole file with just:

```<code>for chunk in df:
    print chunk
</code>```

My problem is I don't know how to use stuff like these below for the whole df and not for just one chunk.

```<code>plt.plot()
print df.head()
print df.describe()
print df.dtypes
customer_group3 = df.groupby('UserID')
y3 = customer_group.size()
</code>```

答:
This might not reply directly to the question, but when you have to load a big dataset it is a good practice, to covert the dtypes of your columns while reading the dataset. Also if you know which columns you need, use the usecols argument to load only those.

```<code>df = pd.read_csv("data.csv",
            usecols=['A', 'B', 'C', 'Date'],
            dtype={'A':'uint32',
                    'B':'uint8',
                    'C':'uint8'
                    },
            parse_dates=['Date'],  # convert to datetime64
            sep='\t'
           )
</code>```

Body:
I have a large csv file, about 600mb with 11 million rows and I want to create statistical data like pivots, histograms, graphs etc. Obviously trying to just to read it normally:

df = pd.read_csv('Check400_900.csv', sep='\t')

Doesn't work so I found iterate and chunksize in a similar post so I used:

df = pd.read_csv('Check1_900.csv', sep='\t', iterator=True, chunksize=1000)

All good, i can for example print df.get_chunk(5)  and search the whole file with just:

for chunk in df:
    print chunk

My problem is I don't know how to use stuff like these below for the whole df and not for just one chunk.

plt.plot()
print df.head()
print df.describe()
print df.dtypes
customer_group3 = df.groupby('UserID')
y3 = customer_group.size()

Body:
This might not reply directly to the question, but when you have to load a big dataset it is a good practice, to covert the dtypes of your columns while reading the dataset. Also if you know which columns you need, use the usecols argument to load only those.

df = pd.read_csv("data.csv",
            usecols=['A', 'B', 'C', 'Date'],
            dtype={'A':'uint32',
                    'B':'uint8',
                    'C':'uint8'
                    },
            parse_dates=['Date'],  # convert to datetime64
            sep='\t'
           )


问:
Partitioning strategy : Full partitioning vs aligned partitioning in Sql Server (tuning options in database engine tuning advisor)
In Database engine tuning advisor, there is an option of Partitioning strategy:

Full partitioning vs aligned partitioning.

What is meant by full partitioning and aligned partitioning and what are its pros and cons?

答:
I believe, that this topic is not relevant anymore, but anyway.
To someone, who interested in it, check that link https://dbtut.com/index.php/2019/05/14/database-engine-tuning-advisordta-in-sql-server/

And what I found here

Full partitioning
You can select this option if you want Partitioning suggestions. You can
find details about the Partition concept in the article “How To Create

Partition On SQL Server“.

Aligned partitioning
You should select this option if you want indexes to be aligned according
to the partition when Partition is recommended. For information about the
details of the Align process, please read to the article named “Can Not   > Switch The Partition On SQL Server“.

ContentLicense: CC BY-SA 3.0


问:
Class constructer from agregation link
I am pretty much new to OOP and C++ but have a project of "graph traversing" (sorry if there's a more formal term).

I am at the very beginning of the project where I have to initialize an 2D grid composed of cases.

I first thought of creating a class Case with 2D-position and a boolean state (occupied of free) as attributes, and a Grid class with a vector of vector of Cases representing the grid.

First I wondered if I'm going in the right direction on terms of Object-oriented programming, and if so I wondered how to initialize the grid in the constructor.

So far I have this for the Case class header :

```<code>class case_tab{

int x,y;

bool state;

public:

case_tab(int x_param, int y_param, bool state_param);
};
</code>```

And the constructor :

```<code>case_tab::case_tab(int x_param, int y_param, bool state_param)

:x(x_param),y(y_param),state(state_param)
{}
</code>```

But the problem comes for the grid constructor (named tableau, here you can see the header):

```<code>class tableau
{

int X, Y;

public:

std::vector<std::vector<case_tab>> tab;

tableau(int X_param, int Y_param);
};
</code>```

Where I don't know how to initialize the grid (tableau) as a grid of free Cases disposed correctly.

I'm pretty sure this is of very basic difficulty but I can't find how to do so, and wonder if it doesn't come from my structure choice in the first place.

Hope someone can help me.

答:
As you declared the attribute tab, it will be initialized by default. So you just have to do two loops so as to fill it. Here is a proposal:

```<code>tableau::tableau(int X_param, int Y_param)
        : X(X_param), Y(Y_param) {
    for(int i = 0; i < X; i++) {
        std::vector<case_tab> row;
        row.reserve(Y);
        for(int j = 0; j < Y; j++) {
            row.emplace_back(i, j, false);
        }
        tab.push_back(row);
    }
}
</code>```

emplace_back generates and adds case_tab objects by calling the constructor that you defined, and reserve allocates memory for the initialized objects.

You should also change tab visibility to private, so as to prevent adding unexpected items to it.

Title: Class constructer from agregation link

Body:
I am pretty much new to OOP and C++ but have a project of "graph traversing" (sorry if there's a more formal term).

I am at the very beginning of the project where I have to initialize an 2D grid composed of cases.

I first thought of creating a class Case with 2D-position and a boolean state (occupied of free) as attributes, and a Grid class with a vector of vector of Cases representing the grid.

First I wondered if I'm going in the right direction on terms of Object-oriented programming, and if so I wondered how to initialize the grid in the constructor.

So far I have this for the Case class header :

class case_tab{

int x,y;

bool state;

public:

case_tab(int x_param, int y_param, bool state_param);
};

And the constructor :

case_tab::case_tab(int x_param, int y_param, bool state_param)

:x(x_param),y(y_param),state(state_param)
{}

But the problem comes for the grid constructor (named tableau, here you can see the header):

class tableau
{

int X, Y;

public:

std::vector<std::vector<case_tab>> tab;

tableau(int X_param, int Y_param);
};

Where I don't know how to initialize the grid (tableau) as a grid of free Cases disposed correctly.

I'm pretty sure this is of very basic difficulty but I can't find how to do so, and wonder if it doesn't come from my structure choice in the first place.

Hope someone can help me.

Body:
As you declared the attribute tab, it will be initialized by default. So you just have to do two loops so as to fill it. Here is a proposal:

tableau::tableau(int X_param, int Y_param)
        : X(X_param), Y(Y_param) {
    for(int i = 0; i < X; i++) {
        std::vector<case_tab> row;
        row.reserve(Y);
        for(int j = 0; j < Y; j++) {
            row.emplace_back(i, j, false);
        }
        tab.push_back(row);
    }
}

emplace_back generates and adds case_tab objects by calling the constructor that you defined, and reserve allocates memory for the initialized objects.

You should also change tab visibility to private, so as to prevent adding unexpected items to it.


问:
Ethers.js token price chart
I'm using Ethers.js to get the token price from BSC using getReserves successfully.

  const nodeRandom = !node ? wssNodes() : node;
  const provider = new ethers.providers.WebSocketProvider(nodeRandom);
  const pairAddress = await pancake.getPair(token0, token1);

  if (pairAddress === "0x0000000000000000000000000000000000000000") {
    return {
      status: "Pair not found",
    };
  }

  const pairContract = new ethers.Contract(pairAddress, pancakePair, provider);
  const reserves = await pairContract.getReserves();
```

I want to create a price chart for that token, but I get into trouble when I don't know how to get the historical price data from BSC.

Does Ethers.js support getting the token price history, or should we store the price we get into our database? If then, is there any way we can build the price chart of a token from the very beginning of the first block when we don't have that in our DB?

Any idea?

答:
You can use the blockTag field of the overrides object - docs. It queries the node to return the value from a specific block instead of the current.

```<code>const reserves = await pairContract.getReserves({
    blockTag: <blockNumer>
});
</code>```

Note that it depends on the node provider if they support these historical queries or not. Most providers support it only in higher tier plans or not at all.

Title: Ethers.js token price chart

Body:
I'm using Ethers.js to get the token price from BSC using getReserves successfully.

  const nodeRandom = !node ? wssNodes() : node;
  const provider = new ethers.providers.WebSocketProvider(nodeRandom);
  const pairAddress = await pancake.getPair(token0, token1);

  if (pairAddress === "0x0000000000000000000000000000000000000000") {
    return {
      status: "Pair not found",
    };
  }

  const pairContract = new ethers.Contract(pairAddress, pancakePair, provider);
  const reserves = await pairContract.getReserves();

I want to create a price chart for that token, but I get into trouble when I don't know how to get the historical price data from BSC.

Does Ethers.js support getting the token price history, or should we store the price we get into our database? If then, is there any way we can build the price chart of a token from the very beginning of the first block when we don't have that in our DB?

Any idea?

Body:
You can use the blockTag field of the overrides object - docs. It queries the node to return the value from a specific block instead of the current.

const reserves = await pairContract.getReserves({
    blockTag: <blockNumer>
});

Note that it depends on the node provider if they support these historical queries or not. Most providers support it only in higher tier plans or not at all.


问:
django: unable to save new user
I'm trying to build a view that shows a form for creating a new user.

Next are the template I'm using, urls.py and the code attempts at views.py and forms.py.

```<code>user_form.html

    <form action="{% url 'app:register' %}" method="post">
        {% csrf_token %}
        {{form.as_p}}
    <input type="submit" value="Register">
    </form>
</code>```
```<code>urls.py

urlpatterns = [
    ...
    path('newuser/',views.NewUser.as_view(), name='newuser'),
    ...
]
</code>```

First attempt:

```<code>views.py

class NewUser(generic.CreateView):
    model = User
    fields = ['username','email','password']
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')
</code>```

This one didn't return errors, but was unable to save the new user data.

Second try involved creating a form for the occasion:

```<code>forms.py

class NewUserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.PasswordInput()

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')
</code>```

This one returned an error: TypeError at /newuser/ BaseForm.__init__() got an unexpected keyword argument 'instance'

Third:

```<code>forms.py

class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')

</code>```

Can't save a new User instance either.
I've also noticed that the model = User line in this last try can be removed.

I'm using the User.objects.all() query in the terminal and the admin page to check for new users.

What am I not doing?

答:
You should make the POST request to the newuser view, so:

```<code><form action="{% url <strong>'app:newuser'</strong> %}" method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Register">
</form></code>```

You can however not use a simple ModelForm: passwords in Django are hashed and the ModelForm will not do that, or at least not automatically.

You can make use of the UserCreationForm [Django-doc] to do the hashing properly, this field also uses two password fields which will be validated.

If you want to implement a custom ModelForm, then you will need to implement the password hashing functionality in the model form:

```<code>class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

    def <b>save</b>(self, commit=True):
        user = super().save(commit=False)
        user<strong>.set_password(self.cleaned_data['password'])</strong>
        if commit:
            user.save()
        return user</code>```

and then plug this into the CreateView with:

```<code>class NewUserView(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')
</code>```

Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names.
Therefore you might consider renaming the view class to NewUserView, instead of <s>NewUser</s>.

Title: django: unable to save new user

Body:
I'm trying to build a view that shows a form for creating a new user.

Next are the template I'm using, urls.py and the code attempts at views.py and forms.py.

user_form.html

    <form action="{% url 'app:register' %}" method="post">
        {% csrf_token %}
        {{form.as_p}}
    <input type="submit" value="Register">
    </form>

urls.py

urlpatterns = [
    ...
    path('newuser/',views.NewUser.as_view(), name='newuser'),
    ...
]

First attempt:

views.py

class NewUser(generic.CreateView):
    model = User
    fields = ['username','email','password']
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')

This one didn't return errors, but was unable to save the new user data.

Second try involved creating a form for the occasion:

forms.py

class NewUserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.PasswordInput()

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')

This one returned an error: TypeError at /newuser/ BaseForm.__init__() got an unexpected keyword argument 'instance'

Third:

forms.py

class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')

Can't save a new User instance either.
I've also noticed that the model = User line in this last try can be removed.

I'm using the User.objects.all() query in the terminal and the admin page to check for new users.

What am I not doing?

Body:
You should make the POST request to the newuser view, so:

<form action="{% url 'app:newuser' %}" method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Register">
</form>

You can however not use a simple ModelForm: passwords in Django are hashed and the ModelForm will not do that, or at least not automatically.

You can make use of the UserCreationForm [Django-doc] to do the hashing properly, this field also uses two password fields which will be validated.

If you want to implement a custom ModelForm, then you will need to implement the password hashing functionality in the model form:

class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

and then plug this into the CreateView with:

class NewUserView(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')

Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names.
Therefore you might consider renaming the view class to NewUserView, instead of <s>NewUser</s>.


问:
How do I get client IP address in ASP.NET Core?
Can you please let me know how to get client IP address in ASP.NET when using MVC 6.
Request.ServerVariables["REMOTE_ADDR"] does not work.

答:
```<code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

public string GetClientIPAddress(HttpContext context)
    {
        string ip = string.Empty;
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
        {
            ip = context.Request.Headers["X-Forwarded-For"];
        }
        else
        {
            ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
        }
        return ip;
    }
</code>```

Where you want to get Ip address;

```<code>GetClientIPAddress(HttpContext);
</code>```

Body:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

public string GetClientIPAddress(HttpContext context)
    {
        string ip = string.Empty;
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
        {
            ip = context.Request.Headers["X-Forwarded-For"];
        }
        else
        {
            ip = context.Request.HttpContext.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString();
        }
        return ip;
    }

Where you want to get Ip address;

GetClientIPAddress(HttpContext);


问:
Run Quarkus tests with TestContainers using WSL2 + Podman
With the license change for Docker Desktop on Windows, I'm looking for an alternative. Podman + WSL2 seems to do the trick for me. Except for Testcontainers in my Quarkus tests.

I'm able to run my tests within WSL2 by starting podman system service in WSL2 (podman system service -t 0 tcp:localhost:8880) and setting the DOCKER_HOST env var (DOCKER_HOST=tcp://localhost:8880).

Now this works, but isn't really what I need, since at my company we develop in VSCode, IntelliJ and Eclipse. I'd like to be able to run the tests from within those IDE's. Is there any way to pass the podman uri (from WSL) to my IDE in Windows while running Quarkus tests?

If anyone would know any other docker desktop alternatives that work with TestContainers, that would be awesome as well. I have tried Rancher Desktop, but it gets stuck and the tests eventually time out.

答: enter image description hereTake IntelliJ for example, you can set DOCKER_HOST env var by "Run/Debug Configurations" and it works perfectly.</p>


问:
Group of objects with similar names
I have an object:

```<code>public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}
</code>```

I return a list that may look like the following:

```<code>var students = new List<Student>() {
                new Student(){ Id = 1, Name="Bill85"},
                new Student(){ Id = 2, Name="Bill66"},
                new Student(){ Id = 3, Name="Ram7895"},
                new Student(){ Id = 4, Name="Ram5566"},
                new Student(){ Id = 5, Name="Join1230"}
            };
</code>```

I want to group them together if they have similar names, to get the result like below, is there any quick way to solve this?

```<code>GroupStudentList
    UserList
        Id = 1, Name="Bill85"
        Id = 2, Name="Bill66"
    UserList
        Id = 3, Name="Ram7895"
        Id = 4, Name="Ram5566"
    UserList
        Id = 3, Name="Join1230"
</code>```

答:
```<code>public class Student
{
 public List<Student> ListGroupStudent {get; set;}
 //add one list property...
}

var listGroup = listStudent.GroupBy(
    x => x.Name,
    (key, y) => new { ListGroupStudent = y.ToList() });
</code>```

Title: Group of objects with similar names

Body:
I have an object:

public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}

I return a list that may look like the following:

var students = new List<Student>() {
                new Student(){ Id = 1, Name="Bill85"},
                new Student(){ Id = 2, Name="Bill66"},
                new Student(){ Id = 3, Name="Ram7895"},
                new Student(){ Id = 4, Name="Ram5566"},
                new Student(){ Id = 5, Name="Join1230"}
            };

I want to group them together if they have similar names, to get the result like below, is there any quick way to solve this?

GroupStudentList
    UserList
        Id = 1, Name="Bill85"
        Id = 2, Name="Bill66"
    UserList
        Id = 3, Name="Ram7895"
        Id = 4, Name="Ram5566"
    UserList
        Id = 3, Name="Join1230"


问:
Spring.mvc.servlet.path vs Server.servlet.context-path
I have Spring Boot application in which I use "spring.mvc.servlet.path=/api/v1" to acces my endpoints. For example when I test my "users" endpoint in postman i Have: "http://localhost:8081/api/v1/users". And it works.

The problem is when I integrate Swagger for my documentation. And I try to acces my doc in swagger-u.html with "http://localhost:8081/api/v1/swagger-ui.html" it doesn`t work.

When I change my configuration from application.properties to "server.servlet.context-path=/api/v1" . The endpoint of Swagger works and my "http://localhost:8081/api/v1/users" doesn`t work.

Any sugestions of how may I resolve this problem ?

答:
I was running different applications on the same server and I run into accessibility issues which forced me to add server context-path for these different applications.

Context path is a name with which a web application is accessed.
By default, Spring Boot serves the content on the root context path (“/”).

However to avoid accessibility issues you can change this in the application.propeties file:

```<code> server.servlet.context-path=/test
</code>```

The servlet path represents the path of the main DispatcherServlet which is the front controller. The default value is similar to the context path (“/”).
To change these value you can use:

```<code>  spring.mvc.servlet.path=/api/v1
</code>```

With these changes you can access your api and swagger documentation endpoints as follows

http://localhost:8081/test/api/v1/users

http://localhost:8081/test/swagger-ui.html

The swagger documentation is exposed only through the context-path because it is not accessed through the front controller...

You can read more about this here
https://www.baeldung.com/spring-boot-context-path
https://www.baeldung.com/spring-context-vs-servlet-path

.

Body:
I was running different applications on the same server and I run into accessibility issues which forced me to add server context-path for these different applications.

Context path is a name with which a web application is accessed.
By default, Spring Boot serves the content on the root context path (“/”).

However to avoid accessibility issues you can change this in the application.propeties file:

 server.servlet.context-path=/test

The servlet path represents the path of the main DispatcherServlet which is the front controller. The default value is similar to the context path (“/”).
To change these value you can use:

  spring.mvc.servlet.path=/api/v1

With these changes you can access your api and swagger documentation endpoints as follows

http://localhost:8081/test/api/v1/users

http://localhost:8081/test/swagger-ui.html

The swagger documentation is exposed only through the context-path because it is not accessed through the front controller...

You can read more about this here
https://www.baeldung.com/spring-boot-context-path
https://www.baeldung.com/spring-context-vs-servlet-path

.


问:
can you fake *nix uptime?
Just curious, Can you fake an uptime, for instance increase it to 10 years?

I have tried changing system time, and it won't do this trick.

答: Have a look at this utility: UptimeFaker.</p>

ContentLicense: CC BY-SA 2.5

Title: can you fake *nix uptime?


问:
How to Combine Multiple Excel into one with Talend
I'm a new in Talend and need some help.

I want to write data in the same excel file containing different sheets, I have 2 tFileOuputExcel, I put the same file name and different sheet names,

In output the data is written only in the first sheet but not in the second sheet.

Below is the screenshot of my job.

答: in 2nd tFileOutputExcel select checkbox "Append Existing File"</p>


问:
Suppressing Firebase error logging on failed signInWithEmailAndPassword
I am attempting to implement login functionality using Firebase auth, in NextJS. Calling the function with invalid login details logs an error to the console, despite the empty catch statement in the handler for the login function. How do I suppress Firebase from logging this error to the console?

Login function handler:

```<code>const signinWithEmail = async (email, password) => {
    setLoading(true);
    signInWithEmailAndPassword(auth, email, password)
        .then((response) => {
            handleUser(response.user);
            Router.push("/");
        })
        .catch((error) => {
            // Do nothing
        });
};
</code>```

Error in console (blurred due to exposed API key):

答:
Those network error logs are shown by the browser when the request returns an error. The catch block in code still works as intended. This can be disabled but by users themselves. Checkout: Suppress Chrome 'Failed to load resource' messages in console

The API key visible in the request is meant to be public and that's not an issue. Checkout:
Is it safe to expose Firebase apiKey to the public?

Body:
I am attempting to implement login functionality using Firebase auth, in NextJS. Calling the function with invalid login details logs an error to the console, despite the empty catch statement in the handler for the login function. How do I suppress Firebase from logging this error to the console?

Login function handler:

const signinWithEmail = async (email, password) => {
    setLoading(true);
    signInWithEmailAndPassword(auth, email, password)
        .then((response) => {
            handleUser(response.user);
            Router.push("/");
        })
        .catch((error) => {
            // Do nothing
        });
};

Error in console (blurred due to exposed API key):


问:
how to retrieve form values and labels from react hook form and antd Select
I am using antd Select and react hook form via 'Controller'. I am populating the Select options from a fetched data with structure;

{
{
"id": "232342",
"term": "hello"
}
{
"id": "232342",
"term": "hello"
}
}

the Select component properly displays the term for selection. However, i want to retrieve both the 'id'and 'term' of the selected and use it to populate another json object.

getValues(" ") retrieves the 'id' only. How do i retrieve and access both the 'id' and 'term'.

Here is a portion of code:

```<code>import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import { Select } from 'antd'

const { Option } = Select

export default function PatientRegistrationForm({ options }) {
  const { register, handleSubmit, getValues, control, formState: { errors } } = useForm({
      defaultValues: {
         customer: "",
      }
  })

    const children = []
    for (const {id, pt: {term}} of options){
        children.push(<Option key={id}>{term}</Option>)
    }

    // Define the retrieved values from the form
        const retrievedID = getValues("customer")

        // Use the retreived values to populate this object
        const customer = {
            customerId = retrievedID
            customerName = "nothing happens here"
            },

  return (
      <div className="">
          <form onSubmit={handleSubmit(onSubmit)} className="">

            <section>
            <Controller
                control={control}
                name="customer"
                render={({ field }) => (
                    <Select {...field} defaultValue=""
                        bordered={true}
                        filterOption={true}
                        className="form-control"

                    >
                        { children }
                    </Select>
                )}
            />
            </section>
           </form>
      </div>

  );
}
</code>```

Thanks in advance for your help.

答: thank you #sgarcia.dev for your answer. I know its been a while but i want to put it out here incase it helps someone else. It turns out it had little to do with react hook form. Ant design select component has a prop 'labelInValue' which returns an object containing both the label and value.</p>

Body:
I am using antd Select and react hook form via 'Controller'. I am populating the Select options from a fetched data with structure;

{
{
"id": "232342",
"term": "hello"
}
{
"id": "232342",
"term": "hello"
}
}

the Select component properly displays the term for selection. However, i want to retrieve both the 'id'and 'term' of the selected and use it to populate another json object.

getValues(" ") retrieves the 'id' only. How do i retrieve and access both the 'id' and 'term'.

Here is a portion of code:

import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import { Select } from 'antd'

const { Option } = Select

export default function PatientRegistrationForm({ options }) {
  const { register, handleSubmit, getValues, control, formState: { errors } } = useForm({
      defaultValues: {
         customer: "",
      }
  })

    const children = []
    for (const {id, pt: {term}} of options){
        children.push(<Option key={id}>{term}</Option>)
    }

    // Define the retrieved values from the form
        const retrievedID = getValues("customer")

        // Use the retreived values to populate this object
        const customer = {
            customerId = retrievedID
            customerName = "nothing happens here"
            },

  return (

          <form onSubmit={handleSubmit(onSubmit)} className="">

            <Controller
                control={control}
                name="customer"
                render={({ field }) => (
                    <Select {...field} defaultValue=""
                        bordered={true}
                        filterOption={true}
                        className="form-control"

                    >
                        { children }
                    </Select>
                )}
            />

           </form>

  );
}

Thanks in advance for your help.


问:
Polymorphic association foreign_type sets ancestor type instead current, using STI class
I have

```<code>class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end
</code>```

I have to mention that I'm using a single table called cars which has a field type.

```<code>class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end
</code>```

When I do

```<code>  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"
</code>```

And it should be

```<code>  a.itemable_type
  => "Porsche"
</code>```

Do anybody have an idea about this?

Update

According to bor1s's answer probably this is the right behaviour. So if is it, then my question is how can I set it to Porsche implicitly?

答: This is because Porshe is virtual model, it is not really exist in in database, it just has type field to know that it is Porshe. Maybe you should get rid of STI and use say type column to save Car model with type of Porshe and use scope to find porshes. I hope I helped you alittle.

Body:
I have

class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end

I have to mention that I'm using a single table called cars which has a field type.

class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end

When I do

  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"

And it should be

  a.itemable_type
  => "Porsche"

Do anybody have an idea about this?

Update

According to bor1s's answer probably this is the right behaviour. So if is it, then my question is how can I set it to Porsche implicitly?


问:
crossAxisAlignment: CrossAxisAlignment.end doesn't work
I am pretty new to programming and also to Flutter, so please excuse me if my question is silly. I am trying to push Skip button to the bottom left corner of the screen. But the crossAxisAlignment: CrossAxisAlignment.end code doesn't work. How could I do this the right way so it can adapt to all screen formats properly? The problematic part is at the bottom of the entire code. Thank you in advance!

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            width: 230,
            decoration: BoxDecoration(),
            child: Image.asset('images/logo1.png'),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            child: Text(
              'Login',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30),
            height: 50,
            width: double.infinity,
            child: Text(
              'E-mail',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            height: 50,
            width: double.infinity,
            child: Text(
              'Password',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              height: 50.0,
              minWidth: double.infinity,
              color: Colors.orangeAccent,
              child: Text(
                "Login",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
              onPressed: () => {},
              splashColor: Colors.redAccent,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            child: Center(
              child: TextButton(
                style: TextButton.styleFrom(
                  textStyle: TextStyle(fontSize: 17),
                ),
                onPressed: () {},
                child: Text(
                  'Forgot your password?',
                  style: TextStyle(color: Colors.black54),
                ),
              ),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Container(
                margin: EdgeInsets.only(top: 5),
                child: TextButton(
                  style: TextButton.styleFrom(
                    textStyle: TextStyle(fontSize: 17),
                  ),
                  onPressed: () {},
                  child: Text(
                    'Skip',
                    style: TextStyle(color: Colors.black54),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
```

Mobile Display

答:
You can use Spacer widget before Row. By default, row children will start from left.

 ///others widgets
 const Spacer(), /// just add this
 Row(....
```

More about Spacer widget.

Body:
I am pretty new to programming and also to Flutter, so please excuse me if my question is silly. I am trying to push Skip button to the bottom left corner of the screen. But the crossAxisAlignment: CrossAxisAlignment.end code doesn't work. How could I do this the right way so it can adapt to all screen formats properly? The problematic part is at the bottom of the entire code. Thank you in advance!

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            width: 230,
            decoration: BoxDecoration(),
            child: Image.asset('images/logo1.png'),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            child: Text(
              'Login',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30),
            height: 50,
            width: double.infinity,
            child: Text(
              'E-mail',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            height: 50,
            width: double.infinity,
            child: Text(
              'Password',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              height: 50.0,
              minWidth: double.infinity,
              color: Colors.orangeAccent,
              child: Text(
                "Login",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
              onPressed: () => {},
              splashColor: Colors.redAccent,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            child: Center(
              child: TextButton(
                style: TextButton.styleFrom(
                  textStyle: TextStyle(fontSize: 17),
                ),
                onPressed: () {},
                child: Text(
                  'Forgot your password?',
                  style: TextStyle(color: Colors.black54),
                ),
              ),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Container(
                margin: EdgeInsets.only(top: 5),
                child: TextButton(
                  style: TextButton.styleFrom(
                    textStyle: TextStyle(fontSize: 17),
                  ),
                  onPressed: () {},
                  child: Text(
                    'Skip',
                    style: TextStyle(color: Colors.black54),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Mobile Display

Body:
You can use Spacer widget before Row. By default, row children will start from left.

 ///others widgets
 const Spacer(), /// just add this
 Row(....

More about Spacer widget.


问:
How to test ant design Select and Option properly using jest?
I am using Ant Design for my select form component and I would like to test the options value because the values will change dynamically based on the different choices that user made while filling.

my-test.spec.js

```<code>      let questionDropdown
      await waitFor(() => {
        questionDropdown = screen.getByRole('combobox', { name: 'Question'})
        expect(questionDropdown).toBeDefined()
      })
      fireEvent.click(questionDropdown)

      // Hoping to test the options after clicking on the select, but I can't find the options element on screen
      // expect(screen.getByText('question 1')).toBeDefined()
      // expect(screen.queryAllByRole('option').length).toEqual(2)
</code>```

I found this issues in antd about how to mock the Select and Options components.

```<code>jest.mock('antd', () => {
  const antd = jest.requireActual('antd');

  const Select = ({ children, onChange }) => {
    return <select onChange={e => onChange(e.target.value)}>{children}</select>;
  };

  Select.Option = ({ children, ...otherProps }) => {
    return <option {...otherProps}>{children}</option>;
  }

  return {
    ...antd,
    Select,
  }
}
</code>```

but still have no luck getting my options tested.

答:
You can test it without mocking. See this example:</p>
```<code>import { Select, SelectProps } from 'antd';
import React from 'react';

const { Option } = Select;

export type Period = 'days' | 'months' | 'years';

const ranges = [
  { name: 'Dia', duration: 'days' },
  { name: 'Mês', duration: 'months' },
  { name: 'Ano', duration: 'years' },
];

export type PeriodRangePickerProps = Pick<SelectProps<Period>, 'value' | 'onChange' | 'style'>;

const PeriodRangePicker = ({ value, onChange, style }: PeriodRangePickerProps) => (
  <Select style={style || { width: 90 }} showSearch optionFilterProp="children" {...{ value, onChange }}>
    {ranges.map(({ duration, name }) => (
      <Option key={duration} value={duration}>
        % {name}
      </Option>
    ))}
  </Select>
);

export default PeriodRangePicker;
</code>```
```<code>import PeriodRangePicker from '@components/PeriodRangePicker/PeriodRangePicker';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('PeriodRangePicker', () => {
  it('should call onChange with correct values', async () => {
    const handleChangeStub = jest.fn();

    render(<PeriodRangePicker onChange={handleChangeStub} />);

    const periodSelect = screen.getByRole('combobox');

    await userEvent.click(periodSelect);

    await waitFor(() => screen.getByText('% Dia'));

    fireEvent.click(screen.getByText('% Dia'));

    expect(handleChangeStub).toBeCalledWith('days', expect.anything());
  });
});
</code>```

Body:
I am using Ant Design for my select form component and I would like to test the options value because the values will change dynamically based on the different choices that user made while filling.

my-test.spec.js

      let questionDropdown
      await waitFor(() => {
        questionDropdown = screen.getByRole('combobox', { name: 'Question'})
        expect(questionDropdown).toBeDefined()
      })
      fireEvent.click(questionDropdown)

      // Hoping to test the options after clicking on the select, but I can't find the options element on screen
      // expect(screen.getByText('question 1')).toBeDefined()
      // expect(screen.queryAllByRole('option').length).toEqual(2)

I found this issues in antd about how to mock the Select and Options components.

jest.mock('antd', () => {
  const antd = jest.requireActual('antd');

  const Select = ({ children, onChange }) => {
    return <select onChange={e => onChange(e.target.value)}>{children}</select>;
  };

  Select.Option = ({ children, ...otherProps }) => {
    return <option {...otherProps}>{children}</option>;
  }

  return {
    ...antd,
    Select,
  }
}

but still have no luck getting my options tested.

Body:
You can test it without mocking. See this example:

import { Select, SelectProps } from 'antd';
import React from 'react';

const { Option } = Select;

export type Period = 'days' | 'months' | 'years';

const ranges = [
  { name: 'Dia', duration: 'days' },
  { name: 'Mês', duration: 'months' },
  { name: 'Ano', duration: 'years' },
];

export type PeriodRangePickerProps = Pick<SelectProps<Period>, 'value' | 'onChange' | 'style'>;

const PeriodRangePicker = ({ value, onChange, style }: PeriodRangePickerProps) => (
  <Select style={style || { width: 90 }} showSearch optionFilterProp="children" {...{ value, onChange }}>
    {ranges.map(({ duration, name }) => (
      <Option key={duration} value={duration}>
        % {name}
      </Option>
    ))}
  </Select>
);

export default PeriodRangePicker;

import PeriodRangePicker from '@components/PeriodRangePicker/PeriodRangePicker';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('PeriodRangePicker', () => {
  it('should call onChange with correct values', async () => {
    const handleChangeStub = jest.fn();

    render(<PeriodRangePicker onChange={handleChangeStub} />);

    const periodSelect = screen.getByRole('combobox');

    await userEvent.click(periodSelect);

    await waitFor(() => screen.getByText('% Dia'));

    fireEvent.click(screen.getByText('% Dia'));

    expect(handleChangeStub).toBeCalledWith('days', expect.anything());
  });
});


问:
How to add quotes from specific delimiter to end of the line, using awk?
I am trying to modify a file: (file.txt)

```<code>abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~
</code>```

to (new_file.txt)

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
</code>```

I tried using awk command:

```<code>awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt
</code>```

but I am getting output as:

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"
</code>```

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

答:
And also with GNU awk:

```<code>awk '{sub(/~$/,"~\"");print gensub(/~/, "~\"", 4)}' file
abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
</code>```

Two substitutions of the ~ by ~", one at the end with sub() and other at 4th apparition with gensub().

Body:
I am trying to modify a file: (file.txt)

abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~

to (new_file.txt)

abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

I tried using awk command:

awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt

but I am getting output as:

abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

Body:
And also with GNU awk:

awk '{sub(/~$/,"~\"");print gensub(/~/, "~\"", 4)}' file
abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

Two substitutions of the ~ by ~", one at the end with sub() and other at 4th apparition with gensub().


问:
How to make Prettier to ignore a block of code?
Say we have a line of code:

const a = 'a'; const b = 'b';
```
<p>and we wouldn't want it to be formatter by Prettier.</p>
<p>What I've tried so far:</p>
<p>1)</p>
<pre class="lang-js prettyprint-override"><code>// prettier-ignore
const a = 'a'; const b = 'b';
</code>```

// prettier-ignore-start
const a = 'a'; const b = 'b';
// prettier-ignore-end
```
<p>In both cases it gets transformed into:</p>
<pre class="lang-js prettyprint-override"><code>const a = 'a';
const b = 'b';
</code>```

So how to ignore a block of code?

答:
It sucks, but this isnt currently supported.

While this doesnt work for OP's example, one option is to add the prettier-ignore comment to the start of each line to be ignored, using the /* */ comment style, eg.

```<code>/* prettier-ignore */ import { SomeTypeA, SomeTypeB, SomeTypeC } from './some-long-folder-name/super-long-import';
/* prettier-ignore */ import { someFnA, someFnB, someFnC, } from './another-long-folder-name/super-long-import';
</code>```

In my opinion, this is easier on the eyes than the alternatives;

Letting prettier reformat the imports:

```<code>import {
    SomeTypeA,
    SomeTypeB,
    SomeTypeC,
} from './some-long-folder-name/super-long-import';
import {
    someFnA,
    someFnB,
    someFnC,
} from './another-long-folder-name/super-long-import';
</code>```

Specifying the // prettier-ignore comment above each import:

```<code>// prettier-ignore
import { SomeTypeA, SomeTypeB, SomeTypeC } from './some-long-folder-name/super-long-import';
// prettier-ignore
import { someFnA, someFnB, someFnC, } from './another-long-folder-name/super-long-import';
</code>```

Body:
Say we have a line of code:

const a = 'a'; const b = 'b';

and we wouldn't want it to be formatter by Prettier.

What I've tried so far:

1)

// prettier-ignore
const a = 'a'; const b = 'b';

// prettier-ignore-start
const a = 'a'; const b = 'b';
// prettier-ignore-end

In both cases it gets transformed into:

const a = 'a';
const b = 'b';

So how to ignore a block of code?

Body:
It sucks, but this isnt currently supported.

While this doesnt work for OP's example, one option is to add the prettier-ignore comment to the start of each line to be ignored, using the /* */ comment style, eg.

/* prettier-ignore */ import { SomeTypeA, SomeTypeB, SomeTypeC } from './some-long-folder-name/super-long-import';
/* prettier-ignore */ import { someFnA, someFnB, someFnC, } from './another-long-folder-name/super-long-import';

In my opinion, this is easier on the eyes than the alternatives;

Letting prettier reformat the imports:

import {
    SomeTypeA,
    SomeTypeB,
    SomeTypeC,
} from './some-long-folder-name/super-long-import';
import {
    someFnA,
    someFnB,
    someFnC,
} from './another-long-folder-name/super-long-import';

Specifying the // prettier-ignore comment above each import:

// prettier-ignore
import { SomeTypeA, SomeTypeB, SomeTypeC } from './some-long-folder-name/super-long-import';
// prettier-ignore
import { someFnA, someFnB, someFnC, } from './another-long-folder-name/super-long-import';


问:
does validation_data in model.fit() method in Tensorflow Keras have to be a tuple?
I'm implementing a complicated loss function so I use a custom layer to pass the loss. Something like：

```<code>class SIAMESE_LOSS(Layer):
    def __init__(self, **kwargs):
        super(SIAMESE_LOSS, self).__init__(**kwargs)

    @staticmethod
    def mmd_loss(source_samples, target_samples):
        return mmd(source_samples, target_samples)

    @staticmethod
    def regression_loss(pred, labels):
        return K.mean(mae(pred, labels))

    def call(self, inputs, **kwargs):
        source_labels = inputs[0]
        target_labels = inputs[1]
        source_pred = inputs[2]
        target_pred = inputs[3]
        source_samples = inputs[4]
        target_samples = inputs[5]
        source_loss = self.regression_loss(source_pred, source_labels)
        target_loss = self.regression_loss(target_pred, target_labels)
        mmd_loss = self.mmd_loss(source_samples, target_samples)
        self.add_loss(source_loss)
        self.add_loss(target_loss)
        self.add_loss(mmd)
        self.add_metric(source_loss, aggregation='mean', name='source_mae')
        self.add_metric(target_loss, aggregation='mean', name='target_mae')
        self.add_metric(mmd_loss, aggregation='mean', name='MMD')
        return mmd_loss+target_loss+source_loss
</code>```

So the labels are sent to the model as inputs.

Therefore fitting the model will be like:

```<code>        history = model.fit(
            x=[train_data_s, train_data_t, self.train_labels, self.train_data_t],
            y=None,
            batch_size=self.batch_size,
            epochs=base_epochs,
            verbose=2,
            callbacks=cp_callback,
            validation_data=[val_data_s, val_data_t, self.val_labels, self.val_labels_t],
            shuffle=True
        )
</code>```

However, according to the official document in Tensorflow, validation_data should be:

Data on which to evaluate the loss and any model metrics at the end of
  each epoch. The model will not be trained on this data.
  validation_data will override validation_split. validation_data could
  be: tuple (x_val, y_val) of Numpy arrays or tensors tuple (x_val,
  y_val, val_sample_weights) of Numpy arrays dataset For the first two
  cases, batch_size must be provided. For the last case,
  validation_steps could be provided. Note that validation_data does not
  support all the data types that are supported in x, eg, dict,
  generator or keras.utils.Sequence.

There's no 'label' that should be passed since they're already handled by the model as inputs. How can I solve the problem if I still wanna use validation data?

答:
to write your own loss you need to inherit from class Loss and then implement your loss calculation in the init and call methods.
https://www.tensorflow.org/api_docs/python/tf/keras/losses/Loss

so you dont need to train without passing y in model.fit()

Body:
I'm implementing a complicated loss function so I use a custom layer to pass the loss. Something like：

class SIAMESE_LOSS(Layer):
    def __init__(self, **kwargs):
        super(SIAMESE_LOSS, self).__init__(**kwargs)

    @staticmethod
    def mmd_loss(source_samples, target_samples):
        return mmd(source_samples, target_samples)

    @staticmethod
    def regression_loss(pred, labels):
        return K.mean(mae(pred, labels))

    def call(self, inputs, **kwargs):
        source_labels = inputs[0]
        target_labels = inputs[1]
        source_pred = inputs[2]
        target_pred = inputs[3]
        source_samples = inputs[4]
        target_samples = inputs[5]
        source_loss = self.regression_loss(source_pred, source_labels)
        target_loss = self.regression_loss(target_pred, target_labels)
        mmd_loss = self.mmd_loss(source_samples, target_samples)
        self.add_loss(source_loss)
        self.add_loss(target_loss)
        self.add_loss(mmd)
        self.add_metric(source_loss, aggregation='mean', name='source_mae')
        self.add_metric(target_loss, aggregation='mean', name='target_mae')
        self.add_metric(mmd_loss, aggregation='mean', name='MMD')
        return mmd_loss+target_loss+source_loss

So the labels are sent to the model as inputs.

Therefore fitting the model will be like:

        history = model.fit(
            x=[train_data_s, train_data_t, self.train_labels, self.train_data_t],
            y=None,
            batch_size=self.batch_size,
            epochs=base_epochs,
            verbose=2,
            callbacks=cp_callback,
            validation_data=[val_data_s, val_data_t, self.val_labels, self.val_labels_t],
            shuffle=True
        )

However, according to the official document in Tensorflow, validation_data should be:

Data on which to evaluate the loss and any model metrics at the end of
  each epoch. The model will not be trained on this data.
  validation_data will override validation_split. validation_data could
  be: tuple (x_val, y_val) of Numpy arrays or tensors tuple (x_val,
  y_val, val_sample_weights) of Numpy arrays dataset For the first two
  cases, batch_size must be provided. For the last case,
  validation_steps could be provided. Note that validation_data does not
  support all the data types that are supported in x, eg, dict,
  generator or keras.utils.Sequence.

There's no 'label' that should be passed since they're already handled by the model as inputs. How can I solve the problem if I still wanna use validation data?


问:
Java NIO causes file descriptor leak
We have a http server which is implemented based on Java NIO.
It is running on Ubuntu 10.04.2 LTS with java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)

However, it leaks file descriptors, all of them are unix domain sockets.

When use the command "netstat -anp", we can find that the process only opens two unix domain socket.
However, when use lsof -p , we can find that there are huge amounts of file descriptors which are unix domain socket and have the same device value and node value as the one find in netstat.

I have checked our code, and all of the SocketChannels are closed properly.

Is it a bug of Sun JDK?
How can we fix it?

答:
The root cause is found.
In our code, when we close socketchannel, we also cancel the key. The problem is that:
a. We cancel the key in the select thread, and close the socketchannel in another thread
b. The socket channel is closed until the key.cancel is invoked.

By reading the implementation of close and cancel, we can find that the unix domain socket is opened by dup2 and never closed some times (concurrent issue).

Title: Java NIO causes file descriptor leak


问:
AssertionError Address changing in hardhat tests
I'm running into this AssertionError. I'm using a public key generated from the hardhat network. It's saved as a const const recipient = "0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199";

As you can see in the error below the value of recipient is changing (capital letters vs lowercase letter). Any idea why and how this can happen?

should work with ERC2981 royalties:

```<code>  AssertionError: expected '0x8626f6940E2eb28930eFb4CeF49B2d1F2C9…' to equal '0x8626f6940e2eb28930efb4cef49b2d1f2c9…'
  + expected - actual

  -0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199
  +0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199
</code>```

This is the actual test:

```<code>it("should work with ERC2981 royalties", async function () {
    const Token = await ethers.getContractFactory("Token");
    const token = await Token.deploy();
    await token.deployed();

    await token.setRoyalties(0, recipient, 1000);
    let getRoyalties = await token.getRaribleV2Royalties(0);
    assert.equal(getRoyalties[0].value, "1000");
    assert.equal(getRoyalties[0].account, recipient);
    let royalties = await token.royaltyInfo(0, 100000);

    assert.equal(royalties.royaltyAmount.toString(), "10000");
    assert.equal(royalties.receiver, recipient);
});
</code>```

答: It's the address checksum. You can checksum an address using the ethers.utils.getAddress() function (docs).

Body:
I'm running into this AssertionError. I'm using a public key generated from the hardhat network. It's saved as a const const recipient = "0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199";

As you can see in the error below the value of recipient is changing (capital letters vs lowercase letter). Any idea why and how this can happen?

should work with ERC2981 royalties:

  AssertionError: expected '0x8626f6940E2eb28930eFb4CeF49B2d1F2C9…' to equal '0x8626f6940e2eb28930efb4cef49b2d1f2c9…'
  + expected - actual

  -0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199
  +0x8626f6940e2eb28930efb4cef49b2d1f2c9c1199

This is the actual test:

it("should work with ERC2981 royalties", async function () {
    const Token = await ethers.getContractFactory("Token");
    const token = await Token.deploy();
    await token.deployed();

    await token.setRoyalties(0, recipient, 1000);
    let getRoyalties = await token.getRaribleV2Royalties(0);
    assert.equal(getRoyalties[0].value, "1000");
    assert.equal(getRoyalties[0].account, recipient);
    let royalties = await token.royaltyInfo(0, 100000);

    assert.equal(royalties.royaltyAmount.toString(), "10000");
    assert.equal(royalties.receiver, recipient);
});


答:
To change the position for Row children horizontally
you need to use mainAxisAlignment property

mainAxisAlignment property:
How the children should be placed along the main axis.
For example, MainAxisAlignment.start, the default, places the children at the start (i.e., the left for a Row or the top for a Column) of the main axis.

source flutter https://api.flutter.dev/flutter/widgets/Flex/mainAxisAlignment.html

Title: crossAxisAlignment: CrossAxisAlignment.end doesn't work


问:
for-loop confusion
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.</p>
```<code>name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)
</code>```

答:
You forgot add range in you for loop, and you're writing "input(int)" it's wrong, because you just add 0 in your input, and then writing your name</p>
```<code>name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = int(input())
for times in range(answer):
print(name)
</code>```

Title: for-loop confusion

Body:
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.

name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)

Body:
You forgot add range in you for loop, and you're writing "input(int)" it's wrong, because you just add 0 in your input, and then writing your name

name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = int(input())
for times in range(answer):
print(name)


问:
How to insert QChartView in form with Qt Designer?
I want to add QChart to the form. But I can't find it in the Widget Box. So I created it in the code. How can I insert it in QWidget or QFrame or something else?

I want to set area of that widget in QtDesigner.

答:
Let me add something here for the answer below (thanks for that!)

I had some additional steps for using

```<code>QTcreator 4.11.0
</code>```

on

```<code>Ubuntu 20.04.3 LTS
</code>```

First, you need to install not only package

```<code>qml-module-qtcharts
</code>```

But also package

```<code>libqt5charts5-dev
</code>```

Next, for "Option 1: Promoted" below you 1st have to use Button "Add" after entering

```<code>Promoted class name: QChartView
</code>```

and

```<code>Header file: QtCharts
</code>```

Then, you can select it from the "Promoted Classes"

Finally, QTCreator adds to your ui_mainwindow.h (e.g.)

```<code>#include <qchartview.h>
</code>```

and uses

```<code>QChartView *graphicsView;
</code>```

But it does not consider, that type QChartView is defined in "namespace QtCharts" in <qchartview.h>. Therefore, type QChartView is not found.

I fixed (hacked) this by adding a "Central.h" to #include for users as a 1st #include file, with content

```<code>#ifndef CENTRAL_H
#define CENTRAL_H

#include <QtCharts>
using namespace QtCharts;

#endif // CENTRAL_H
</code>```

Body:
Let me add something here for the answer below (thanks for that!)

I had some additional steps for using

QTcreator 4.11.0

on

Ubuntu 20.04.3 LTS

First, you need to install not only package

qml-module-qtcharts

But also package

libqt5charts5-dev

Next, for "Option 1: Promoted" below you 1st have to use Button "Add" after entering

Promoted class name: QChartView

and

Header file: QtCharts

Then, you can select it from the "Promoted Classes"

Finally, QTCreator adds to your ui_mainwindow.h (e.g.)

#include <qchartview.h>

and uses

QChartView *graphicsView;

But it does not consider, that type QChartView is defined in "namespace QtCharts" in <qchartview.h>. Therefore, type QChartView is not found.

I fixed (hacked) this by adding a "Central.h" to #include for users as a 1st #include file, with content

#ifndef CENTRAL_H
#define CENTRAL_H

#include <QtCharts>
using namespace QtCharts;

#endif // CENTRAL_H


问:
Why class definition needs more information of its attributes than what is needed in a function definition?
```<code>def myfunc():
    return x
x = 10
print(myfunc())
</code>```

The above codes work, where the free variable x does not need to be defined when I define myfunc.

However, the following codes do not work:

```<code>class myclass:
   func = extfunc

def extfunc(self):
    return 'hello'
</code>```

Here I need to move the definition of extfunc before the class definition, in order to make the codes work.

Why does class definition need more information of its attributes than what is needed for a free variable in a function definition?

答:
This code:

```<code>def myfunc():
    return x
</code>```

defines a function, but doesn't execute the code inside it where x is until/unless myfunc is called. The body of the function isn't evaluated when the function definition is evaluated, it's evaluated later when the function is called.

In contrast, in this code:

```<code>class myclass:
    func = extfunc
</code>```

the class definition is evaluated in order to create the class, as described in the docs here. So func = extfunc is evaluated as part of class definition in order to assign a value to the func variable in the class scope. func is like a static member in languages that use that terminology.

A more direct comparison would be this:

```<code>class myclass:
    def example(self):
        return x
</code>```

There, return x isn't evaluated until or unless example is called.

See also this example in the documentation:

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

```<code>class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
</code>```

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively.

In your example, myclass.func would be a valid reference immediately after the class definition, so func = extfunc must be evaluated during the class definition, unlike the body of a function.

Body:
def myfunc():
    return x
x = 10
print(myfunc())

The above codes work, where the free variable x does not need to be defined when I define myfunc.

However, the following codes do not work:

class myclass:
   func = extfunc

def extfunc(self):
    return 'hello'

Here I need to move the definition of extfunc before the class definition, in order to make the codes work.

Why does class definition need more information of its attributes than what is needed for a free variable in a function definition?

Body:
This code:

def myfunc():
    return x

defines a function, but doesn't execute the code inside it where x is until/unless myfunc is called. The body of the function isn't evaluated when the function definition is evaluated, it's evaluated later when the function is called.

In contrast, in this code:

class myclass:
    func = extfunc

the class definition is evaluated in order to create the class, as described in the docs here. So func = extfunc is evaluated as part of class definition in order to assign a value to the func variable in the class scope. func is like a static member in languages that use that terminology.

A more direct comparison would be this:

class myclass:
    def example(self):
        return x

There, return x isn't evaluated until or unless example is called.

See also this example in the documentation:

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively.

In your example, myclass.func would be a valid reference immediately after the class definition, so func = extfunc must be evaluated during the class definition, unlike the body of a function.


问:
How do I copy folders in Workspace to another workspace/different instance of talend?
I copied my workspace (jobs/folders from an old PC) down to a shared drive, and copied them into my workspace on my new pc - but they are not showing up when I open talend as a Project? How do I  import them?</p>

答:
Best way to import your jobs is

Open talend on old server.

right click on your folder under which all your jobs exist

Select Export items

Select archive file. Name it. Select Export Dependencies. --> Finish.

Transfer this zip file to shared drive.

Through shared drive transfer to new server.

On new server open talend and Import project from archive file.


问:
Parsing a comment made by "github-actions" bot into JSON
On every pull request that has a specific label our github-actions bot makes an automatic comment that includes a template which needs to be edited by the PR approver, before it can be merged.

The template the bot comments is as follows:

```<code>        **Hello, @${{ github.actor }}!**
        **This component is critical!**
        **Edit and input the following BEFORE approving the PR!**
        ___
        * Description: XXXXXXXXXX
        * Justification: XXXXXXXXXX

        The last change was authored by:
        @${{ github.event.pull_request.user.login }}
</code>```

The Description and Justification fields are replaced with actual values manually by the PR approver (it is not possible to know these in advance). Their values need to be saved as: change_description and justification to be stored in a .json file like so:

```<code>{"change_date": "<Date when PR Merged>", "change_id": "<Pull Request Link>", "change_description": "<from PR Comment>", "component": "<from terragrunt.hcl file>", "justification": "<from PR Comment>", "team": "<from terragrunt.hcl file>"}
</code>```

I've gotten as far as saving the comment body as an environment variable in a new Github action, where I want to parse the comment and save it into a .json file:

```<code>  env:
    BODY: ${{ github.event.comment.body }}
</code>```

All of the logic so far as been simple enough, but now I cannot find a way to pull the values of the Description and Justification from the comment body after they are edited manually. Is this not possible via Github Actions?

答:
Yes it's possible in GitHub Actions.
You have to use regular expressions and bash to parse desired values.

Here is example of regexp to get one of your variables:

\*\*Hello, (.*)\*\*

https://regex101.com/r/Wfww5Y/1

End then in bash you can do:

```<code>[[ $body =~ $regex ]]
$ echo ${BASH_REMATCH[1]}
</code>```

Body:
On every pull request that has a specific label our github-actions bot makes an automatic comment that includes a template which needs to be edited by the PR approver, before it can be merged.

The template the bot comments is as follows:

        **Hello, @${{ github.actor }}!**
        **This component is critical!**
        **Edit and input the following BEFORE approving the PR!**
        ___
        * Description: XXXXXXXXXX
        * Justification: XXXXXXXXXX

        The last change was authored by:
        @${{ github.event.pull_request.user.login }}

The Description and Justification fields are replaced with actual values manually by the PR approver (it is not possible to know these in advance). Their values need to be saved as: change_description and justification to be stored in a .json file like so:

{"change_date": "<Date when PR Merged>", "change_id": "<Pull Request Link>", "change_description": "<from PR Comment>", "component": "<from terragrunt.hcl file>", "justification": "<from PR Comment>", "team": "<from terragrunt.hcl file>"}

I've gotten as far as saving the comment body as an environment variable in a new Github action, where I want to parse the comment and save it into a .json file:

  env:
    BODY: ${{ github.event.comment.body }}

All of the logic so far as been simple enough, but now I cannot find a way to pull the values of the Description and Justification from the comment body after they are edited manually. Is this not possible via Github Actions?

Body:
Yes it's possible in GitHub Actions.
You have to use regular expressions and bash to parse desired values.

Here is example of regexp to get one of your variables:

\*\*Hello, (.*)\*\*

https://regex101.com/r/Wfww5Y/1

End then in bash you can do:

[[ $body =~ $regex ]]
$ echo ${BASH_REMATCH[1]}


问:
Can MongoDB databases be stored in different directories?
I'm having trouble figuring out the answer to this one:

Am I supposed to run one instance of MongoDB for each directory location?

Or am I supposed to store all databases in the same location?

Or Do I run one MongoDB instance and can specify a different location for each database at run time?

答: You can use the --directoryperdb option of mongodb to store each DB in a different physical location.</p>


问:
React, Typescript, and a setState({ [name]: value }) error
I have a couple create-react-app + TypeScript apps that I've been working on over the past few months. At some point (I probably upgraded the lib) tslint started throwing errors on this.setState({ [name]: value }) when state is given a type. It used to let it slide (unless I'm going crazy... not out of the question).

The only way to get tslint to shut up about it, is to change the state type to any, which I don't want to do. If I save the file and let yarn start pick up the change, it runs fine... so I'm able to ignore the error that tslint throws in vscode.

I understand WHY tslint is throwing an error. I'm wondering if there's a rule I can set to ignore this particular error?

Example of where I see this (line 5):

```<code>class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
...
private handleOnChange = (event: any) => {
    const { name, value } = event.target;
    this.setState({ [name]: value });        <-- tslint no likey
}
</code>```

The error:

[ts]
  Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IMyComponentState| ((prevState: Readonly, pro...'.
    Type '{ [x: number]: any; }' is not assignable to type 'Pick

答:
You can add property [key: string]: any; to existing interface declaration IMyComponentState i.e

interface IMyComponentState{
  ...existing fields,
  [x:string]:any
}
```

Body:
I have a couple create-react-app + TypeScript apps that I've been working on over the past few months. At some point (I probably upgraded the lib) tslint started throwing errors on this.setState({ [name]: value }) when state is given a type. It used to let it slide (unless I'm going crazy... not out of the question).

The only way to get tslint to shut up about it, is to change the state type to any, which I don't want to do. If I save the file and let yarn start pick up the change, it runs fine... so I'm able to ignore the error that tslint throws in vscode.

I understand WHY tslint is throwing an error. I'm wondering if there's a rule I can set to ignore this particular error?

Example of where I see this (line 5):

class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
...
private handleOnChange = (event: any) => {
    const { name, value } = event.target;
    this.setState({ [name]: value });        <-- tslint no likey
}

The error:

[ts]
  Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IMyComponentState| ((prevState: Readonly, pro...'.
    Type '{ [x: number]: any; }' is not assignable to type 'Pick


问:
Dynamic naming for build artifacts zip file
in my repo, I have yml file with the code below /.github/workflows/filename.yml

```<code> -  name: Create Artifact
     uses: actions/upload-artifiact@v2
     with:
       name: Report.22.9.zip
       path: |
         project
         !project/Reports/*
         !project/Logs/*
         !project/Snapshots/*
</code>```

Now, I'm trying to make "name: Report.22.9.zip" more dynamic. Something like this

```<code><repo_name>.<branch_name>.<git_build_id>.zip
</code>```

答:
You can create artifact name in previous step and provide it as output to be used by artifact upload step.</p>
```<code>name: Dynamic artifact name

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Generate artifact name
        id: generate-name
        run: |
          echo "::set-output name=artifact::${{ github.event.repository.name }}.${{ github.ref_name }}.${{ github.run_id }}.zip"

      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: ${{ steps.generate-name.outputs.artifact }}
          path: ./README.md
</code>```

Body:
in my repo, I have yml file with the code below /.github/workflows/filename.yml

 -  name: Create Artifact
     uses: actions/upload-artifiact@v2
     with:
       name: Report.22.9.zip
       path: |
         project
         !project/Reports/*
         !project/Logs/*
         !project/Snapshots/*

Now, I'm trying to make "name: Report.22.9.zip" more dynamic. Something like this

<repo_name>.<branch_name>.<git_build_id>.zip

Body:
You can create artifact name in previous step and provide it as output to be used by artifact upload step.

name: Dynamic artifact name

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Generate artifact name
        id: generate-name
        run: |
          echo "::set-output name=artifact::${{ github.event.repository.name }}.${{ github.ref_name }}.${{ github.run_id }}.zip"

      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: ${{ steps.generate-name.outputs.artifact }}
          path: ./README.md


问:
Why I'm getting Error: connect ENOENT from vscode on git push origin
I'm getting an error when trying to push to github from vscode terminal.</p>
```<code>    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'connect',
  address: '/run/user/1000/snap.code/vscode-git-0e219c7318.sock'
}
Missing or invalid credentials.
Error: connect ENOENT /run/user/1000/snap.code/vscode-git-0e219c7318.sock
    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'connect',
  address: '/run/user/1000/snap.code/vscode-git-0e219c7318.sock'
} ```
This is only happening in vscode terminal cause if I use a different one I dont have this, any solution for this?
</code>```

答: It's a problem of VSC have a look at here. Try to push from console instead.</p>

Body:
I'm getting an error when trying to push to github from vscode terminal.

    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'connect',
  address: '/run/user/1000/snap.code/vscode-git-0e219c7318.sock'
}
Missing or invalid credentials.
Error: connect ENOENT /run/user/1000/snap.code/vscode-git-0e219c7318.sock
    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'connect',
  address: '/run/user/1000/snap.code/vscode-git-0e219c7318.sock'
} ```
This is only happening in vscode terminal cause if I use a different one I dont have this, any solution for this?


问:
COUNTIFS w/ Multiple Criteria in Same Column
I'm trying to count instances of letters (like letters C through Z, excluding RR) within the same column if they are listed next to a name. Here's my sample Google Sheet that you can edit.

I'm trying to insert the formula in cell F3 that is highlighted yellow. So far I have...

```<code>=arrayformula(SUM(COUNTIFS(A2:A,{"C","D","E","F","G"},C2:C,E3:E)))
</code>```

It seems like what I have should work, but it's giving me a #VALUE error, saying, "ARRAY arguments to COUNTIFS are of different size".

It seems like REGEXMATCH could be used inside the COUNTIF formula to make it easier to restrict the search to the range of letters I need, but not sure how to construct the formula.

Thanks for your help!

UPDATE
This formula below works but only for column A. I actually need to specify a different range of letters to be counted in column B and totaled in column K.

```<code>=QUERY(A2:C,"select C,count(A) where A matches 'C|D|E|F|G|H|I|J|K' group by C label count(A)''", 0)
</code>```

Seems like this post almost answers it.

答:
A 2-formula solution was found to work as well. Answer is in the same spreadsheet linked above in Sheet2. It should prevent the first formula from not working should someone need a different one.

J2 - =QUERY(A2:C,"select C,count(A) where A matches 'C|D|E|F|G|H|I|J|K' group by C label count(A)''", 0)

L2 - =ArrayFormula(IFNA(vlookup(J2:J,QUERY(A2:C,"select C,count(B) where B matches 'F|G|H|I|J|K' group by C label count(B)''", 0),2,0)))

Body:
I'm trying to count instances of letters (like letters C through Z, excluding RR) within the same column if they are listed next to a name. Here's my sample Google Sheet that you can edit.

I'm trying to insert the formula in cell F3 that is highlighted yellow. So far I have...

=arrayformula(SUM(COUNTIFS(A2:A,{"C","D","E","F","G"},C2:C,E3:E)))

It seems like what I have should work, but it's giving me a #VALUE error, saying, "ARRAY arguments to COUNTIFS are of different size".

It seems like REGEXMATCH could be used inside the COUNTIF formula to make it easier to restrict the search to the range of letters I need, but not sure how to construct the formula.

Thanks for your help!

UPDATE
This formula below works but only for column A. I actually need to specify a different range of letters to be counted in column B and totaled in column K.

=QUERY(A2:C,"select C,count(A) where A matches 'C|D|E|F|G|H|I|J|K' group by C label count(A)''", 0)

Seems like this post almost answers it.