问:
How do I visualise the p95/p99 for a Cloudwatch data source in Grafana?
We're using the Cloudwatch data source in Grafana. I can see in Cloudwatch we can dynamically type in a pXX value of p95 for instance:

But in Grafana I can only see the following: Average, Maximum, Minimum, SampleCount

答:
There's two ways to do it:

Type it in

You can type in p95 into the Statistic box (the dropdown won't show you the option, but you can type it in).

Note you also can't delete the text elements - typing it in will overwrite it.

Making a variable

The other way I found how to do this is to add a custom variable:

I included the Maximum,Minimum,Average and then I added p95 and p90 (but you can add any p value).

You can also add any of the other statistics here:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Statistics-definitions.html

Then in the Grafana dashboard set the variable statistic (or whatever you decide to call it) to your new variable and your graph will now show p95.


来源: stackexchange

问:
KafkaProducer does not send messages in multiprocessing.Process
I got the following concept, which is a simplified example of a real app. The problem is that the producer will not produce messages while working in a multiprocessing.Process process.

```<code>import logging
import multiprocessing
import os

from kafka import KafkaProducer

KAFKA_HOST = os.getenv('KAFKA_HOST')
KAFKA_PORT = os.getenv('KAFKA_PORT')
KAFKA_NAME = os.getenv('KAFKA_NAME')

producer = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')

def test_produce():
    # producer1 = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')
    for i in range(10):
        print('inserting') # prints once
        producer.send(KAFKA_NAME, b'test').get() # will not be commited in the topic

producer.send(KAFKA_NAME, b'test_in_non_thread1').get() # will be commited in the topic
producer.send(KAFKA_NAME, b'test_in_non_thread2').get() # will be commited in the topic
multiprocessing.Process(target=test_produce).start()
</code>```

答:
The problem lies in process-across object serialization, which causes the producer to be serialized whatever-wrong. The solution is to create local producer instances inside your multiprocessed function

```<code>import logging
import multiprocessing
import os

from kafka import KafkaProducer

KAFKA_HOST = os.getenv('KAFKA_HOST')
KAFKA_PORT = os.getenv('KAFKA_PORT')
KAFKA_NAME = os.getenv('KAFKA_NAME')

producer = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')

def test_produce():
    producer1 = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')
    for i in range(10):
        print('inserting') # prints 10 times
        producer1.send(KAFKA_NAME, b'test').get() #all messages will be commited

producer.send(KAFKA_NAME, b'test_in_non_thread1').get() # will be commited in the topic
producer.send(KAFKA_NAME, b'test_in_non_thread2').get() # will be commited in the topic
multiprocessing.Process(target=test_produce).start()
</code>```

This way everything works as it is supposed to be. By the way, you can use threading.Thread, which will not cause such an issue.

https://github.com/dpkp/kafka-python/issues/1416

ContentLicense: CC BY-SA 4.0

Body:
I got the following concept, which is a simplified example of a real app. The problem is that the producer will not produce messages while working in a multiprocessing.Process process.

import logging
import multiprocessing
import os

from kafka import KafkaProducer

KAFKA_HOST = os.getenv('KAFKA_HOST')
KAFKA_PORT = os.getenv('KAFKA_PORT')
KAFKA_NAME = os.getenv('KAFKA_NAME')

producer = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')

def test_produce():
    # producer1 = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')
    for i in range(10):
        print('inserting') # prints once
        producer.send(KAFKA_NAME, b'test').get() # will not be commited in the topic

producer.send(KAFKA_NAME, b'test_in_non_thread1').get() # will be commited in the topic
producer.send(KAFKA_NAME, b'test_in_non_thread2').get() # will be commited in the topic
multiprocessing.Process(target=test_produce).start()

Body:
The problem lies in process-across object serialization, which causes the producer to be serialized whatever-wrong. The solution is to create local producer instances inside your multiprocessed function

import logging
import multiprocessing
import os

from kafka import KafkaProducer

KAFKA_HOST = os.getenv('KAFKA_HOST')
KAFKA_PORT = os.getenv('KAFKA_PORT')
KAFKA_NAME = os.getenv('KAFKA_NAME')

producer = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')

def test_produce():
    producer1 = KafkaProducer(bootstrap_servers=f'{KAFKA_HOST}:{KAFKA_PORT}')
    for i in range(10):
        print('inserting') # prints 10 times
        producer1.send(KAFKA_NAME, b'test').get() #all messages will be commited

producer.send(KAFKA_NAME, b'test_in_non_thread1').get() # will be commited in the topic
producer.send(KAFKA_NAME, b'test_in_non_thread2').get() # will be commited in the topic
multiprocessing.Process(target=test_produce).start()

This way everything works as it is supposed to be. By the way, you can use threading.Thread, which will not cause such an issue.

https://github.com/dpkp/kafka-python/issues/1416


问:
When using rvm ruby 3.0.0 OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed

Description

Hi we are using rvm on macos-big sur AWS ec2 machines but it seems that there is an issue with rvm and openssl

Steps to reproduce

We installed rvm and ruby via packer

brew install gpg2
echo " ------------------ GPG2 Installation completed -----------------------"
curl -sSL https://rvm.io/mpapis.asc | gpg --import -
curl -sSL https://rvm.io/pkuczynski.asc | gpg --import -
curl -sSL https://get.rvm.io | bash -s stable
source ~/.bash_profile && rvm install "ruby-3.0.0"
```
<p>It looks okay</p>
<pre class="lang-sh prettyprint-override"><code>rvm use 3.0.0
openssl version
which openssl
</code>```

Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
/usr/bin/openssl
LibreSSL 2.8.3

But when I

git clone https://github.com/mislav/ssl-tools.git
ruby ssl-tools/doctor.rb
```
<p>I get an error</p>
<blockquote>
<p>Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
/Users/ec2-user/.rvm/rubies/ruby-3.0.0/bin/ruby (3.0.0-p0)
OpenSSL 1.1.1m  14 Dec 2021: /usr/local/etc/openssl@1.1
SSL_CERT_DIR=""
SSL_CERT_FILE=""</p>
<p>HEAD https://status.github.com:443
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate)</p>
<p>The server presented a certificate that could not be verified:
subject: /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
issuer: /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
error code 20: unable to get local issuer certificate</p>
<p>Possible causes:
<code>/usr/local/etc/openssl@1.1/cert.pem' does not exist </code>/usr/local/etc/openssl@1.1/certs/' is empty</p>
</blockquote>
<p>When I</p>
<pre class="lang-sh prettyprint-override"><code>brew doctor
</code>```

I get

Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!

Warning: Homebrew's "sbin" was not found in your PATH but you have installed
formulae that put executables in /usr/local/sbin.
Consider setting your PATH for example like so:
echo 'export PATH="/usr/local/sbin:$PATH"' >> ~/.zshrc

Warning: Broken symlinks were found. Remove them with brew cleanup:
/usr/local/etc/gnutls/cert.pem
/usr/local/etc/openssl@1.1/cert.pem

Asked the same question in github.com/rvm

答:
This was the solution that worked

In ~/.bashrc

```<code># Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"
</code>```

In ~/.bash_profile

```<code>[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
</code>```

In ~/.zshrc

```<code># Avoid warning: Homebrew's "sbin" was not found in your PATH but you have installed formulae that put executables in /usr/local/sbin
export PATH="/usr/local/sbin:$PATH"
# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"
</code>```

In provisioner

```<code># Remove broken symlinks before using brew
/usr/local/bin/brew cleanup

/usr/local/bin/brew install gpg2
echo "------------------ GPG2 Installation completed -----------------"
curl -sSL https://rvm.io/mpapis.asc | /usr/local/bin/gpg --import -
curl -sSL https://rvm.io/pkuczynski.asc | /usr/local/bin/gpg --import -
curl -sSL https://get.rvm.io | bash -s stable --auto-dotfiles
source ~/.bash_profile
</code>```

Body:
Description

Hi we are using rvm on macos-big sur AWS ec2 machines but it seems that there is an issue with rvm and openssl

Steps to reproduce

We installed rvm and ruby via packer

brew install gpg2
echo " ------------------ GPG2 Installation completed -----------------------"
curl -sSL https://rvm.io/mpapis.asc | gpg --import -
curl -sSL https://rvm.io/pkuczynski.asc | gpg --import -
curl -sSL https://get.rvm.io | bash -s stable
source ~/.bash_profile && rvm install "ruby-3.0.0"

It looks okay

rvm use 3.0.0
openssl version
which openssl

Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
/usr/bin/openssl
LibreSSL 2.8.3

But when I

git clone https://github.com/mislav/ssl-tools.git
ruby ssl-tools/doctor.rb

I get an error

Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
/Users/ec2-user/.rvm/rubies/ruby-3.0.0/bin/ruby (3.0.0-p0)
OpenSSL 1.1.1m  14 Dec 2021: /usr/local/etc/openssl@1.1
SSL_CERT_DIR=""
SSL_CERT_FILE=""

HEAD https://status.github.com:443
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate)

The server presented a certificate that could not be verified:
subject: /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
issuer: /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
error code 20: unable to get local issuer certificate

Possible causes:
/usr/local/etc/openssl@1.1/cert.pem' does not exist /usr/local/etc/openssl@1.1/certs/' is empty

When I

brew doctor

I get

Using /Users/ec2-user/.rvm/gems/ruby-3.0.0
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!

Warning: Homebrew's "sbin" was not found in your PATH but you have installed
formulae that put executables in /usr/local/sbin.
Consider setting your PATH for example like so:
echo 'export PATH="/usr/local/sbin:$PATH"' >> ~/.zshrc

Warning: Broken symlinks were found. Remove them with brew cleanup:
/usr/local/etc/gnutls/cert.pem
/usr/local/etc/openssl@1.1/cert.pem

Asked the same question in github.com/rvm

Body:
This was the solution that worked

In ~/.bashrc

# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"

In ~/.bash_profile

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

In ~/.zshrc

# Avoid warning: Homebrew's "sbin" was not found in your PATH but you have installed formulae that put executables in /usr/local/sbin
export PATH="/usr/local/sbin:$PATH"
# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"

In provisioner

# Remove broken symlinks before using brew
/usr/local/bin/brew cleanup

/usr/local/bin/brew install gpg2
echo "------------------ GPG2 Installation completed -----------------"
curl -sSL https://rvm.io/mpapis.asc | /usr/local/bin/gpg --import -
curl -sSL https://rvm.io/pkuczynski.asc | /usr/local/bin/gpg --import -
curl -sSL https://get.rvm.io | bash -s stable --auto-dotfiles
source ~/.bash_profile


问:
How to set a fixed DATABASE_URL for Heroku Postgres
I am using a professional tier Heroku Postgres database. The DATABASE_URL changes whenever maintenance is conducted. This fact makes it essentially impossible for us to connect external apps to this database instance since they break at regular intervals whenever maintenance is conducted.

I require a static, unchanging URL or IP address to my Postgres instance so that external applications can have an uninterrupted connection to the database across maintenance windows.

Is there a recommended way of setting this up? If not I will have to perform a migration to some other service provider because performing an update to all my infrastructure or creating polling mechanisms to get around this problem is not feasible.

A less important question but why does Heroku Postsgres keep changing the URL? Is it for security? There is nothing in their documentation that explains why this happens.

答:
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku

The database URL is managed by Heroku and will change under some circumstances such as:

User-initiated database credential rotations using heroku pg:credentials:rotate.

Catastrophic hardware failures that require Heroku Postgres staff to recover your database on new hardware.

Security issues or threats that require Heroku Postgres staff to rotate database credentials.

Automated failover events on HA-enabled plans.

Check if this is an option for your setup:

```<code>DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
</code>```

You supply the DATABASE_URL to your external app/process. You can also build a small service that redirects a static URL to that dynamic DATABASE_URL.

Body:
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku

The database URL is managed by Heroku and will change under some circumstances such as:

User-initiated database credential rotations using heroku pg:credentials:rotate.

Catastrophic hardware failures that require Heroku Postgres staff to recover your database on new hardware.

Security issues or threats that require Heroku Postgres staff to rotate database credentials.

Automated failover events on HA-enabled plans.

Check if this is an option for your setup:

DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process

You supply the DATABASE_URL to your external app/process. You can also build a small service that redirects a static URL to that dynamic DATABASE_URL.


问:
Use drag and drop cursor java swing or javafx
I would like to change the cursor to use the drag and drop "move" and "move and copy" cursors in my application on a panel when I perform certain actions. The area is using swing inside of a swing node so a swing (Apply to panel) or JavaFx (Applying to swing node) solution would work.

I did find swing cursors DragSource.DefaultMoveDrop and DragSource.DefaultCopyDrop but when I apply them my cursor doesn't change. (And I know I am applying the cursor correctly as applying other cursors work fine)

EDIT: Note that when not nested in a SwingNode and in a JFrame instead the cursor does change to what I want. I have amended the code example to emulate the environment I am in where it doesn't work:

```<code>public class Temp extends Application {

    public static void main(String[] args) {
        Application.launch();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        SwingNode swingNode = new SwingNode();
        SwingUtilities.invokeLater(() -> {
            JPanel panel = new JPanel();
            panel.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); //Change this
            swingNode.setContent(panel);
        });
        Scene scene = new Scene(new BorderPane(swingNode));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
</code>```

答:
Ok turns out it works DragSource.DefaultMoveDrop and DragSource.DefaultCopyDrop actually work in a normal swing application, just not on JPanel inside a SwingNode which the environment I am working in uses. (I can't change this)

Therefore if you run into this issue and you are NOT mixing the frameworks this forms an answer.

Body:
I would like to change the cursor to use the drag and drop "move" and "move and copy" cursors in my application on a panel when I perform certain actions. The area is using swing inside of a swing node so a swing (Apply to panel) or JavaFx (Applying to swing node) solution would work.

I did find swing cursors DragSource.DefaultMoveDrop and DragSource.DefaultCopyDrop but when I apply them my cursor doesn't change. (And I know I am applying the cursor correctly as applying other cursors work fine)

EDIT: Note that when not nested in a SwingNode and in a JFrame instead the cursor does change to what I want. I have amended the code example to emulate the environment I am in where it doesn't work:

public class Temp extends Application {

    public static void main(String[] args) {
        Application.launch();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        SwingNode swingNode = new SwingNode();
        SwingUtilities.invokeLater(() -> {
            JPanel panel = new JPanel();
            panel.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); //Change this
            swingNode.setContent(panel);
        });
        Scene scene = new Scene(new BorderPane(swingNode));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}


问:
Regular expression for recognizing url
I want to create a Regex for url in order to get all links from input string.
The Regex should recognize the following formats of the url address:

http(s)://www.webpage.com

http(s)://webpage.com

www.webpage.com

and also the more complicated urls like:
 - http://www.google.pl/#sclient=psy&hl=pl&site=&source=hp&q=regex+url&pbx=1&oq=regex+url&aq=f&aqi=g1&aql=&gs_sm=e&gs_upl=1582l3020l0l3199l9l6l0l0l0l0l255l1104l0.2.3l5l0&bav=on.2,or.r_gc.r_pw.&fp=30a1604d4180f481&biw=1680&bih=935

I have the following one

```<code>((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)
</code>```

but it does not recognize the following pattern: www.webpage.com. Can someone please help me to create an appropriate Regex?

EDIT:
It should works to find an appropriate link and moreover place a link in an appropriate index like this:

```<code>private readonly Regex RE_URL = new Regex(@"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", RegexOptions.Multiline);
foreach (Match match in (RE_URL.Matches(new_text)))
            {
                // Copy raw string from the last position up to the match
                if (match.Index != last_pos)
                {
                    var raw_text = new_text.Substring(last_pos, match.Index - last_pos);
                    text_block.Inlines.Add(new Run(raw_text));
                }

                // Create a hyperlink for the match
                var link = new Hyperlink(new Run(match.Value))
                {
                    NavigateUri = new Uri(match.Value)
                };
                link.Click += OnUrlClick;

                text_block.Inlines.Add(link);

                // Update the last matched position
                last_pos = match.Index + match.Length;
            }
</code>```

答:
The regex you give doesn't work for www. addresses because it is expecting a URI scheme (the bit before the URL, like http://). The 'www.' part in your regular expression doesn't work because it would only match www.:// (which is meaningless)

Try something like this instead:

```<code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)
</code>```

This will match something with a valid URI scheme, or something beginning with 'www.'

ContentLicense: CC BY-SA 3.0

Title: Regular expression for recognizing url

Body:
I want to create a Regex for url in order to get all links from input string.
The Regex should recognize the following formats of the url address:

http(s)://www.webpage.com

http(s)://webpage.com

www.webpage.com

and also the more complicated urls like:
 - http://www.google.pl/#sclient=psy&hl=pl&site=&source=hp&q=regex+url&pbx=1&oq=regex+url&aq=f&aqi=g1&aql=&gs_sm=e&gs_upl=1582l3020l0l3199l9l6l0l0l0l0l255l1104l0.2.3l5l0&bav=on.2,or.r_gc.r_pw.&fp=30a1604d4180f481&biw=1680&bih=935

I have the following one

((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)

but it does not recognize the following pattern: www.webpage.com. Can someone please help me to create an appropriate Regex?

EDIT:
It should works to find an appropriate link and moreover place a link in an appropriate index like this:

private readonly Regex RE_URL = new Regex(@"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", RegexOptions.Multiline);
foreach (Match match in (RE_URL.Matches(new_text)))
            {
                // Copy raw string from the last position up to the match
                if (match.Index != last_pos)
                {
                    var raw_text = new_text.Substring(last_pos, match.Index - last_pos);
                    text_block.Inlines.Add(new Run(raw_text));
                }

                // Create a hyperlink for the match
                var link = new Hyperlink(new Run(match.Value))
                {
                    NavigateUri = new Uri(match.Value)
                };
                link.Click += OnUrlClick;

                text_block.Inlines.Add(link);

                // Update the last matched position
                last_pos = match.Index + match.Length;
            }

Body:
The regex you give doesn't work for www. addresses because it is expecting a URI scheme (the bit before the URL, like http://). The 'www.' part in your regular expression doesn't work because it would only match www.:// (which is meaningless)

Try something like this instead:

(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)

This will match something with a valid URI scheme, or something beginning with 'www.'


问:
How to show/hide @foreach statement
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

```
<p>I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).</p>
<p>I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?</p>
<p>-- EDIT --</p>
<p>I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

        <slot />

</template>

<script>
export default {
    name: "Dropdownitems",
    setup() {
        const showLinks = false;

        return {
            showLinks,
        };
    },
};
</script>

<style></style></code>```

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

```

答:
Try with a @if directive:

Conditional Rendering

from the documentation:

```<code><button @click="awesome = !awesome">Toggle</button>

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no </h1>
</code>```

As showed in the example it render the "h1" tag conditionally respect the "awesome" variable.
In this case i will set a default value of "false" and i will turn it to "true" in the mounted hook:

Lifecycle

Title: How to show/hide @foreach statement

Body:
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).

I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?

-- EDIT --

I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:

<template>

        <slot />

</template>

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

Body:
Try with a @if directive:

Conditional Rendering

from the documentation:

<button @click="awesome = !awesome">Toggle</button>

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no </h1>

As showed in the example it render the "h1" tag conditionally respect the "awesome" variable.
In this case i will set a default value of "false" and i will turn it to "true" in the mounted hook:

Lifecycle


问:
'pipwin' is not recognized as an internal or external command
It is showing like this:

```<code>'pipwin' is not recognized as an internal or external command,
operable program or batch file
</code>```

.
How to solve this issue i am beginner please help!!

答:
Try this:

```<code>pip install pipwin
pipwin install [Your packagename]
</code>```

Or
Add Path of scripts to environment variable

```<code>set PATH=%PATH%;C:\Users\DELL\AppData\Roaming\Python\Python39\Scripts
</code>```

Body:
It is showing like this:

'pipwin' is not recognized as an internal or external command,
operable program or batch file

.
How to solve this issue i am beginner please help!!

Body:
Try this:

pip install pipwin
pipwin install [Your packagename]

Or
Add Path of scripts to environment variable

set PATH=%PATH%;C:\Users\DELL\AppData\Roaming\Python\Python39\Scripts


问:
devServer doent work for multiply entries in webpack
I'm trying to do react app with two diferent entries. One for admin and another for user.
this is my webpack.config

```<code>const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
require('dotenv').config();
const Dotenv = require('dotenv-webpack');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (env, argv) => {
    const isDevelopment =
        process.env.NODE_ENV !== 'production' && argv.mode !== 'production';
    console.log('isDevelopment', isDevelopment);
    return {
        mode: isDevelopment ? 'development' : 'production',
        devtool: isDevelopment ? 'inline-cheap-source-map' : false,
        target: 'web',
        resolve: {
            alias: {
                Components: path.resolve(__dirname, 'src/components/'),
                Auth: path.resolve(__dirname, 'src/components/auth'),
                Editor: path.resolve(__dirname, 'src/components/editor'),
                Ui: path.resolve(__dirname, 'src/components/ui'),
                UserCabinet: path.resolve(
                    __dirname,
                    'src/components/userCabinet'
                ),
                Context: path.resolve(__dirname, 'src/context'),
                Services: path.resolve(__dirname, 'src/services'),
                Utils: path.resolve(__dirname, 'src/utils'),
            },
        },
        plugins: [
            new HtmlWebpackPlugin({
                chunks: ['index'],
                template: 'public/index.html',
            }),
            new HtmlWebpackPlugin({
                chunks: ['admin'],
                filename: 'admin/index.html',
                template: 'public/admin.html',
            }),
            isDevelopment && new ReactRefreshWebpackPlugin(),
            new Dotenv(),
            new CopyPlugin({
                patterns: [
                    { from: './src/manifest.json', to: '' },
                    { from: './src/service-worker.js', to: '' },
                    { from: './src/offline.html', to: '' },
                ],
            }),
        ].filter(Boolean),
        entry: {
            index: './src/index.js',
            admin: './src/admin.js',
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            publicPath: '/',
            filename: isDevelopment
                ? '[name]__[contenthash:4].js'
                : '[contenthash].js',
            clean: true,
        },
        optimization: {
            runtimeChunk: { name: 'runtime' },
        },
        performance: {
            hints: false,
        },
        devServer: {
            historyApiFallback: {
                disableDotRule: true,
                rewrites: [{ from: /^\/admin\/.*$/, to: 'admin.html' }],
            },
            static: {
                directory: path.join(__dirname, 'dist'),
                serveIndex: true,
                watch: true,
            },
            hot: true,
        },
        stats: 'errors-warnings',
        module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: require.resolve('babel-loader'),
                            options: {
                                plugins: [
                                    isDevelopment &&
                                        require.resolve('react-refresh/babel'),
                                ].filter(Boolean),
                            },
                        },
                    ],
                },
                {
                    test: /\.css$/,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: {
                                    localIdentName: '[local]',
                                },
                            },
                        },
                    ],
                },
                {
                    test: /\.s[ac]ss$/i,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: {
                                    localIdentName: isDevelopment
                                        ? '[name].[local]__[hash:base64:5]'
                                        : '[hash]',
                                },
                            },
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sassOptions: {
                                    includePaths: [
                                        path.join(__dirname, 'src/styles'),
                                    ],
                                },
                                additionalData: `@import "_variables.scss";`,
                            },
                        },
                    ],
                },
                {
                    test: /\.(png|jpe?g|gif|svg|woff2)$/,
                    type: 'asset',
                },
            ],
        },
    };
};
</code>```

And in only works for
for all another routes it shows Cannot GET {path}.

As I understoot I have a problem with devServer, because it not working write for second app. Because browser doesnt see admin.html and admin.js

DO you have any ideas what is wrong?

答:
I have found my mistake.
It was because I write wrong rewrites for DevServer.
So the write way is :  rewrites: [{ from: /^/admin/.*$/, to: 'admin/index.html' }],</p>

Body:
I'm trying to do react app with two diferent entries. One for admin and another for user.
this is my webpack.config

const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
require('dotenv').config();
const Dotenv = require('dotenv-webpack');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (env, argv) => {
    const isDevelopment =
        process.env.NODE_ENV !== 'production' && argv.mode !== 'production';
    console.log('isDevelopment', isDevelopment);
    return {
        mode: isDevelopment ? 'development' : 'production',
        devtool: isDevelopment ? 'inline-cheap-source-map' : false,
        target: 'web',
        resolve: {
            alias: {
                Components: path.resolve(__dirname, 'src/components/'),
                Auth: path.resolve(__dirname, 'src/components/auth'),
                Editor: path.resolve(__dirname, 'src/components/editor'),
                Ui: path.resolve(__dirname, 'src/components/ui'),
                UserCabinet: path.resolve(
                    __dirname,
                    'src/components/userCabinet'
                ),
                Context: path.resolve(__dirname, 'src/context'),
                Services: path.resolve(__dirname, 'src/services'),
                Utils: path.resolve(__dirname, 'src/utils'),
            },
        },
        plugins: [
            new HtmlWebpackPlugin({
                chunks: ['index'],
                template: 'public/index.html',
            }),
            new HtmlWebpackPlugin({
                chunks: ['admin'],
                filename: 'admin/index.html',
                template: 'public/admin.html',
            }),
            isDevelopment && new ReactRefreshWebpackPlugin(),
            new Dotenv(),
            new CopyPlugin({
                patterns: [
                    { from: './src/manifest.json', to: '' },
                    { from: './src/service-worker.js', to: '' },
                    { from: './src/offline.html', to: '' },
                ],
            }),
        ].filter(Boolean),
        entry: {
            index: './src/index.js',
            admin: './src/admin.js',
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            publicPath: '/',
            filename: isDevelopment
                ? '[name]__[contenthash:4].js'
                : '[contenthash].js',
            clean: true,
        },
        optimization: {
            runtimeChunk: { name: 'runtime' },
        },
        performance: {
            hints: false,
        },
        devServer: {
            historyApiFallback: {
                disableDotRule: true,
                rewrites: [{ from: /^\/admin\/.*$/, to: 'admin.html' }],
            },
            static: {
                directory: path.join(__dirname, 'dist'),
                serveIndex: true,
                watch: true,
            },
            hot: true,
        },
        stats: 'errors-warnings',
        module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: require.resolve('babel-loader'),
                            options: {
                                plugins: [
                                    isDevelopment &&
                                        require.resolve('react-refresh/babel'),
                                ].filter(Boolean),
                            },
                        },
                    ],
                },
                {
                    test: /\.css$/,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: {
                                    localIdentName: '[local]',
                                },
                            },
                        },
                    ],
                },
                {
                    test: /\.s[ac]ss$/i,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: {
                                    localIdentName: isDevelopment
                                        ? '[name].[local]__[hash:base64:5]'
                                        : '[hash]',
                                },
                            },
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sassOptions: {
                                    includePaths: [
                                        path.join(__dirname, 'src/styles'),
                                    ],
                                },
                                additionalData: `@import "_variables.scss";`,
                            },
                        },
                    ],
                },
                {
                    test: /\.(png|jpe?g|gif|svg|woff2)$/,
                    type: 'asset',
                },
            ],
        },
    };
};

And in only works for
for all another routes it shows Cannot GET {path}.

As I understoot I have a problem with devServer, because it not working write for second app. Because browser doesnt see admin.html and admin.js

DO you have any ideas what is wrong?


问:
A compound WHERE clause in GAQL?
Could you please confirm GQAL doesn't support compound WHERE clause?

```<code> FROM group_placement_view\
 WHERE\
    metrics.impressions >= 10000 \
    AND (metrics.video_view_rate < 10' OR metrics.average_cpm > 10000 )
</code>```

and not event OR as non-compound clause?

```<code>    metrics.average_cpm\
 FROM group_placement_view\
 WHERE\
    metrics.impressions >= 10000 \
    OR metrics.video_view_rate < 10'
</code>```

答: WHERE clause may only contain AND conditions https://developers.google.com/google-ads/api/docs/query/grammar</p>

Title: A compound WHERE clause in GAQL?

Body:
Could you please confirm GQAL doesn't support compound WHERE clause?

 FROM group_placement_view\
 WHERE\
    metrics.impressions >= 10000 \
    AND (metrics.video_view_rate < 10' OR metrics.average_cpm > 10000 )

and not event OR as non-compound clause?

    metrics.average_cpm\
 FROM group_placement_view\
 WHERE\
    metrics.impressions >= 10000 \
    OR metrics.video_view_rate < 10'


问:
log4net items not shown in AppServiceAppLogs
We are using log4net for our application logging in azure.
We configured it according to this document , the logs are stored in

```<code>d:/home/LogFiles/Application/Log4netfile-[%processid].txt
</code>```

we can download the files from https://xxxx.scm.azurewebsites.net/api/dump and I can also see them in Log stream, there it looks like this

```<code>2022-02-06T18:22:57  PID[29616] Verbose     log4net: Adding appender named [FileAppender] to logger [root].
2022-02-06T18:22:57  PID[29616] Verbose     log4net: Hierarchy Threshold []
2022-02-06T18:22:58  PID[29616] Verbose     LOG4NET Fatal LOG4NET LOG4NET
2022-02-06T18:22:58  PID[29616] Verbose     LOG4NET Debug Message Message
</code>```

Line  items like:

```<code>log4net: Adding appender named
</code>```

are created by log4net during internal setup (using debug=true), and those show up in our AppServiceAppLogs,  however, items which are genereted by the logger using:

```<code>Logger.Fatal("LOG4NET Fatal LOG4NET LOG4NET");
</code>```

are visible in stream and files but they are  not showing up in AppServiceLogs.

I tried multiple different appenders the only one which shows up in Log-Streams and in files is FileAppender (or RollingFileAppender), all others are not showing in LogStreams or (as expected) in the files.

Based on this https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs#send-logs-to-azure-monitor I assume that everything writen to the files should be than sent to azure-monitor - but in our case this is not hapening. Could you provide some reference about implementation / code how the sending of the files is done, and which process does that ?

I am wandering is there anything which we could configure differently to get the log-items to end up in AppServiceLogs? Or should we use some other appender?

I am aware of the issue in AspNetTraceAppender and I am trying to avoid implementation of new appender.

答:
There are a few things you can look into:

Call log4net configure before writing to your log file (only once is enough):

```<code>log4net.Config.XmlConfigurator();

</code>```

or

```<code>log4net.Config.XmlConfigurator.Configure();
</code>```

and then you can add flushing to your configuration:

```<code><appender name="AzureTraceAppender" type="log4net.Appender.TraceAppender">
  <param name="ImmediateFlush" value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <!-- can be any pattern you like -->
    <conversionPattern value="%logger - %message" />
  </layout>
</appender>

</code>```

Immediately, this will flush the message.

In Global.asax, To make log4net read your configuration.

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup

    // Initialize log4net.
    log4net.Config.XmlConfigurator.Configure();
}
```

Make sure Azure Diagnostics has configured to all information needed for debugging.

After that, you can enable internal log4net debugging. Refer internal debugging on this log4net faq page. Standard it should log to your listener you have configured. To the trace element Add the autoflush="true" option . Or find directory on the worker role you can write to and access to read your logs.

Body:
We are using log4net for our application logging in azure.
We configured it according to this document , the logs are stored in

d:/home/LogFiles/Application/Log4netfile-[%processid].txt

we can download the files from https://xxxx.scm.azurewebsites.net/api/dump and I can also see them in Log stream, there it looks like this

2022-02-06T18:22:57  PID[29616] Verbose     log4net: Adding appender named [FileAppender] to logger [root].
2022-02-06T18:22:57  PID[29616] Verbose     log4net: Hierarchy Threshold []
2022-02-06T18:22:58  PID[29616] Verbose     LOG4NET Fatal LOG4NET LOG4NET
2022-02-06T18:22:58  PID[29616] Verbose     LOG4NET Debug Message Message

Line  items like:

log4net: Adding appender named

are created by log4net during internal setup (using debug=true), and those show up in our AppServiceAppLogs,  however, items which are genereted by the logger using:

Logger.Fatal("LOG4NET Fatal LOG4NET LOG4NET");

are visible in stream and files but they are  not showing up in AppServiceLogs.

I tried multiple different appenders the only one which shows up in Log-Streams and in files is FileAppender (or RollingFileAppender), all others are not showing in LogStreams or (as expected) in the files.

Based on this https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs#send-logs-to-azure-monitor I assume that everything writen to the files should be than sent to azure-monitor - but in our case this is not hapening. Could you provide some reference about implementation / code how the sending of the files is done, and which process does that ?

I am wandering is there anything which we could configure differently to get the log-items to end up in AppServiceLogs? Or should we use some other appender?

I am aware of the issue in AspNetTraceAppender and I am trying to avoid implementation of new appender.

Body:
There are a few things you can look into:

Call log4net configure before writing to your log file (only once is enough):

log4net.Config.XmlConfigurator();

or

log4net.Config.XmlConfigurator.Configure();

and then you can add flushing to your configuration:

<appender name="AzureTraceAppender" type="log4net.Appender.TraceAppender">
  <param name="ImmediateFlush" value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <!-- can be any pattern you like -->
    <conversionPattern value="%logger - %message" />
  </layout>
</appender>

Immediately, this will flush the message.

In Global.asax, To make log4net read your configuration.

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup

    // Initialize log4net.
    log4net.Config.XmlConfigurator.Configure();
}

Make sure Azure Diagnostics has configured to all information needed for debugging.

After that, you can enable internal log4net debugging. Refer internal debugging on this log4net faq page. Standard it should log to your listener you have configured. To the trace element Add the autoflush="true" option . Or find directory on the worker role you can write to and access to read your logs.


问:
Simulate network failure / offline mode in Capybara?
I have some JavaScript in my app that detects when the network connection goes away and temporarily caches data in local storage, to be synced with the server when the connection is re-established.

I've been trying to find a way to test this end-to-end using Capybara, but I can't seem to find any way of either temporarily disabling the app server or switching the headless browser into offline mode. FWIW I'm using Poltergeist as the driver.

Does anyone have an idea how this could be tested? (I can test the JavaScript app using sinon to fake the server going away, but I'd like to be able to test it end-to-end with a headless browser if possible).

答:
I found also another option. To start Chrome with

options.add_argument('--host-resolver-rules=MAP * ~NOTFOUND')
```

I saw this in chromium docs because this flag was missing from google-chrome --help.

Which link also means that you can also use your own proxy server to simulate different conditions as well.

Body:
I found also another option. To start Chrome with

options.add_argument('--host-resolver-rules=MAP * ~NOTFOUND')

I saw this in chromium docs because this flag was missing from google-chrome --help.

Which link also means that you can also use your own proxy server to simulate different conditions as well.


问:
DiscordJS filtering users from buttons and limiting buttons to user who used command
I'm trying to make a bot that lets users create embeds using a series of commands and its going well. But I encountered a problem, the bot uses buttons but to confirm something like "Are you sure this is your title?" any user can click the button; which is a problem. I only want the user who used the command to be able to use the buttons.

Here is what I tried at the start:

```<code>client.on('interactionCreate', async interaction => {
const filter = m => !m.author.bot && m.author.id === interaction.user.id;
const collector = interaction.channel.createMessageCollector({filter, max:1, time:10000});

if (!interaction.isButton() && interaction.user.id != interaction.message.author.id) return;
</code>```

I tried to use interaction.user.id != or === interaction.message.author.id but that doesn't work

答:
```<code>client.on("interactionCreate", async (interaction) => {
  //filter the user so it only works for the user who sent the command
  if (interaction.user.id !== message.author.id) {
    const embed = new MessageEmbed()
      .setDescription("You Cannot Interact With This Message!")
      .setColor("RED");
    return interaction.reply({ embeds: [embed], ephemeral: true });
  } else {
    //Code Here
  }
});
</code>```

idk if you still need it but

hope it works, it works for me

Body:
I'm trying to make a bot that lets users create embeds using a series of commands and its going well. But I encountered a problem, the bot uses buttons but to confirm something like "Are you sure this is your title?" any user can click the button; which is a problem. I only want the user who used the command to be able to use the buttons.

Here is what I tried at the start:

client.on('interactionCreate', async interaction => {
const filter = m => !m.author.bot && m.author.id === interaction.user.id;
const collector = interaction.channel.createMessageCollector({filter, max:1, time:10000});

if (!interaction.isButton() && interaction.user.id != interaction.message.author.id) return;

I tried to use interaction.user.id != or === interaction.message.author.id but that doesn't work

Body:
client.on("interactionCreate", async (interaction) => {
  //filter the user so it only works for the user who sent the command
  if (interaction.user.id !== message.author.id) {
    const embed = new MessageEmbed()
      .setDescription("You Cannot Interact With This Message!")
      .setColor("RED");
    return interaction.reply({ embeds: [embed], ephemeral: true });
  } else {
    //Code Here
  }
});

idk if you still need it but

hope it works, it works for me


问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
To access array's element you have to use square brackets. So, it's just replacing

```<code>$name = $_POST("name");
</code>```

with

```<code>$name = $_POST["name"];
</code>```

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Body:
To access array's element you have to use square brackets. So, it's just replacing

$name = $_POST("name");

with

$name = $_POST["name"];


问:
How can I disable the overlay for warnings in a React app?
I’m using react-app-rewired and I want to disable the overlay for Typescript warnings that appears every time I compile.  For reasons I don't understand, warnings that the VSCode Typescript checker doesn't pick up appear on the overlay; webpack is being a stricter enforcer (stricter than I want it to be in fact).

Anyway, I tried react-app-rewired start --no-client-overlay and I tried this for my config-overrides.js file:

```<code>module.exports = {
    webpack: function (config, _) {
        config.devServer = {
            client: {
                overlay: false
            }
        }
        return config
    }
}
</code>```

Neither has any effect.  It would be good to know how to disable the overlay but an equally good solution would be how to have the compiler use the same level of strictness that VSCode does.

答:
If you are using Webpack v4 (CRA v4), this should be the documentation you are looking for https://v4.webpack.js.org/configuration/dev-server/#devserveroverlay

module.exports = {
    webpack: function (config, _) {
        config.devServer = {
            overlay: {
                warnings: true,
                errors: true
            }
        }
        return config
    }
}
```

The config you provided above is for Webpack v5 (CRA v5), so make sure you are using CRA v5 (and also check that react-app-rewired supports that version).

Body:
I’m using react-app-rewired and I want to disable the overlay for Typescript warnings that appears every time I compile.  For reasons I don't understand, warnings that the VSCode Typescript checker doesn't pick up appear on the overlay; webpack is being a stricter enforcer (stricter than I want it to be in fact).

Anyway, I tried react-app-rewired start --no-client-overlay and I tried this for my config-overrides.js file:

module.exports = {
    webpack: function (config, _) {
        config.devServer = {
            client: {
                overlay: false
            }
        }
        return config
    }
}

Neither has any effect.  It would be good to know how to disable the overlay but an equally good solution would be how to have the compiler use the same level of strictness that VSCode does.

Body:
If you are using Webpack v4 (CRA v4), this should be the documentation you are looking for https://v4.webpack.js.org/configuration/dev-server/#devserveroverlay

module.exports = {
    webpack: function (config, _) {
        config.devServer = {
            overlay: {
                warnings: true,
                errors: true
            }
        }
        return config
    }
}

The config you provided above is for Webpack v5 (CRA v5), so make sure you are using CRA v5 (and also check that react-app-rewired supports that version).


问:
Install R packages using docker file
I have installed R using below line in my docker file. Please suggest how do I specify now packages to be installed in my docker file.

```<code>RUN yum -y install R-core R-devel
</code>```

I'm doing something like this:

```<code>RUN R -e "install.packages('methods',dependencies=TRUE, repos='http://cran.rstudio.com/')"\
    && R -e "install.packages('jsonlite',dependencies=TRUE, repos='http://cran.rstudio.com/')" \
    && R -e "install.packages('tseries',dependencies=TRUE, repos='http://cran.rstudio.com/')"
</code>```

Is this the right way to do?

答:
The best solution I found is with install2.r from the littler package.

First install littler

```<code>RUN R -e "install.packages('littler', dependencies=TRUE)"
</code>```

Then you can use it from bash in your Dockerfile

```<code>RUN install2.r --error --deps TRUE methods
RUN install2.r --error --deps TRUE jsonlite
RUN install2.r --error --deps TRUE tseries
</code>```

The --error flag makes the build quit if the package has not been installed correctly. The --deps TRUE flag is for automatically installing the dependencies for the package

# corrected used of package name ('litter' to 'littler')

Title: Install R packages using docker file

Body:
I have installed R using below line in my docker file. Please suggest how do I specify now packages to be installed in my docker file.

RUN yum -y install R-core R-devel

I'm doing something like this:

RUN R -e "install.packages('methods',dependencies=TRUE, repos='http://cran.rstudio.com/')"\
    && R -e "install.packages('jsonlite',dependencies=TRUE, repos='http://cran.rstudio.com/')" \
    && R -e "install.packages('tseries',dependencies=TRUE, repos='http://cran.rstudio.com/')"

Is this the right way to do?

Body:
The best solution I found is with install2.r from the littler package.

First install littler

RUN R -e "install.packages('littler', dependencies=TRUE)"

Then you can use it from bash in your Dockerfile

RUN install2.r --error --deps TRUE methods
RUN install2.r --error --deps TRUE jsonlite
RUN install2.r --error --deps TRUE tseries

The --error flag makes the build quit if the package has not been installed correctly. The --deps TRUE flag is for automatically installing the dependencies for the package

# corrected used of package name ('litter' to 'littler')


问:
golang: How to check for exported fields in an interface
short version:

```<code>
import (
    "fmt"
    "reflect"
)

type StatusVal int
type Foo struct {
    Name string
    Age  int
    art  string
}

func ListFields(a interface{}) {
    v := reflect.ValueOf(a).Elem()
    fmt.Printf(" Kind: %+v \n", v.Type())
    for _, f := range reflect.VisibleFields(v.Type()) {
        if f.IsExported() {
            fmt.Printf(" Kind: %+v \n", f)
        } else {
            fmt.Printf(" Kind: %s \n", f.Name)
        }
    }

}

func main() {
    var x Foo
    ListFields(&x)

}
</code>```

This code works, but what I really need is var x []Foo , and I cannot find a way to get that to work and check for IsExported in the fields of the slice of structs.

Long version:

I was looking to generate a generic sqlToStruct function, and I bumped into this awesome answer:
Generalizing *sql.Rows Scan in Go

I don't have the reputation to reply there.

The only problem with that is that if my struct has any unexported fields, it panics, and I would like to check for that and return an error to be handled, rather than let it panic.

Also: I have been coding in go for a very short amount of time, please understand where I am coming from and sorry if I am missing something absolutely obvious.

答:
func ListFields(a interface{}) {
    rt := reflect.TypeOf(a) // take type of a
    if rt.Kind() == reflect.Ptr {
        rt = rt.Elem() // use Elem to get the pointed-to-type
    }
    if rt.Kind() == reflect.Slice {
        rt = rt.Elem() // use Elem to get type of slice's element
    }
    if rt.Kind() == reflect.Ptr { // handle input of type like []*StructType
        rt = rt.Elem() // use Elem to get the pointed-to-type
    }
    if rt.Kind() != reflect.Struct {
        return
    }

    fmt.Printf(" Kind: %+v \n", rt)
    for _, f := range reflect.VisibleFields(rt) {
        if f.IsExported() {
            fmt.Printf(" Kind: %+v \n", f)
        } else {
            fmt.Printf(" Kind: %s \n", f.Name)
        }
    }
}
```

https://go.dev/play/p/0J3VXmFPe87

Body:
short version:

import (
    "fmt"
    "reflect"
)

type StatusVal int
type Foo struct {
    Name string
    Age  int
    art  string
}

func ListFields(a interface{}) {
    v := reflect.ValueOf(a).Elem()
    fmt.Printf(" Kind: %+v \n", v.Type())
    for _, f := range reflect.VisibleFields(v.Type()) {
        if f.IsExported() {
            fmt.Printf(" Kind: %+v \n", f)
        } else {
            fmt.Printf(" Kind: %s \n", f.Name)
        }
    }

}

func main() {
    var x Foo
    ListFields(&x)

}

This code works, but what I really need is var x []Foo , and I cannot find a way to get that to work and check for IsExported in the fields of the slice of structs.

Long version:

I was looking to generate a generic sqlToStruct function, and I bumped into this awesome answer:
Generalizing *sql.Rows Scan in Go

I don't have the reputation to reply there.

The only problem with that is that if my struct has any unexported fields, it panics, and I would like to check for that and return an error to be handled, rather than let it panic.

Also: I have been coding in go for a very short amount of time, please understand where I am coming from and sorry if I am missing something absolutely obvious.

Body:
func ListFields(a interface{}) {
    rt := reflect.TypeOf(a) // take type of a
    if rt.Kind() == reflect.Ptr {
        rt = rt.Elem() // use Elem to get the pointed-to-type
    }
    if rt.Kind() == reflect.Slice {
        rt = rt.Elem() // use Elem to get type of slice's element
    }
    if rt.Kind() == reflect.Ptr { // handle input of type like []*StructType
        rt = rt.Elem() // use Elem to get the pointed-to-type
    }
    if rt.Kind() != reflect.Struct {
        return
    }

    fmt.Printf(" Kind: %+v \n", rt)
    for _, f := range reflect.VisibleFields(rt) {
        if f.IsExported() {
            fmt.Printf(" Kind: %+v \n", f)
        } else {
            fmt.Printf(" Kind: %s \n", f.Name)
        }
    }
}

https://go.dev/play/p/0J3VXmFPe87


问:
userId dosen't get into the mongoose schema
i'm trying to send a post request to create a new task for a user, the mongoose schema of each task is:

```<code>let todoSchema = new AppSchema ({
    userId: String,
    title: String,
    completed: Boolean
}, {versionKey: false})
</code>```

and when i send the request, the task is created without the userId.
this is the request:

```<code>add = () => {
        const task = {
            userId: this.props.id,
            title: this.state.title,
            completed: false,
        }

        if(task.title) {
            axiosUtils.create('http://localhost:8000/todos/', task)
            alert('task created!')
        }

    }
</code>```

*the typeof task.userId is string, it is the mongoDB _id of the specific user toString()

答:
The function axios.create() just creates an axios instance with the specified config to send requests, but does not actually send any request.
Here's the documentation about how to send a POST request with axios.</p>

Body:
i'm trying to send a post request to create a new task for a user, the mongoose schema of each task is:

let todoSchema = new AppSchema ({
    userId: String,
    title: String,
    completed: Boolean
}, {versionKey: false})

and when i send the request, the task is created without the userId.
this is the request:

add = () => {
        const task = {
            userId: this.props.id,
            title: this.state.title,
            completed: false,
        }

        if(task.title) {
            axiosUtils.create('http://localhost:8000/todos/', task)
            alert('task created!')
        }

    }

*the typeof task.userId is string, it is the mongoDB _id of the specific user toString()


问:
Efficient matrix times column vector for each column
I have a matrix

```<code>1 2 3
1 2 3
1 2 3
</code>```

that I need to multiply with a column vector

```<code>[2
 3
 4]
</code>```

to get

```<code>2 4 6
3 6 9
4 8 12
</code>```

Now, I can make the vector into a matrix and do an element-wise multiplication, but is there also an efficient way to do this in MKL / CBLAS?

答:
Could you please check the information provided below if it helps depending on your requirement.

For vector-vector operations, please refer the below link.

https://www.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-c/top/blas-and-sparse-blas-routines/blas-routines/blas-level-1-routines-and-functions.html#blas-level-1-routines-and-functions

For matrix-vector operations, please refer the below link.

https://www.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-c/top/blas-and-sparse-blas-routines/blas-routines/blas-level-2-routines.html#blas-level-2-routines
l
For matrix-matrixoperations, please refer the below link.

https://www.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-c/top/blas-and-sparse-blas-routines/blas-routines/blas-level-3-routines.html#blas-level-3-routines

The question mark in the group name corresponds to different character codes indicating the data type (s, d, c, and z or their combination)

Body:
I have a matrix

1 2 3
1 2 3
1 2 3

that I need to multiply with a column vector

[2
 3
 4]

to get

2 4 6
3 6 9
4 8 12

Now, I can make the vector into a matrix and do an element-wise multiplication, but is there also an efficient way to do this in MKL / CBLAS?


问:
How to test annotation based role-specific security in test annotated with `@WebMvcTest` and `@WithMockUser`
My Problem is that I can not test the role-based authentication of my annotated Rest Endpoints in my tests. The specified roles seem to make no difference

I am using annotation based security configuration on my REST-controllers like this:

@RestController
@RequestMapping("rest/person")
class PersonRestController(
    private val securityService: SecurityService,
    private val personService: PersonService,
) {

    @GetMapping("/list")
    @Secured(UserRole.Role.ROLE_COMPANY)
    fun list(): List<Person> {
        val companyId = securityService.currentUser.companyId
        return personService.findByCompany(companyId)
    }

}

```
<p>In my Web Layer tests I am using <code>@WebMvcTest</code> with a shared config class, that provides all required beans (we have some shared ExceptionHandlers and Interceptors that I would like to test with my Controllers)</p>
<p>My Test looks like this:</p>
```@WebMvcTest(PersonRestController::class)
@Import(RestControllerTestConfig::class)
class GroupedScheduleRestControllerTest {

    @Autowired
    private lateinit var mvc: MockMvc

    @MockBean
    private lateinit var personService: PersonService

    // This bean is provided by RestControllerTestConfig
    @Autowired
    private lateinit var someSharedService: SomeSharedService

    @Test
    @WithMockUser(value = "user@company.at")
    fun testReturnsEmptyList() {
        val response = mvc.perform(MockMvcRequestBuilders.get("/rest/person/list"))

        response.andExpect(status().isOk)
            .andExpect(jsonPath("$.length()").value(0))
    }
}

```

Now I would like to add a unit test, that verifies, that only a user with the role COMPANY can access this endpoint - but I can't get this to work. My test always runs through when I add WithMockUser, independent of what I pass in for the roles.
And it always fails with a 401 Unauthorized when I remove WithMockUser so some security setup seems to be happening but the @Secured in my RestEndpoint seems to have no effect.

Am I missing some configuration here to notify @WebMvcTest to pick up the Security annotations from the instantiated RestController?

答: Okay in order for the @Secured annotations to be picked up, I added <code>@EnableGlobalMethodSecurity(securedEnabled = true)</code> to my Configuration class and it worked like a charm </p>

Body:
My Problem is that I can not test the role-based authentication of my annotated Rest Endpoints in my tests. The specified roles seem to make no difference

I am using annotation based security configuration on my REST-controllers like this:

@RestController
@RequestMapping("rest/person")
class PersonRestController(
    private val securityService: SecurityService,
    private val personService: PersonService,
) {

    @GetMapping("/list")
    @Secured(UserRole.Role.ROLE_COMPANY)
    fun list(): List<Person> {
        val companyId = securityService.currentUser.companyId
        return personService.findByCompany(companyId)
    }

}

In my Web Layer tests I am using @WebMvcTest with a shared config class, that provides all required beans (we have some shared ExceptionHandlers and Interceptors that I would like to test with my Controllers)

My Test looks like this:

@WebMvcTest(PersonRestController::class)
@Import(RestControllerTestConfig::class)
class GroupedScheduleRestControllerTest {

    @Autowired
    private lateinit var mvc: MockMvc

    @MockBean
    private lateinit var personService: PersonService

    // This bean is provided by RestControllerTestConfig
    @Autowired
    private lateinit var someSharedService: SomeSharedService

    @Test
    @WithMockUser(value = "user@company.at")
    fun testReturnsEmptyList() {
        val response = mvc.perform(MockMvcRequestBuilders.get("/rest/person/list"))

        response.andExpect(status().isOk)
            .andExpect(jsonPath("$.length()").value(0))
    }
}

Now I would like to add a unit test, that verifies, that only a user with the role COMPANY can access this endpoint - but I can't get this to work. My test always runs through when I add WithMockUser, independent of what I pass in for the roles.
And it always fails with a 401 Unauthorized when I remove WithMockUser so some security setup seems to be happening but the @Secured in my RestEndpoint seems to have no effect.

Am I missing some configuration here to notify @WebMvcTest to pick up the Security annotations from the instantiated RestController?

Body: Okay in order for the @Secured annotations to be picked up, I added @EnableGlobalMethodSecurity(securedEnabled = true) to my Configuration class and it worked like a charm


问:
How do I select groups of customer references that don't use a particular service?
Using the following table (customer_table):

customer_ref
product
service

PI-003
cube
streaming

PI-722
cube
streaming

PI-723
cube
streaming

PI-724
cube
streaming

PI-724
pyramid
download

PI-725
cube
streaming

PI-727
cube
streaming

PI-728
cube
streaming

PI-729
cube
streaming

PI-729
pyramid
download

PI-730
cube
streaming

PI-730
sphere
radio

How do I select groups of customer references that don't use a download as a service?

If I do:
SELECT customer_ref FROM customer_table WHERE service <> download

It will return customer_ref PI-724 and PI-729 which do have a service that isn't download but I don't want to return them because under the same customer_ref they do have a service that is download - if that makes sense.

Under my parameters I want to return the following customer_ref:

customer_ref

PI-003

PI-722

PI-723

PI-725

PI-727

PI-728

PI-730

答:
try like below using aggregation</p>
```<code>select customer_ref from
group by customer_ref
having sum(case when service='download' then 1 else 0 end)=0
</code>```

Body:
try like below using aggregation

select customer_ref from
group by customer_ref
having sum(case when service='download' then 1 else 0 end)=0


问:
AndroidX worker is being canceled when i exit my screen
Using this library "androidx.work:work-runtime-ktx:2.5.0" to run a background thread.
But OneTimeWorkRequest is being cancelled everything i exit the screen. What i am trying to acheive is set it run on the application level can someone help please or some hints? here is my code below :

```<code>            var workManager = WorkManager.getInstance(requireContext())
            val data: Data.Builder = Data.Builder().apply {
                putLong("inspectionId", id)
            }
            val task = OneTimeWorkRequest.Builder(NewSyncWorkManager::class.java).apply {
//                setConstraints(constraints)

                setInputData(data.build())
                setInitialDelay(1,TimeUnit.SECONDS)
                addTag(id.toString())
            }.build()
            workManager.enqueue(task)
</code>```

while NewSyncWorkManager is as following:

```<code>class NewSyncWorkManager(context: Context,workerParams: WorkerParameters) :
    CoroutineWorker(context, workerParams) {
        override suspend fun doWork(): Result {

                    showNotification()

                    val foregroundInfo = ForegroundInfo(notificationId, notification!!)
                    setForeground(foregroundInfo)

                    if (inspectionId == 0L) {
                        Log.d("wah", "inspectionId to upload is missing, stopping")
                        return Result.failure()
                    }

                    val propertySections = sectionsRepo.getPropertyLayout(inspectionId)?.reportSections
                    .....
                    UPLOAD requests to the server
    }
    }
</code>```

答: Fixed the issue by running the UPLOAD requests to the server inside a GlobalScope

Body:
Using this library "androidx.work:work-runtime-ktx:2.5.0" to run a background thread.
But OneTimeWorkRequest is being cancelled everything i exit the screen. What i am trying to acheive is set it run on the application level can someone help please or some hints? here is my code below :

            var workManager = WorkManager.getInstance(requireContext())
            val data: Data.Builder = Data.Builder().apply {
                putLong("inspectionId", id)
            }
            val task = OneTimeWorkRequest.Builder(NewSyncWorkManager::class.java).apply {
//                setConstraints(constraints)

                setInputData(data.build())
                setInitialDelay(1,TimeUnit.SECONDS)
                addTag(id.toString())
            }.build()
            workManager.enqueue(task)

while NewSyncWorkManager is as following:

class NewSyncWorkManager(context: Context,workerParams: WorkerParameters) :
    CoroutineWorker(context, workerParams) {
        override suspend fun doWork(): Result {

                    showNotification()

                    val foregroundInfo = ForegroundInfo(notificationId, notification!!)
                    setForeground(foregroundInfo)

                    if (inspectionId == 0L) {
                        Log.d("wah", "inspectionId to upload is missing, stopping")
                        return Result.failure()
                    }

                    val propertySections = sectionsRepo.getPropertyLayout(inspectionId)?.reportSections
                    .....
                    UPLOAD requests to the server
    }
    }


问:
How to pass comma character in makefile function
In Makefile there is defined a print function, which takes print text as argument and then print it.
My question is that how to pass comma character as a text part to print it ?
For example below is relevant makefile section where comma is not printable.

```<code>print = echo '$(1)'

help:
        @$(call print, He lives in Paris, does not he?)
</code>```

Now if run makefile like:

```<code>$ make help
</code>```

It prints

```<code>$  He lives in Paris
</code>```

instead of

```<code>$  He lives in Paris, does not he?
</code>```

I know in makefile comma uses as argument separate, but how I can make it as printable.
I used different escape character combination to pass comma as text message like \, /, $$, ',' ","  but nothing works

答:
Same as the answer of oguz ismail, but with slight optimization:

You can use a comma itself as a variable name

```<code>, := ,
msg = echo '$1'
help:; @$(call msg,He lives in Paris$(,) does not he?)
</code>```

Source

Body:
In Makefile there is defined a print function, which takes print text as argument and then print it.
My question is that how to pass comma character as a text part to print it ?
For example below is relevant makefile section where comma is not printable.

print = echo '$(1)'

help:
        @$(call print, He lives in Paris, does not he?)

Now if run makefile like:

$ make help

It prints

$  He lives in Paris

instead of

$  He lives in Paris, does not he?

I know in makefile comma uses as argument separate, but how I can make it as printable.
I used different escape character combination to pass comma as text message like \, /, $$, ',' ","  but nothing works

Body:
Same as the answer of oguz ismail, but with slight optimization:

You can use a comma itself as a variable name

, := ,
msg = echo '$1'
help:; @$(call msg,He lives in Paris$(,) does not he?)

Source


问:
How to solve git@github.com: Permission denied (Public key) problem?
I was working with git to commit my files and folder to new repository. Everyone time when I was pushing my code it asked for username and password (which is github token for me). To avoid this I read solution on Configuring user and password with Git Bash given by @manojlds.

So I ran this command:
git remote set-url origin git+ssh://git@github.com/username/reponame.git after reading it.

Now when I am pushing my code it neither the problem is solved nor it is giving me option to enter username and password(token)

After doing $ git push it is showing this

git@github.com: Permission denied (publickey). fatal: Could not read
from remote repository.

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

What should I do to revert it back and so that at least I can enter username and password(token) and upload my files and folder.

答:
From August 13, 2021, no longer accepts Password-based authentication. Github provides a more secure alternative to it and ie. PATs(Personal Access Tokens).

How to generate personal access token

If you have done this properly, You can also refer this

GitHub Error Message - Permission denied (publickey)


问:
Honeycomb activity spontaneously restarts itself
I've got a really odd problem which comes out when testing my app on the Honeycomb emulator. When the "tablet" is rotated to portrait, my main Activity seems to just get stuck, and restarts itself over and over again. The stack trace below seems to give no indication of what is going on, and I haven't been able to pinpoint the restart when debugging either. The same thing doesn't occur on a Gingerbread phone, which uses the same portrait layout.

I do not own a Honeycomb device (yet) so I cannot see whether this is a quirk of the emulator or not.

```<code>08-02 21:28:02.137: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:02.193: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21010
08-02 21:28:04.136: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:04.209: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21015
08-02 21:28:04.230: WARN/ActivityManager(81): Launch timeout has expired, giving up wake lock!
08-02 21:28:06.127: DEBUG/dalvikvm(419): GC_CONCURRENT freed 105K, 3% free 7353K/7559K, paused 13ms+161ms
08-02 21:28:06.178: WARN/ActivityManager(81): Activity idle timeout for ActivityRecord{40841ae0 com.espian.formulae.pro/.Host}
08-02 21:28:06.517: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:06.567: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21020
08-02 21:28:08.447: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
</code>```

Thanks in advance for your help

答: I have found the problem finally! I have a spinner in the ActionBar, and didn't realise the listener was activated when the activity is first created. In landscape this just added another menu to the multiview pane (which I have recently noticed was another bug), but in portrait fires a new activity every time the last one is created.</p>

Body:
I've got a really odd problem which comes out when testing my app on the Honeycomb emulator. When the "tablet" is rotated to portrait, my main Activity seems to just get stuck, and restarts itself over and over again. The stack trace below seems to give no indication of what is going on, and I haven't been able to pinpoint the restart when debugging either. The same thing doesn't occur on a Gingerbread phone, which uses the same portrait layout.

I do not own a Honeycomb device (yet) so I cannot see whether this is a quirk of the emulator or not.

08-02 21:28:02.137: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:02.193: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21010
08-02 21:28:04.136: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:04.209: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21015
08-02 21:28:04.230: WARN/ActivityManager(81): Launch timeout has expired, giving up wake lock!
08-02 21:28:06.127: DEBUG/dalvikvm(419): GC_CONCURRENT freed 105K, 3% free 7353K/7559K, paused 13ms+161ms
08-02 21:28:06.178: WARN/ActivityManager(81): Activity idle timeout for ActivityRecord{40841ae0 com.espian.formulae.pro/.Host}
08-02 21:28:06.517: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419
08-02 21:28:06.567: WARN/WindowManager(81): Failure taking screenshot for (354x230) to layer 21020
08-02 21:28:08.447: INFO/ActivityManager(81): Starting: Intent { cmp=com.espian.formulae.pro/.Host (has extras) } from pid 419

Thanks in advance for your help


问:
Generate dictionary by template in inventory
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113
```
<p>Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):</p>
<pre class="lang-yaml prettyprint-override"><code>children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113
</code>```

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

答:
Those kind of requirements tend to be managed with the add_host module.

Given the playbook:

- hosts: localhost
  gather_facts: no

  tasks:
    - add_host:
        name: "child-{{ item.name }}"
        param: "some-data-{{ item.param }}"
        group: dynamic_hosts
      loop: "{{ _hosts }}"
      vars:
        _hosts:
          - name: 1111
            param: 1111-bis
          - name: 1112
            param: 1112-bis
          - name: 1113
            param: 1113-bis

- hosts: dynamic_hosts
  gather_facts: no

  tasks:
    - debug:
        msg: "On host `{{ item }}` the value of `param` is `{{ hostvars[item].param }}`"
      loop: "{{ ansible_play_hosts }}"
      run_once: true
```
<p>We are constructing a dynamic inventory group named <code>dynamic_hosts</code>, which we can then use in the same playbook.</p>
<p>This would actually yields:</p>
<pre class="lang-none prettyprint-override"><code>PLAY [localhost] ****************************************************************

TASK [add_host] *****************************************************************
ok: [localhost] => (item={'name': 1111, 'param': '1111-bis'})
ok: [localhost] => (item={'name': 1112, 'param': '1112-bis'})
ok: [localhost] => (item={'name': 1113, 'param': '1113-bis'})

PLAY [dynamic_hosts] ************************************************************

TASK [debug] ********************************************************************
ok: [child-1111] => (item=child-1111) =>
  msg: On host `child-1111` the value of `param` is `some-data-1111-bis`
ok: [child-1111] => (item=child-1112) =>
  msg: On host `child-1112` the value of `param` is `some-data-1112-bis`
ok: [child-1111] => (item=child-1113) =>
  msg: On host `child-1113` the value of `param` is `some-data-1113-bis`
</code>```

Body:
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113

Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):

children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

Body:
Those kind of requirements tend to be managed with the add_host module.

Given the playbook:

- hosts: localhost
  gather_facts: no

  tasks:
    - add_host:
        name: "child-{{ item.name }}"
        param: "some-data-{{ item.param }}"
        group: dynamic_hosts
      loop: "{{ _hosts }}"
      vars:
        _hosts:
          - name: 1111
            param: 1111-bis
          - name: 1112
            param: 1112-bis
          - name: 1113
            param: 1113-bis

- hosts: dynamic_hosts
  gather_facts: no

  tasks:
    - debug:
        msg: "On host `{{ item }}` the value of `param` is `{{ hostvars[item].param }}`"
      loop: "{{ ansible_play_hosts }}"
      run_once: true

We are constructing a dynamic inventory group named dynamic_hosts, which we can then use in the same playbook.

This would actually yields:

PLAY [localhost] ****************************************************************

TASK [add_host] *****************************************************************
ok: [localhost] => (item={'name': 1111, 'param': '1111-bis'})
ok: [localhost] => (item={'name': 1112, 'param': '1112-bis'})
ok: [localhost] => (item={'name': 1113, 'param': '1113-bis'})

PLAY [dynamic_hosts] ************************************************************

TASK [debug] ********************************************************************
ok: [child-1111] => (item=child-1111) =>
  msg: On host `child-1111` the value of `param` is `some-data-1111-bis`
ok: [child-1111] => (item=child-1112) =>
  msg: On host `child-1112` the value of `param` is `some-data-1112-bis`
ok: [child-1111] => (item=child-1113) =>
  msg: On host `child-1113` the value of `param` is `some-data-1113-bis`


问:
Pandas: How to split a column of string of multiple tuples to multiple columns of individual string of tuple
I need advice on how to proceed when slicing a string with an explanation.

I have in dataframe column:

data

(0,1), (1,2)

And I would like to divide it into this form.

1
2

(0,1)
(1,2)

How to split this string correctly?

When I use this:

```<code>.str.split(',', expand=True)
</code>```

, it also divides my string between parentheses, but I don't want to. How to do this correctly (and an explanation please)?

答:
You can use the following regex with Series.str.split:

import pandas as pd
df = pd.DataFrame({'data': ['(0,1), (1,2)']})
df2 = df['data'].str.split(r'\s*,\s*(?![^()]*\))', expand=True)
```
<p>Output of <code>df2</code>:</p>
<pre class="lang-none prettyprint-override"><code>       0       1
0  (0,1)   (1,2)
</code>```

See the regex demo. Details:

\s*,\s* - a comma enclosed with zero or more whitespaces

(?![^()]*\)) - a negative lookahead that fails the match if, immediately to the right of the current location, there are zero or more chars other than ( and ) and then a ) char.

Body:
I need advice on how to proceed when slicing a string with an explanation.

I have in dataframe column:

data

(0,1), (1,2)

And I would like to divide it into this form.

1
2

(0,1)
(1,2)

How to split this string correctly?

When I use this:

.str.split(',', expand=True)

, it also divides my string between parentheses, but I don't want to. How to do this correctly (and an explanation please)?

Body:
You can use the following regex with Series.str.split:

import pandas as pd
df = pd.DataFrame({'data': ['(0,1), (1,2)']})
df2 = df['data'].str.split(r'\s*,\s*(?![^()]*\))', expand=True)

Output of df2:

       0       1
0  (0,1)   (1,2)

See the regex demo. Details:

\s*,\s* - a comma enclosed with zero or more whitespaces

(?![^()]*\)) - a negative lookahead that fails the match if, immediately to the right of the current location, there are zero or more chars other than ( and ) and then a ) char.


问:
Unidac / MyDac / SQL - I have problem with fast insert about 1000 rows
I use unidac components. And i have problem with fast insert about 1000 rows.

```<code>var
  query: TUniquery;
begin
  query.SQL.Add('INSERT INTO Table (field1,field2,field3) VALUES (:b0,:b1,:b2);');
  for I := 0 to 1000 do
  begin
   Query.ParamByName('b0').AsInteger := 1;
   Query.ParamByName('b1').AsInteger := 2;
   Query.ParamByName('b2').AsInteger := Random(100);
   Query.Prepare;
   Query.Execute;  //1000 times is very slow
end;
</code>```

It is faster

```<code>var
  query: TUniquery;
begin
  for I := 0 to 1000 do
    Query.SQL.Add('INSERT INTO Table (field1,field2,field3) VALUES (1,2,Random(100));');
  end;
  Query.Execute;  //1 times - is fast add
end;
</code>```

But, I would like to use the first format with the procedure  Query.ParamByName('b1').AsInteger := 2; because it is clearer and with a large number of columns I find myself easier to find.

Do you have any ideas on how to solve this?

Maybe you have some other ways to quickly insert a large number of rows with different data?

答: If you need to quickly insert a large number of records, you should use batch updates. You can read more about batch inserting into MySQL using UniDAC (or MyDAC) in their blog</p>

Body:
I use unidac components. And i have problem with fast insert about 1000 rows.

var
  query: TUniquery;
begin
  query.SQL.Add('INSERT INTO Table (field1,field2,field3) VALUES (:b0,:b1,:b2);');
  for I := 0 to 1000 do
  begin
   Query.ParamByName('b0').AsInteger := 1;
   Query.ParamByName('b1').AsInteger := 2;
   Query.ParamByName('b2').AsInteger := Random(100);
   Query.Prepare;
   Query.Execute;  //1000 times is very slow
end;

It is faster

var
  query: TUniquery;
begin
  for I := 0 to 1000 do
    Query.SQL.Add('INSERT INTO Table (field1,field2,field3) VALUES (1,2,Random(100));');
  end;
  Query.Execute;  //1 times - is fast add
end;

But, I would like to use the first format with the procedure  Query.ParamByName('b1').AsInteger := 2; because it is clearer and with a large number of columns I find myself easier to find.

Do you have any ideas on how to solve this?

Maybe you have some other ways to quickly insert a large number of rows with different data?


问:
props are not working when using map method in react.js
props are passing fine when we are passing them as a whole array of objects but it is not working when I am passing the props by traversing through the array using map function.

```<code>import { React, useEffect, useState } from "react";

import axios from "axios";

import "./Home.css";
import Cardimg from "./Cardimg";
const Home = props => {
    return (
        <>
            <div className="header">PHOTO GALLERY</div>
            <div className="photos">
                {props.data?.map(e => {
                    <Cardimg data={e.ImgUrl}></Cardimg>;
                })}
            </div>
        </>
    );
};

export default Home;
</code>```

in the above code props are passing when I am passing manually in Cardimg component...but as soon as I start using map then it doesn't work...like the props are not reaching the component.

below is my Cardimg component

```<code>import React from 'react'

const Cardimg = (props) => {
  console.log(props.data);
    return (
    <div>{props.data}</div>
  )
}

export default Cardimg
</code>```

答:
You need to return the Cardimg component inside map callback function.

Either like this

```<code>{
    props.data?.map(e => {
        return <Cardimg data={e.ImgUrl}></Cardimg>;
    });
}
</code>```

Or like this

```<code>{
    props.data?.map(e => <Cardimg data={e.ImgUrl}></Cardimg>)
}
</code>```

Body:
props are passing fine when we are passing them as a whole array of objects but it is not working when I am passing the props by traversing through the array using map function.

import { React, useEffect, useState } from "react";

import axios from "axios";

import "./Home.css";
import Cardimg from "./Cardimg";
const Home = props => {
    return (
        <>

PHOTO GALLERY

                {props.data?.map(e => {
                    <Cardimg data={e.ImgUrl}></Cardimg>;
                })}

        </>
    );
};

export default Home;

in the above code props are passing when I am passing manually in Cardimg component...but as soon as I start using map then it doesn't work...like the props are not reaching the component.

below is my Cardimg component

import React from 'react'

const Cardimg = (props) => {
  console.log(props.data);
    return (

{props.data}

  )
}

export default Cardimg

Body:
You need to return the Cardimg component inside map callback function.

Either like this

{
    props.data?.map(e => {
        return <Cardimg data={e.ImgUrl}></Cardimg>;
    });
}

Or like this

{
    props.data?.map(e => <Cardimg data={e.ImgUrl}></Cardimg>)
}


问:
Intellij Idea problem with text file impossible to read
I have a problem using Intellij Idea.

I am absolutely unable to load text file as InputStream - it doesnt matter where do I put the file (main/java, main/resources...) it just can't find the file - in Eclipse everything works just fine.

I tried setings->compiler->resource patterns and added ?*.txt but that doesn't seem to work either.

Any help is appreciated.

答: Look at the image, notice that the txt files are in the project root, and not the source folders (in blue).


问:
How can i create environment in python?
My project has an python version(3.10),i want to add python (3.6) version.
i dont want to delete the old version and my pc has not enough space for virtual machine.
How can i create env?
Can anyone help? Python was first installed directly, should I install anaconda?</p>

答:
enter image description here

I solved the problem by downloading the anaconda promt, creating a new env from there and running the vscode from within the anaconda, when I type the python version, the version I set appears when I type it in normcal cmd, the version 3.10 appears.

Title: How can i create environment in python?