问:
Creating a GIF of stockdata using matplotlib
Trying to create a gif showing the return for a specific stock from 1. jan 2022 to 31. dec 2022.

But I cannot seem to wrap my head around manipulating my data (which comes from excel) into creating my gif. If I use simple strings, I can create the gif, but it will not use dates in x-axis or work the way I want i to.

Below is the code used, must be clarified the data pulled from excel consists of 2 columns. First column is dates (255 days) and the second column is the returns from the specific stock (AO).

```<code>df = pd.read_excel('aoc25.xlsx', sheet_name='Ark1', index_col=0)

def animate(i):
   plt.cla()
   data = df
   x = df['Dato']
   y = data['AO']

   plt.plot(x, y)
   plt.xlabel('2022')
   plt.ylabel('Kurs')
   plt.title('AO Performance')

ani = FuncAnimation(plt.gcf(), animate, interval = 40, blit=True, frames = 100, repeat = True)
ani.save("AO.gif", dpi=300, writer=PillowWriter(fps=25))
</code>```

All help is greatly appreciated!

My data looks like this:

```<code>                    AO
   Dato
  2021-12-31    100.000000
  2022-01-03    99.464715
  2022-01-04    100.256324
  2022-01-05    101.410427
  2022-01-06    101.468675
</code>```

Body:
Trying to create a gif showing the return for a specific stock from 1. jan 2022 to 31. dec 2022.

But I cannot seem to wrap my head around manipulating my data (which comes from excel) into creating my gif. If I use simple strings, I can create the gif, but it will not use dates in x-axis or work the way I want i to.

Below is the code used, must be clarified the data pulled from excel consists of 2 columns. First column is dates (255 days) and the second column is the returns from the specific stock (AO).

df = pd.read_excel('aoc25.xlsx', sheet_name='Ark1', index_col=0)

def animate(i):
   plt.cla()
   data = df
   x = df['Dato']
   y = data['AO']

   plt.plot(x, y)
   plt.xlabel('2022')
   plt.ylabel('Kurs')
   plt.title('AO Performance')

ani = FuncAnimation(plt.gcf(), animate, interval = 40, blit=True, frames = 100, repeat = True)
ani.save("AO.gif", dpi=300, writer=PillowWriter(fps=25))

All help is greatly appreciated!

My data looks like this:

                    AO
   Dato
  2021-12-31    100.000000
  2022-01-03    99.464715
  2022-01-04    100.256324
  2022-01-05    101.410427
  2022-01-06    101.468675


来源: stackexchange

问:
gmail api body recognition
I get messages from gmail by api. I have this code and it works.

```<code>for message in messages:
    # Get the message from its id
    msg = service.users().messages().get(userId="me", id=message["id"], format="full").execute()

    # Use try-except to avoid any errors
    try:
        # Get the headers of the message
        headers = msg["payload"]["headers"]

        # Initialize variables for the Subject, Sender Email, Date, In-Reply-To, and References headers
        subject = None
        sender = None
        date = None
        in_reply_to = None
        references = None

        # Look for Subject, Sender Email, and Date in the headers
        for d in headers:
            if d["name"] == "Subject":
                subject = d["value"]
            if d["name"] == "From":
                sender = d["value"]
            if d["name"] == "Date":
                date = d["value"]
            if d["name"] == "In-Reply-To":
                in_reply_to = d["value"]
            if d["name"] == "References":
                references = d["value"]

        # Initialize an empty string called body
        body = ""

        # Loop through the parts of the message body
        for part in msg["payload"]["parts"]:
            # If the part is of type 'text/plain' or 'text/html'
            if part["mimeType"] in ["text/plain", "text/html"]:
                # Decode the data of the part and get the text
                msg_data = part["body"]["data"] # bytes
                msg_text = base64.urlsafe_b64decode(msg_data).decode()
                # Append the text to the body string
                body += msg_text
        #get the snippet
        snippet = msg['snippet']

        # Get the message's data
        if 'parts' in msg['payload']:
            if msg['payload']['parts'][0]['mimeType'] == 'multipart/alternative':
                message_raw = msg['payload']['parts'][0]['parts'][0]['body']['data']
            else:
                message_raw = msg['payload']['parts'][0]['body']['data']
        else:
            message_raw = msg['payload']['body']['data']

        # Decode the data from base64
        msg_text = base64.urlsafe_b64decode(message_raw).decode()

        # Parse the message with BeautifulSoup
        soup = BeautifulSoup(msg_text, 'html.parser')

        # Append the subject, sender, body, and date to the rows list
        rows.append((subject, sender, body, date, message["id"], snippet, in_reply_to, references, soup))

    except:
        pass

# Create a DataFrame with the rows and set the column names
df = pd.DataFrame(rows, columns=["subject", "sender", "body", "date", "id", 'snippet', 'in_reply_to','references', 'soup'])
</code>```

I have 2 problems:

some messages are with empty body (column body), but if i parse them with bs4 there are not. But bs4 parse body not goog and I have a lot of extra symbols like '[\r\n\r\n ...  ... \r\n [\n]]'.

if I add code after

Decode the data from base64

```<code>    msg_text = base64.urlsafe_b64decode(message_raw).decode()

    # Parse the message with BeautifulSoup
    soup = BeautifulSoup(msg_text, 'html.parser')

    # Use the prettify() method to add indentation and line breaks
    b_soup = soup.prettify()

    # Use the get_text() method to remove tags
    b_soup = soup.get_text()

    # Use regular expressions to remove unwanted characters
    b_soup = re.sub(r'\s+', ' ', soup)
    # Append the subject, sender, body, and date to the rows list

    rows.append((subject, sender, body, date, message["id"], snippet, soup, b_soup))
</code>```

to make beatiful soup I get empty df.

I try to get gmail api enails and parse them.

ContentLicense: CC BY-SA 4.0

Title: gmail api body recognition

Body:
I get messages from gmail by api. I have this code and it works.

for message in messages:
    # Get the message from its id
    msg = service.users().messages().get(userId="me", id=message["id"], format="full").execute()

    # Use try-except to avoid any errors
    try:
        # Get the headers of the message
        headers = msg["payload"]["headers"]

        # Initialize variables for the Subject, Sender Email, Date, In-Reply-To, and References headers
        subject = None
        sender = None
        date = None
        in_reply_to = None
        references = None

        # Look for Subject, Sender Email, and Date in the headers
        for d in headers:
            if d["name"] == "Subject":
                subject = d["value"]
            if d["name"] == "From":
                sender = d["value"]
            if d["name"] == "Date":
                date = d["value"]
            if d["name"] == "In-Reply-To":
                in_reply_to = d["value"]
            if d["name"] == "References":
                references = d["value"]

        # Initialize an empty string called body
        body = ""

        # Loop through the parts of the message body
        for part in msg["payload"]["parts"]:
            # If the part is of type 'text/plain' or 'text/html'
            if part["mimeType"] in ["text/plain", "text/html"]:
                # Decode the data of the part and get the text
                msg_data = part["body"]["data"] # bytes
                msg_text = base64.urlsafe_b64decode(msg_data).decode()
                # Append the text to the body string
                body += msg_text
        #get the snippet
        snippet = msg['snippet']

        # Get the message's data
        if 'parts' in msg['payload']:
            if msg['payload']['parts'][0]['mimeType'] == 'multipart/alternative':
                message_raw = msg['payload']['parts'][0]['parts'][0]['body']['data']
            else:
                message_raw = msg['payload']['parts'][0]['body']['data']
        else:
            message_raw = msg['payload']['body']['data']

        # Decode the data from base64
        msg_text = base64.urlsafe_b64decode(message_raw).decode()

        # Parse the message with BeautifulSoup
        soup = BeautifulSoup(msg_text, 'html.parser')

        # Append the subject, sender, body, and date to the rows list
        rows.append((subject, sender, body, date, message["id"], snippet, in_reply_to, references, soup))

    except:
        pass

# Create a DataFrame with the rows and set the column names
df = pd.DataFrame(rows, columns=["subject", "sender", "body", "date", "id", 'snippet', 'in_reply_to','references', 'soup'])

I have 2 problems:

some messages are with empty body (column body), but if i parse them with bs4 there are not. But bs4 parse body not goog and I have a lot of extra symbols like '[\r\n\r\n ...  ... \r\n [\n]]'.

if I add code after

Decode the data from base64

    msg_text = base64.urlsafe_b64decode(message_raw).decode()

    # Parse the message with BeautifulSoup
    soup = BeautifulSoup(msg_text, 'html.parser')

    # Use the prettify() method to add indentation and line breaks
    b_soup = soup.prettify()

    # Use the get_text() method to remove tags
    b_soup = soup.get_text()

    # Use regular expressions to remove unwanted characters
    b_soup = re.sub(r'\s+', ' ', soup)
    # Append the subject, sender, body, and date to the rows list

    rows.append((subject, sender, body, date, message["id"], snippet, soup, b_soup))

to make beatiful soup I get empty df.

I try to get gmail api enails and parse them.


问:
Warning: First parameter must either be an object or the name of an existing class in ............../plugins/xe-preview/xe-preview.php on line 24
I installed a plugin on my WordPress website and I'm getting this error:

Warning: First parameter must either be an object or the name of an existing class in /home/customer/www/XXXXXXXXXXX/public_html/wp-content/plugins/xe-preview/xe-preview.php on line 24

Unfortunately the plugin provider is really not able to solve the issue.

I used the WordPress plugin on different hosting, different PHP versions, different WordPress version also.

Maybe anybody has an idea?

[xe-preview key="{API-Key}"] = API Key is correct.

<?php
/*
Plugin Name: XE Preview
Description: [xe-preview key="{API-Key}"]
*/
define( 'XEP_PLUGIN', __FILE__ );
define( 'XEP_PLUGIN_DIR', untrailingslashit( dirname( XEP_PLUGIN ) ) );
define( 'XEP_PLUGIN_VIEWS_DIR', XEP_PLUGIN_DIR . '/views/' );

function render($attributes){
    $key= 0;
    $out ="";
    if (isset($attributes["key"])){
        $key = $attributes["key"];
    }
    $url = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    $catid = 0;
    if(isset($_GET['catid'])) {
        $catid = $_GET['catid'];
    }
    $api_url = "https://xeev.app/en/tmpl_api_v3?key=$key&catid=$catid";
    $j_data = file_get_contents($api_url);
    $data = json_decode($j_data);
    if (property_exists($data,"data")){
        ob_start();
        include(XEP_PLUGIN_VIEWS_DIR."list.php");
        $out = ob_get_contents();
        ob_end_clean();
    }
    return $out;

}

add_action('init', 'init_page');
function init_page() {
    wp_register_style( 'xe_style', plugins_url('/css/style.css', __FILE__), false, '1.0.0', 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
    wp_enqueue_style( 'xe_style' );
}
add_shortcode( 'xe-preview', 'render' );
```


问:
Check GPS status with COARSE permission
I'm able to check if user has enabled GPS location via calback

```<code>LocationManagerCompat.registerGnssStatusCallback.
</code>```

Problem is that it needs ACCESS_FINE_LOCATION permission but I'd like to use is also when user enables only ACCESS_COARSE_LOCATION. Is there any clean solution how to achieve it.

Right now, I repeatedly check locationSettings which is not optimal.

```<code>locationStatusTimer = Timer().schedule(0, LOCATION_STATUS_REQUEST_PERIOD) {
                LocationServices.getSettingsClient(activity)
                    .checkLocationSettings(
                        LocationSettingsRequest.Builder()
                            .addLocationRequest(locationRequest)
                            .build()
                    ).addOnSuccessListener {
                        deviceLocationController.updateLocationStatus(DeviceLocationStatus.Enabled)
                    }.addOnFailureListener {
                        deviceLocationController.updateLocationStatus(DeviceLocationStatus.Disabled)
                    }
            }
</code>```

Title: Check GPS status with COARSE permission

Body:
I'm able to check if user has enabled GPS location via calback

LocationManagerCompat.registerGnssStatusCallback.

Problem is that it needs ACCESS_FINE_LOCATION permission but I'd like to use is also when user enables only ACCESS_COARSE_LOCATION. Is there any clean solution how to achieve it.

Right now, I repeatedly check locationSettings which is not optimal.

locationStatusTimer = Timer().schedule(0, LOCATION_STATUS_REQUEST_PERIOD) {
                LocationServices.getSettingsClient(activity)
                    .checkLocationSettings(
                        LocationSettingsRequest.Builder()
                            .addLocationRequest(locationRequest)
                            .build()
                    ).addOnSuccessListener {
                        deviceLocationController.updateLocationStatus(DeviceLocationStatus.Enabled)
                    }.addOnFailureListener {
                        deviceLocationController.updateLocationStatus(DeviceLocationStatus.Disabled)
                    }
            }


问:
REST API design: Keep a unique item in a collection
Suppose I have some REST APIs to manage a user's registered emails. Users can register multiple emails, but only one of them can be primary.

Suppose this is the API that can be used to change email attributes. We can use it to change if an email is a primary email:

```<code>PATCH /members/:member_id/emails/:email_id
{
    "is_primary": false
}
</code>```

Suppose a user has registered the primary and secondary email addresses and needs to exchange the primary and secondary emails. A nature UI design pops up a dialog showing all the email addresses, and the user uses the check box or dropdown list to make the exchange and press the OK button. The question is how the UI translates the operation.

Because the endpoint only supports updating a single email at a time, the UI must first change the secondary email to primary and then change one of the primary emails to secondary. Hopefully, we will allow multiple primary emails.

Should the updating operation target the email set, not a single email address? What's a better design? Thanks in advance.

Body:
Suppose I have some REST APIs to manage a user's registered emails. Users can register multiple emails, but only one of them can be primary.

Suppose this is the API that can be used to change email attributes. We can use it to change if an email is a primary email:

PATCH /members/:member_id/emails/:email_id
{
    "is_primary": false
}

Suppose a user has registered the primary and secondary email addresses and needs to exchange the primary and secondary emails. A nature UI design pops up a dialog showing all the email addresses, and the user uses the check box or dropdown list to make the exchange and press the OK button. The question is how the UI translates the operation.

Because the endpoint only supports updating a single email at a time, the UI must first change the secondary email to primary and then change one of the primary emails to secondary. Hopefully, we will allow multiple primary emails.

Should the updating operation target the email set, not a single email address? What's a better design? Thanks in advance.


问:
VueJS getting posts from Wordpress with Axios and Composition API giving error "Maximum recursive updates exceeded in component"
Yet another question regarding the same project.

The following Options API code works flawlessly, no errors and everything shows correctly:

```<code><script lang="ts">
import axios from "axios";
import { ref } from "vue";

export default {
  data() {
    return {
      postsUrl: "https://localhost/wordpress/wp-json/wp/v2/news",

      posts: [] as any[],
      isLoading: false,
      regex: /(<([^>]+)>)/gi,
      errorCaught: false,
    };
  },
  methods: {
    getPosts() {
      this.isLoading = true;
      axios
        .get(this.postsUrl, { params: { _embed: true } })
        .then((response) => {
          this.posts = response.data;
          console.log("Pages retrieved!");
          console.log(this.posts);
          this.isLoading = false;
        })
        .catch((error) => {
          console.log(error);
          if (error) {
            this.isLoading = false;
            setTimeout(() => {
              this.errorCaught = true;
            }, 1100);
          }
        });
    },
  },
  mounted() {
    this.getPosts();
  },
};
</script>
</code>```

and the template:

```<code><template>
  <div class="news-container">
    <div class="loading">
      <transition name="fadeLoading">
        <div v-if="isLoading">Loading...</div>
      </transition>
      <transition name="fadeLoading">
        <div v-if="errorCaught">There was an error loading news</div>
      </transition>
    </div>
    <div v-if="posts">
      <ul v-for="id in posts" :key="id" ref="posts">
        <h1>
          <router-view :to="id.slug" tag="div" key="page.id"
            >{{ id.title.rendered }}
          </router-view>
        </h1>

        <p class="date">{{ id.date }}</p>
      </ul>
    </div>
  </div>
</template>
</code>```

But, when I do this with Composition API, there is an error:

Maximum recursive updates exceeded in component . This means you
have a reactive effect that is mutating its own dependencies and thus
recursively triggering itself. Possible sources include component
template, render function, updated hook or watcher source function.

After playing around with commenting out parts, seems like the posts constant gets the response.data correctly, but before that, it populates itself 208 times unnecessarily, which is btw 52times as many, as posts I have in the response.data:

```<code>const posts = ref([] as any);
</code>```

Could you tell me why this happens and how to get rid of this error message?
Thank you for your time.

Body:
Yet another question regarding the same project.

The following Options API code works flawlessly, no errors and everything shows correctly:

and the template:

<template>

      <transition name="fadeLoading">

Loading...

      </transition>
      <transition name="fadeLoading">

There was an error loading news

      </transition>

          <router-view :to="id.slug" tag="div" key="page.id"
            >{{ id.title.rendered }}
          </router-view>

{{ id.date }}

</template>

But, when I do this with Composition API, there is an error:

Maximum recursive updates exceeded in component . This means you
have a reactive effect that is mutating its own dependencies and thus
recursively triggering itself. Possible sources include component
template, render function, updated hook or watcher source function.

After playing around with commenting out parts, seems like the posts constant gets the response.data correctly, but before that, it populates itself 208 times unnecessarily, which is btw 52times as many, as posts I have in the response.data:

const posts = ref([] as any);

Could you tell me why this happens and how to get rid of this error message?
Thank you for your time.


问:
Xcode 14, how do I tell DocC to include private functions?
I have a project that I would like to document for future reference. Is there a way to tell DocC to include private and internal functions like you can in Jazzy?</p>


问:
Powershell | Insert image into specific position in a word document
I've managed to insert images into my word document, yet can't find any answers online on how to position an image in a specific position.

This is all I have at the moment:

```<code>    $word = New-Object -ComObject Word.Application
    $word.visible = $true

    $document = $word.documents.Add()
    $selection = $word.selection

    $newInline = $selection.InlineShapes.AddPicture($path)
    $newInline.Height = 50
    $newInline.Width = 150
</code>```

Body:
I've managed to insert images into my word document, yet can't find any answers online on how to position an image in a specific position.

This is all I have at the moment:

    $word = New-Object -ComObject Word.Application
    $word.visible = $true

    $document = $word.documents.Add()
    $selection = $word.selection

    $newInline = $selection.InlineShapes.AddPicture($path)
    $newInline.Height = 50
    $newInline.Width = 150


问:
OleDbDataAdapter Fill() out of memory
I need to Read Excel to DB, but when I run to Fill() will error：System.Data.OleDb.OleDbException: out of memory / full memory

```<code>using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT TOP 10 [titleName] FROM [" + sheet1 + "]", excel_con))
{
    DataTable dtExcelData = new DataTable();
    oda.Fill(dtExcelData);
}
</code>```

When I open excel in local and save, then run again this code will work, I don't know why?

My work need to auto run, so I can't open excel everytime.

this excel is from Email, I use imap

Title: OleDbDataAdapter Fill() out of memory

Body:
I need to Read Excel to DB, but when I run to Fill() will error：System.Data.OleDb.OleDbException: out of memory / full memory

using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT TOP 10 [titleName] FROM [" + sheet1 + "]", excel_con))
{
    DataTable dtExcelData = new DataTable();
    oda.Fill(dtExcelData);
}

When I open excel in local and save, then run again this code will work, I don't know why?

My work need to auto run, so I can't open excel everytime.

this excel is from Email, I use imap


问:
Xampp - MySQL is running and showing green, but unable to connect phpMyAdmin in browser
I recently updated my windows after restarting of my laptop, i started xampp, Apache and MySQL both are running and it's showing green but i'm unable to login to phpmyadmin, i'm getting access denied.
Please find the below images for your references and i'm getting below errors.

Xampp Screenshot

Phpmyadmin Screen shot

I need to run mysql and need to access phpmyadmin

Resolved.
Click on Config next to mysql, and open my.ini and follow below steps

```<code># The MySQL server
default-character-set=utf8mb4
[mysqld]
skip-grant-tables   <<<--- Add this line
port=3306
</code>```

Body:
I recently updated my windows after restarting of my laptop, i started xampp, Apache and MySQL both are running and it's showing green but i'm unable to login to phpmyadmin, i'm getting access denied.
Please find the below images for your references and i'm getting below errors.

Xampp Screenshot

Phpmyadmin Screen shot

I need to run mysql and need to access phpmyadmin

Resolved.
Click on Config next to mysql, and open my.ini and follow below steps

# The MySQL server
default-character-set=utf8mb4
[mysqld]
skip-grant-tables   <<<--- Add this line
port=3306


问:
How to get VM pricing information using `@ibm-cloud/platform-services`
I've been trying to get the pricing information IBM cloud VMs using @ibm-cloud/platform-services/global-catalog/v1 (ref). However I cannot find anything in the documentation on how to do that.

Documentation: https://cloud.ibm.com/apidocs/resource-catalog/global-catalog?code=node

Please give me an example to get the hourly pricing for the VM profile say bx2-2x8 (VM with 2 cores and, GiB memory)


问:
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 4 and 3 in dimension 2
I am getting this error when I try batch size more than 1

```<code>RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 5 and 4 in dimension 2 at C:\w\1\s\tmp_conda_3.6_095855\conda\conda-bld\pytorch_1579082406639\work\aten\src\TH/generic/THTensor.cpp:612
</code>```

All the solution I found talk about images as inputs, but my inputs are numpy arrays (.npy) that I converted to tensors separately. Here is my code for the conversion:

```<code> tensor1 = torch.from_numpy(np.load(NPY))
 tensor1 = tensor1.type(torch.FloatTensor)
 tensor1 = torch.einsum('h w c -> c h w', tensor1)
</code>```

I understand that by default numpy data is given as

```<code>[batch_size, depth, height, width, channels]
</code>```

however torch torch tensors have this dimension

```<code>[batch_size, channels, depth, height, width].
</code>```

From this, I am guessing dimension 2 refers to depth.
Is there any way I can make the sizes of the tensors in dimension 2 similar? If so, how can I do this with numpy arrays?

Here is the code of the model I am experimenting with for reference:

```<code>        elif arch.startswith('resnet50'):
            self.features = nn.Sequential(*list(original_model.children())[:-1])

            for i, param in enumerate(self.features.parameters()):

                param.requires_grad = False
            self.fc_pre = nn.Sequential(nn.Linear(2048, fc_size), nn.Dropout())
            self.rnn = nn.LSTM(input_size = fc_size,
                        hidden_size = hidden_size,
                        num_layers = lstm_layers,
                        batch_first = True)
            self.fc = nn.Linear(hidden_size, num_classes)
            self.modelName = 'resnet50_lstm'

        else:
            raise Exception("This architecture has not been supported yet")

    def init_hidden(self, num_layers, batch_size):
        return (torch.zeros(num_layers, batch_size, self.hidden_size).cuda(),
                torch.zeros(num_layers, batch_size, self.hidden_size).cuda())

    def forward(self, inputs, hidden=None, steps=0):
        length = len(inputs)
        fs = torch.zeros(inputs[0].size(0), length, self.rnn.input_size).cuda()

        for i in range(length):

            f = self.features(inputs[i])
            f = f.view(f.size(0), -1)
            f = self.fc_pre(f)
            fs[:, i, :] = f

        outputs, hidden = self.rnn(fs, hidden)
        outputs = self.fc(outputs)
        return outputs
</code>```

Thank you.

Body:
I am getting this error when I try batch size more than 1

RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 5 and 4 in dimension 2 at C:\w\1\s\tmp_conda_3.6_095855\conda\conda-bld\pytorch_1579082406639\work\aten\src\TH/generic/THTensor.cpp:612

All the solution I found talk about images as inputs, but my inputs are numpy arrays (.npy) that I converted to tensors separately. Here is my code for the conversion:

 tensor1 = torch.from_numpy(np.load(NPY))
 tensor1 = tensor1.type(torch.FloatTensor)
 tensor1 = torch.einsum('h w c -> c h w', tensor1)

I understand that by default numpy data is given as

[batch_size, depth, height, width, channels]

however torch torch tensors have this dimension

[batch_size, channels, depth, height, width].

From this, I am guessing dimension 2 refers to depth.
Is there any way I can make the sizes of the tensors in dimension 2 similar? If so, how can I do this with numpy arrays?

Here is the code of the model I am experimenting with for reference:

        elif arch.startswith('resnet50'):
            self.features = nn.Sequential(*list(original_model.children())[:-1])

            for i, param in enumerate(self.features.parameters()):

                param.requires_grad = False
            self.fc_pre = nn.Sequential(nn.Linear(2048, fc_size), nn.Dropout())
            self.rnn = nn.LSTM(input_size = fc_size,
                        hidden_size = hidden_size,
                        num_layers = lstm_layers,
                        batch_first = True)
            self.fc = nn.Linear(hidden_size, num_classes)
            self.modelName = 'resnet50_lstm'

        else:
            raise Exception("This architecture has not been supported yet")

    def init_hidden(self, num_layers, batch_size):
        return (torch.zeros(num_layers, batch_size, self.hidden_size).cuda(),
                torch.zeros(num_layers, batch_size, self.hidden_size).cuda())

    def forward(self, inputs, hidden=None, steps=0):
        length = len(inputs)
        fs = torch.zeros(inputs[0].size(0), length, self.rnn.input_size).cuda()

        for i in range(length):

            f = self.features(inputs[i])
            f = f.view(f.size(0), -1)
            f = self.fc_pre(f)
            fs[:, i, :] = f

        outputs, hidden = self.rnn(fs, hidden)
        outputs = self.fc(outputs)
        return outputs

Thank you.


问:
swift CVPixelBuffer video is darker than original image
My app takes a snapshot of view: ZStack ( image with opacity 0.4 , white rectangle with opacity 0.25 then text) and save it as a image then enables user to generate a video using that image and some audio, I followed tutorials

https://img.ly/blog/how-to-make-videos-from-still-images-with-avfoundation-and-swift/ http://twocentstudios.com/2017/02/20/creating-a-movie-with-an-image-and-audio-on-ios/
https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image

The video is generated successfully with audio and image, however the output video is always darker than the produced image from snapshot.

saved image and video from photos app

image looks like what appear in device:

output video darker than the used image :S

here are some functions

snapshot

```<code>extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self.ignoresSafeArea(.all))
        let view = controller.view

    let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }

    }

}
</code>```

Create video using image

```<code>  func writeSingleImageToMovie(image: UIImage, movieLength: TimeInterval, outputFileURL: URL, completion: @escaping (Error?) -> ())
     {
        print("writeSingleImageToMovie is called")

        do {
            let imageSize = image.size
            let videoWriter = try AVAssetWriter(outputURL: outputFileURL, fileType: AVFileType.mp4)
            let videoSettings: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.h264,
                                                AVVideoWidthKey: imageSize.width, //was imageSize.width
                                                AVVideoHeightKey: imageSize.height] //was imageSize.height

            let videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
            let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput, sourcePixelBufferAttributes: nil)

            if !videoWriter.canAdd(videoWriterInput) { throw NSError() }
            videoWriterInput.expectsMediaDataInRealTime = true
            videoWriter.add(videoWriterInput)

            videoWriter.startWriting()
            let timeScale: Int32 = 4 // 600 recommended in CMTime for movies.
            let halfMovieLength = Float64(movieLength/2.0) // videoWriter assumes frame lengths are equal.
            let startFrameTime = CMTimeMake(value: 0, timescale: timeScale)

            let endFrameTime = CMTimeMakeWithSeconds(Double(60), preferredTimescale: timeScale)

            videoWriter.startSession(atSourceTime: startFrameTime)

        guard let cgImage = image.cgImage else { throw NSError() }

            let buffer: CVPixelBuffer = try CGImage.pixelBuffer(fromImage: cgImage, size: imageSize)

            while !adaptor.assetWriterInput.isReadyForMoreMediaData { usleep(10) }
            adaptor.append(buffer, withPresentationTime: startFrameTime)
            while !adaptor.assetWriterInput.isReadyForMoreMediaData { usleep(10) }
            adaptor.append(buffer, withPresentationTime: endFrameTime)

            videoWriterInput.markAsFinished()
            videoWriter.finishWriting
            {
                completion(videoWriter.error)
            }

        } catch {
            print("CATCH Error in writeSingleImageToMovie")
            completion(error)
        }
}
</code>```

Here is the function to create CVPixelBuffer, I tried to create buffer using CIImage also but got the same result

```<code>extension CGImage {

    static func pixelBuffer(fromImage image: CGImage, size: CGSize) throws -> CVPixelBuffer {
        print("pixelBuffer from CGImage")
        let options: CFDictionary = [kCVPixelBufferCGImageCompatibilityKey as String: true, kCVPixelBufferCGBitmapContextCompatibilityKey as String: true] as CFDictionary
        var pxbuffer: CVPixelBuffer? = nil
        let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_32ARGB, options, &pxbuffer)
        guard let buffer = pxbuffer, status == kCVReturnSuccess else { throw NSError() }

        CVPixelBufferLockBaseAddress(buffer, [])
        guard let pxdata = CVPixelBufferGetBaseAddress(buffer)
        else { throw NSError() }
        let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer)

        let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

            guard let context = CGContext(data: pxdata, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else { print("error in `CG context")
                throw NSError() }
        context.concatenate(CGAffineTransform(rotationAngle: 0))
        context.draw(image, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        CVPixelBufferUnlockBaseAddress(buffer, [])

        return buffer
        }
}
</code>```

I got stuck into this problem, I can't seem to find a solution..
any hint would be appreciated.

Body:
My app takes a snapshot of view: ZStack ( image with opacity 0.4 , white rectangle with opacity 0.25 then text) and save it as a image then enables user to generate a video using that image and some audio, I followed tutorials

https://img.ly/blog/how-to-make-videos-from-still-images-with-avfoundation-and-swift/ http://twocentstudios.com/2017/02/20/creating-a-movie-with-an-image-and-audio-on-ios/
https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image

The video is generated successfully with audio and image, however the output video is always darker than the produced image from snapshot.

saved image and video from photos app

image looks like what appear in device:

output video darker than the used image :S

here are some functions

snapshot

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self.ignoresSafeArea(.all))
        let view = controller.view

    let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }

    }

}

Create video using image

  func writeSingleImageToMovie(image: UIImage, movieLength: TimeInterval, outputFileURL: URL, completion: @escaping (Error?) -> ())
     {
        print("writeSingleImageToMovie is called")

        do {
            let imageSize = image.size
            let videoWriter = try AVAssetWriter(outputURL: outputFileURL, fileType: AVFileType.mp4)
            let videoSettings: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.h264,
                                                AVVideoWidthKey: imageSize.width, //was imageSize.width
                                                AVVideoHeightKey: imageSize.height] //was imageSize.height

            let videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
            let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput, sourcePixelBufferAttributes: nil)

            if !videoWriter.canAdd(videoWriterInput) { throw NSError() }
            videoWriterInput.expectsMediaDataInRealTime = true
            videoWriter.add(videoWriterInput)

            videoWriter.startWriting()
            let timeScale: Int32 = 4 // 600 recommended in CMTime for movies.
            let halfMovieLength = Float64(movieLength/2.0) // videoWriter assumes frame lengths are equal.
            let startFrameTime = CMTimeMake(value: 0, timescale: timeScale)

            let endFrameTime = CMTimeMakeWithSeconds(Double(60), preferredTimescale: timeScale)

            videoWriter.startSession(atSourceTime: startFrameTime)

        guard let cgImage = image.cgImage else { throw NSError() }

            let buffer: CVPixelBuffer = try CGImage.pixelBuffer(fromImage: cgImage, size: imageSize)

            while !adaptor.assetWriterInput.isReadyForMoreMediaData { usleep(10) }
            adaptor.append(buffer, withPresentationTime: startFrameTime)
            while !adaptor.assetWriterInput.isReadyForMoreMediaData { usleep(10) }
            adaptor.append(buffer, withPresentationTime: endFrameTime)

            videoWriterInput.markAsFinished()
            videoWriter.finishWriting
            {
                completion(videoWriter.error)
            }

        } catch {
            print("CATCH Error in writeSingleImageToMovie")
            completion(error)
        }
}

Here is the function to create CVPixelBuffer, I tried to create buffer using CIImage also but got the same result

extension CGImage {

    static func pixelBuffer(fromImage image: CGImage, size: CGSize) throws -> CVPixelBuffer {
        print("pixelBuffer from CGImage")
        let options: CFDictionary = [kCVPixelBufferCGImageCompatibilityKey as String: true, kCVPixelBufferCGBitmapContextCompatibilityKey as String: true] as CFDictionary
        var pxbuffer: CVPixelBuffer? = nil
        let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(size.width), Int(size.height), kCVPixelFormatType_32ARGB, options, &pxbuffer)
        guard let buffer = pxbuffer, status == kCVReturnSuccess else { throw NSError() }

        CVPixelBufferLockBaseAddress(buffer, [])
        guard let pxdata = CVPixelBufferGetBaseAddress(buffer)
        else { throw NSError() }
        let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer)

        let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

            guard let context = CGContext(data: pxdata, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else { print("error in `CG context")
                throw NSError() }
        context.concatenate(CGAffineTransform(rotationAngle: 0))
        context.draw(image, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        CVPixelBufferUnlockBaseAddress(buffer, [])

        return buffer
        }
}

I got stuck into this problem, I can't seem to find a solution..
any hint would be appreciated.


问:
Unable to click radio button using selenium java
screenshot of about radio button

```<code> By template=By.xpath("//div[@id='static-content-template-block']/div[1]/div/label/input");

    WebElement element1= driver.findElement(template);
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].scrollIntoView();",element1);
    driver.findElement(template).click();
</code>```

above was the code that I written for radio button but it is not working

I want to select about us radio button from this image2
this is the html code3

Body:
screenshot of about radio button

 By template=By.xpath("//div[@id='static-content-template-block']/div[1]/div/label/input");

    WebElement element1= driver.findElement(template);
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].scrollIntoView();",element1);
    driver.findElement(template).click();

above was the code that I written for radio button but it is not working

I want to select about us radio button from this image2
this is the html code3


问:
Trigger a script while using ImportRange
I would like to create an empty checkbox in the Column A, when the Column C of the same row is changed.

It's pretty easy to do it when I modify "manually" the column C :

```<code>function onEdit(e) {
  if (e.range.getColumn() == 3) {
    var row = e.range.getRow();
    SpreadsheetApp.getActiveSheet().getRange(row, 1).insertCheckboxes();
  }
}

</code>```

The problem is that my data in the Column C are imported through an IMPORTRANGE, which does not trigger my script.

Do you know how to solve my issue ?

I've tried to change onEdit by onChange but it still doesn't work.

I've also tried to import my data in an other Sheet and to then to "forward" it with a "dirty" "=sheet1!C1" for the row1 for exemple, but it still does not work.

Body:
I would like to create an empty checkbox in the Column A, when the Column C of the same row is changed.

It's pretty easy to do it when I modify "manually" the column C :

function onEdit(e) {
  if (e.range.getColumn() == 3) {
    var row = e.range.getRow();
    SpreadsheetApp.getActiveSheet().getRange(row, 1).insertCheckboxes();
  }
}

The problem is that my data in the Column C are imported through an IMPORTRANGE, which does not trigger my script.

Do you know how to solve my issue ?

I've tried to change onEdit by onChange but it still doesn't work.

I've also tried to import my data in an other Sheet and to then to "forward" it with a "dirty" "=sheet1!C1" for the row1 for exemple, but it still does not work.


Title: Comparing array a to array b

Body:
I want to go through an array and check that it matches. Is there a way other than a loop?

console.log(['m111', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] == ['m111', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
// false


问:
The Application Default Credentials are not available. They are available if running in Google Compute Engine in spring boot
```<code>@SpringBootApplication
public class GooglecloudApplication {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(GooglecloudApplication.class, args);

        // Initialize client that will be used to send requests. This client only needs
        // to be created
        // once, and can be reused for multiple requests. After completing all of your
        // requests, call
        // the "close" method on the client to safely clean up any remaining background
        // resources.
        try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {

            // The path to the image file to annotate
            String fileName = "./resources/mrz_passport_1.jpg";

            // Reads the image file into memory
            Path path = Paths.get(fileName);
            byte[] data = Files.readAllBytes(path);
            ByteString imgBytes = ByteString.copyFrom(data);

            // Builds the image annotation request
            List<AnnotateImageRequest> requests = new ArrayList<>();
            Image img = Image.newBuilder().setContent(imgBytes).build();
            Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
            AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
            requests.add(request);

            // Performs label detection on the image file
            BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = response.getResponsesList();

            for (AnnotateImageResponse res : responses) {
                if (res.hasError()) {
                    System.out.format("Error: %s%n", res.getError().getMessage());
                    return;
                }

                for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                    annotation.getAllFields().forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
                }
            }
        }
    }

}
</code>```

Error:

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:125)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:97)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:70)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:168)
at com.google.cloud.vision.v1.stub.GrpcImageAnnotatorStub.create(GrpcImageAnnotatorStub.java:115)
at com.google.cloud.vision.v1.stub.ImageAnnotatorStubSettings.createStub(ImageAnnotatorStubSettings.java:163)
at com.google.cloud.vision.v1.ImageAnnotatorClient.(ImageAnnotatorClient.java:160)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:142)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:133)
at com.googlecloud.GooglecloudApplication.main(GooglecloudApplication.java:35)
... 5 more

I am facing this problem " java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine". I have also key json file but I dont know where to use this file

Body:
@SpringBootApplication
public class GooglecloudApplication {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(GooglecloudApplication.class, args);

        // Initialize client that will be used to send requests. This client only needs
        // to be created
        // once, and can be reused for multiple requests. After completing all of your
        // requests, call
        // the "close" method on the client to safely clean up any remaining background
        // resources.
        try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {

            // The path to the image file to annotate
            String fileName = "./resources/mrz_passport_1.jpg";

            // Reads the image file into memory
            Path path = Paths.get(fileName);
            byte[] data = Files.readAllBytes(path);
            ByteString imgBytes = ByteString.copyFrom(data);

            // Builds the image annotation request
            List<AnnotateImageRequest> requests = new ArrayList<>();
            Image img = Image.newBuilder().setContent(imgBytes).build();
            Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
            AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
            requests.add(request);

            // Performs label detection on the image file
            BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = response.getResponsesList();

            for (AnnotateImageResponse res : responses) {
                if (res.hasError()) {
                    System.out.format("Error: %s%n", res.getError().getMessage());
                    return;
                }

                for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
                    annotation.getAllFields().forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
                }
            }
        }
    }

}

Error:

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:125)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:97)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:70)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:168)
at com.google.cloud.vision.v1.stub.GrpcImageAnnotatorStub.create(GrpcImageAnnotatorStub.java:115)
at com.google.cloud.vision.v1.stub.ImageAnnotatorStubSettings.createStub(ImageAnnotatorStubSettings.java:163)
at com.google.cloud.vision.v1.ImageAnnotatorClient.(ImageAnnotatorClient.java:160)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:142)
at com.google.cloud.vision.v1.ImageAnnotatorClient.create(ImageAnnotatorClient.java:133)
at com.googlecloud.GooglecloudApplication.main(GooglecloudApplication.java:35)
... 5 more

I am facing this problem " java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine". I have also key json file but I dont know where to use this file


问:
Google sign-in authentication popup adding my webs icon
When i click sign in with google on my webpage a pop up opens and i can login through there now what my issue is
I need my web icon to be diplayed on the google authentication popup page how can i add my webs icon there.
Here i have added the image url for reference.
Google sign-in</p>


问:
Need to build a logic for random selection of product in PLP
I'm new to selenium automation testing I built a logic for the site automation but in this logic, I manually picked one product. Did the testing for it now I need to build a logic for random selection of the product from PLP and it adds to the cart.

I used
jp@gc - WebdDriverSampler for logic

CSV Data set the config for dynamic input

script language -javascript

Thanks in advance.

PLP:

(https://i.stack.imgur.com/W9H1M.jpg)

```<code>WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div/div/div[2]/div[1]/input")).sendKeys(CapCodeInput);//this line for dynamic value input
WDS.browser.findElement(org.openqa.selenium.By.xpath("//div[@id='mm-0']/div/div/div/div/div/div/div[2]/div/div/div/div[2]/div[2]/button")).click();// submit

WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[3]/div/div/div/div[2]/div/div/button")).click();// Allproducts button
WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[1]/header/div[2]/div/nav/ul/li[1]/a")).click();//PLP

WDS.browser.findElement(org.openqa.selenium.By.xpath("//div[@id='mm-0']/div/div/div[2]/div/div/div[4]/div[2]/div/div/div[5]/div/a/img")).click();//This is single product xpath

var wait = new pkg.WebDriverWait(WDS.browser, java.time.Duration.ofSeconds(15))
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
wait.until(conditions.elementToBeClickable(org.openqa.selenium.By.xpath('//*[@id="customizer-container"]/div/div[2]/div[2]/div[3]/button'))).click();

var start = new Date().getTime()
var attempt = 1
while (new Date().getTime() - start < 5000) {
    try {
        var button = WDS.browser.findElement(pkg.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[1]/div[10]/div/div/div/div[3]/div/a/span"))
        button.click();
        WDS.log.info('Element found')
        break
    }
    catch (err) {
        WDS.log.info('Attempt # ' + attempt + ', Element not found)
        java.lang.Thread.sleep(1000)
        attempt++
    }
}
</code>```

The above logic is for a single product and I need help to build logic for a random selection of products the image is attached for reference.

Looked for references, but did not find the exact solution to the problem. Need the logic for the random selection of products and add it to the cart.

Body:
I'm new to selenium automation testing I built a logic for the site automation but in this logic, I manually picked one product. Did the testing for it now I need to build a logic for random selection of the product from PLP and it adds to the cart.

I used
jp@gc - WebdDriverSampler for logic

CSV Data set the config for dynamic input

script language -javascript

Thanks in advance.

PLP:

(https://i.stack.imgur.com/W9H1M.jpg)

WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[2]/div[1]/div/div/div[2]/div[1]/input")).sendKeys(CapCodeInput);//this line for dynamic value input
WDS.browser.findElement(org.openqa.selenium.By.xpath("//div[@id='mm-0']/div/div/div/div/div/div/div[2]/div/div/div/div[2]/div[2]/button")).click();// submit

WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[3]/div/div/div/div[2]/div/div/button")).click();// Allproducts button
WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[1]/header/div[2]/div/nav/ul/li[1]/a")).click();//PLP

WDS.browser.findElement(org.openqa.selenium.By.xpath("//div[@id='mm-0']/div/div/div[2]/div/div/div[4]/div[2]/div/div/div[5]/div/a/img")).click();//This is single product xpath

var wait = new pkg.WebDriverWait(WDS.browser, java.time.Duration.ofSeconds(15))
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
wait.until(conditions.elementToBeClickable(org.openqa.selenium.By.xpath('//*[@id="customizer-container"]/div/div[2]/div[2]/div[3]/button'))).click();

var start = new Date().getTime()
var attempt = 1
while (new Date().getTime() - start < 5000) {
    try {
        var button = WDS.browser.findElement(pkg.By.xpath("//*[@id='mm-0']/div[1]/div/div[1]/div/div/div/div[1]/div[10]/div/div/div/div[3]/div/a/span"))
        button.click();
        WDS.log.info('Element found')
        break
    }
    catch (err) {
        WDS.log.info('Attempt # ' + attempt + ', Element not found)
        java.lang.Thread.sleep(1000)
        attempt++
    }
}

The above logic is for a single product and I need help to build logic for a random selection of products the image is attached for reference.

Looked for references, but did not find the exact solution to the problem. Need the logic for the random selection of products and add it to the cart.


问:
Bootstrap MDB Angular - time picker, change input date format to American format
all I have the following date picker on my site:

```<code><mdb-form-control>
      <input
        mdbInput
        [mdbDatepicker]="datepicker"
        type="text"
        class="form-control"
        id="exampleDatepicker"
        [(ngModel)]="selectedDate"
        (change)="changeDate(); calcNight()"
        placeholder="dd/mm/yyyy"

      />
      <label mdbLabel for="exampleDatepicker" class="form-label">Select a date</label>
      <mdb-datepicker-toggle [mdbDatepicker]="datepicker"></mdb-datepicker-toggle>
      <mdb-datepicker   [inline]="true" #datepicker (dateChanged)="dateChange($event)"></mdb-datepicker>
</mdb-form-control>
</code>```

I am based in the UK and when I change the date I get the output eg Fri Jan 06 2023 02:35:19 GMT+0000 (Greenwich Mean Time) and here we use the format dd/mm/yyyy

Now a user of my site from the US has reported a problem where he entered the date in the format of mm/dd/yyyy but the picker translated it as a UK format dd/mm/yyyy. I am wondering how I set the input format so the picker knows the format of the input and therefore gives the correct selectedDate?

Thanks for any help here.

Body:
all I have the following date picker on my site:

<mdb-form-control>
      <input
        mdbInput
        [mdbDatepicker]="datepicker"
        type="text"
        class="form-control"
        id="exampleDatepicker"
        [(ngModel)]="selectedDate"
        (change)="changeDate(); calcNight()"
        placeholder="dd/mm/yyyy"

      />
      Select a date
      <mdb-datepicker-toggle [mdbDatepicker]="datepicker"></mdb-datepicker-toggle>
      <mdb-datepicker   [inline]="true" #datepicker (dateChanged)="dateChange($event)"></mdb-datepicker>
</mdb-form-control>

I am based in the UK and when I change the date I get the output eg Fri Jan 06 2023 02:35:19 GMT+0000 (Greenwich Mean Time) and here we use the format dd/mm/yyyy

Now a user of my site from the US has reported a problem where he entered the date in the format of mm/dd/yyyy but the picker translated it as a UK format dd/mm/yyyy. I am wondering how I set the input format so the picker knows the format of the input and therefore gives the correct selectedDate?

Thanks for any help here.


问:
Splay Tree insertion time efficiency with different input cases
So I used the same splaytree used in geeksforgeeks and did some experiment with it:

code: https://www.geeksforgeeks.org/insertion-in-splay-tree/?ref=rp

vers.1

    #include <ctime>
    // the code for splaytree is too long so I just put the link here: https://www.geeksforgeeks.org/insertion-in-splay-tree/?ref=rp
    double t1=clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        root = insert(root, x);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);
```
<p>vers.2</p>
<pre class="lang-cpp prettyprint-override"><code>    int x;
    double t1=clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        root = insert(root, i);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);
</code>```

OUTPUT:

for vers. 1: the insertion time is
cpp insertion time: 0.779000
for vers. 2: the insertion time is
insertion time: 0.156000

I know Splay tree "splays" every time it does insertion, so consider that rand may generates same outputs sometimes, why splay tree works much faster when it takes 1000000 distinct inputs? That doesn't make any sense to me. (I am a student and yea my English is bad sorry about it).

EDIT:

I modified vers.2 to:

    int x;
    double t1 = clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        printf("%d",x);
        root = insert(root, i);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);
```
<p>modified vers.2 output:</p>
``` ....a bunch of numbers...time: 0.569000
```

still faster than vers. 1

Body:
So I used the same splaytree used in geeksforgeeks and did some experiment with it:

code: https://www.geeksforgeeks.org/insertion-in-splay-tree/?ref=rp

vers.1

    #include <ctime>
    // the code for splaytree is too long so I just put the link here: https://www.geeksforgeeks.org/insertion-in-splay-tree/?ref=rp
    double t1=clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        root = insert(root, x);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);

vers.2

    int x;
    double t1=clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        root = insert(root, i);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);

OUTPUT:

for vers. 1: the insertion time is
cpp insertion time: 0.779000
for vers. 2: the insertion time is
insertion time: 0.156000

I know Splay tree "splays" every time it does insertion, so consider that rand may generates same outputs sometimes, why splay tree works much faster when it takes 1000000 distinct inputs? That doesn't make any sense to me. (I am a student and yea my English is bad sorry about it).

EDIT:

I modified vers.2 to:

    int x;
    double t1 = clock();
    for(int i = 0; i < 1000000; i++)
    {
        x = rand()%max_x;
        printf("%d",x);
        root = insert(root, i);
    }

    double t2=clock();
    double result = (t2-t1)/CLOCKS_PER_SEC;
    printf("insertion time: %f\n", result);

modified vers.2 output:

 ....a bunch of numbers...time: 0.569000

still faster than vers. 1


问:
The repetitive background image leaves a line on the ios phone, how to solve this

The resulting line is as shown above.

```<code>background-size: 100%;
background-repeat: repeat-y;
</code>```

Body:
The resulting line is as shown above.

background-size: 100%;
background-repeat: repeat-y;


问:
Jupyter NBConvert --to pdf causes undefined control sequence '\HyPsd@expand@utfvii'
Any jupyter notebook I try to export to PDF leads to an error

```<code>! Undefined control sequence.
\HyPsd@expand@utfvii ...'.
</code>```

I can export as webpdf but University prefers PDF where possible (page counts etc.).

I have an M1 Mac and have followed this post to get my ipynb's to export to PDF but am stuck on the final step (jupyter nbconvert --to pdf test.ipynb)

I have also run tlmgr update --all --self to make sure it's not old versions.

I have inspected by converting ipynb to tex via jupyter nbconvert --to latex test.ipynb and there is no obvious issue.

Body:
Any jupyter notebook I try to export to PDF leads to an error

! Undefined control sequence.
\HyPsd@expand@utfvii ...'.

I can export as webpdf but University prefers PDF where possible (page counts etc.).

I have an M1 Mac and have followed this post to get my ipynb's to export to PDF but am stuck on the final step (jupyter nbconvert --to pdf test.ipynb)

I have also run tlmgr update --all --self to make sure it's not old versions.

I have inspected by converting ipynb to tex via jupyter nbconvert --to latex test.ipynb and there is no obvious issue.


问:
Input file is not getting the correct file on secound upload

I have a problem with a input field to upload a image. When the user update there image / upload a file.

It works fine the first try, but if they want to change it again right after they updated it, some weird things happen.

First time uploading a image, it's the correct image that is uploaded.

Secound time, it will choose the first again. (I wan't the image that the user uploaded)

Third time it will put the correct image, as it was the first try.

What am i missing? Image name is also diffrent.

.../ProfileImageChangeComponent.tsx

  function handleUpload(e: File | any) {
  const loaderToast = toast.loading("Uploader...");
  const file = e.target.files[0];
  const fileExt = file?.name?.split(".").pop();
  const fileSize = file?.size;

console.log(e.target.files && e.target.files[0]);

if (file) {
  if (fileSize > 15000000) {
    toast.error("Billedet må ikke være større end 15MB!");
    toast.dismiss(loaderToast);
    return;
  }

  if (fileExt == "jpg" || fileExt == "png" || fileExt == "jpeg") {
    props.setprofilePicturePreview(URL.createObjectURL(file));
    props.setprofilePicture(file);
    toast.dismiss(loaderToast);
    toast.promise(
      CLIENT_API.put(
        "merchant/profile_picture/",
        {
          image: file,
        },
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      ).then((res) => {
        console.log(res.data.new);
        sessionStorage.setItem(
          "user",
          JSON.stringify({
            ...user,
            profile_picture: res.data.new,
          })
        );

        setUser({
          ...user,
          profile_picture: res.data.new,
        });
      }),
      {
        loading: "Opdatere din profil...",
        success: (data) => {
          props.fileUpload.current.value = "";
          e.target.files = null;

          sessionStorage.setItem(
            "user",
            JSON.stringify({
              ...user,
            })
          );

          return `Dit profilbillede er opdateret`;
        },
        error: (error) => {
          if (error?.response?.data?.detail) {
            return error?.response?.data?.detail;
          } else return error?.response?.data?.message;
        },
      },
      { error: { duration: 5000 } }
    );
  } else {
    toast.error(
      "Billedet skal være i jpg, png eller jpeg format!" + fileExt
    ),
      { duration: 5000 };
    toast.dismiss(loaderToast);
  }
} else {
  toast.dismiss(loaderToast);
}
  }

      <input
      type="file"
      ref={props.fileUpload}
      accept="image/png, image/jpeg, image/jpg"
      onChange={(e) => {
        handleUpload(e);
      }}
      hidden
    />
```


问:
Other ways than for loop
I'm creating a new tensor with the right dimensions, but it's taken forever using a for loop. Is there a faster way to do this? Maybe just changing the shape of the orignial tensor.

In general im creating a neural network, and the reason for why I have to change the shape is for it to fit with my other input in the network.

This is a sample from the data:

```<code>    labels_numeric_copy = [8, 3, 7, 4, 4, 5, 4, 8, 5, 4, 4, 8, 4, 6]
</code>```

This is the code for this part of the code.

```<code>frames = np.empty((32000, 100))
for i in range (len(labels_numeric_copy)):
    np.append(frames,labels_numeric_copy[i])
</code>```

I already tried reshape and view. Any ideas?

Title: Other ways than for loop

Body:
I'm creating a new tensor with the right dimensions, but it's taken forever using a for loop. Is there a faster way to do this? Maybe just changing the shape of the orignial tensor.

In general im creating a neural network, and the reason for why I have to change the shape is for it to fit with my other input in the network.

This is a sample from the data:

    labels_numeric_copy = [8, 3, 7, 4, 4, 5, 4, 8, 5, 4, 4, 8, 4, 6]

This is the code for this part of the code.

frames = np.empty((32000, 100))
for i in range (len(labels_numeric_copy)):
    np.append(frames,labels_numeric_copy[i])

I already tried reshape and view. Any ideas?


问:
read method of ItemReader & stepExecutionListner's custom implementation is not called
read method of ItemReader & stepExecutionListner's custom implementation is not called. The basic code structure is as below -

```<code>public class myCustomReader implements ItemReader<List<String>>, StepExecutionListener {

    Logger logger = LogManager.getLogger(this);

    private List<String> dataList;

    @Override
    synchronized public List<String> read()
            throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        logger.info("read called");

        dataList.add("A");
        dataList.add("B");
        dataList.add("C");
        dataList.add("D");
        dataList.add("E");

        return dataList;
    }
    @Override
    public void beforeStep(StepExecution stepExecution) {
        logger.info("beforeStep called");
        dataList.add("A");
        dataList.add("B");
        dataList.add("C");
        dataList.add("D");
        dataList.add("E");
    }
    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        logger.info("afterStep called");
        return ExitStatus.COMPLETED;
    }

}
</code>```

The appropriate configurations are done in the xml files. The reader is getting called and prints only beforeStep() & afterStep() logs, no logs from read() method. Since there's no data passed to processor from reader, processor gets called but doesnt do anything.
Please help me identify the root cause and fix it.

```<code><batch:job id="jobId" restartable="false"
    job-repository="jobRepository">
    <batch:step id="stepdId">
        <batch:tasklet task-executor="batchTaskExecuter">
            <batch:chunk reader="myCustomReader"

                writer="myCustomWriter"
                commit-interval="10"
                >
            </batch:chunk>
        </batch:tasklet>
    </batch:step>
</batch:job>
</code>```

Edit: added config.

Edit2: I tried removing & adding 'synchornized' for read() method, without any change. When I remove stepExecutionListener and keep only ItemReader in the implementation, then only read method gets called.

I am expecting read() method logs to get printed, i.e. read() method should get called.

Body:
read method of ItemReader & stepExecutionListner's custom implementation is not called. The basic code structure is as below -

public class myCustomReader implements ItemReader<List<String>>, StepExecutionListener {

    Logger logger = LogManager.getLogger(this);

    private List<String> dataList;

    @Override
    synchronized public List<String> read()
            throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        logger.info("read called");

        dataList.add("A");
        dataList.add("B");
        dataList.add("C");
        dataList.add("D");
        dataList.add("E");

        return dataList;
    }
    @Override
    public void beforeStep(StepExecution stepExecution) {
        logger.info("beforeStep called");
        dataList.add("A");
        dataList.add("B");
        dataList.add("C");
        dataList.add("D");
        dataList.add("E");
    }
    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        logger.info("afterStep called");
        return ExitStatus.COMPLETED;
    }

}

The appropriate configurations are done in the xml files. The reader is getting called and prints only beforeStep() & afterStep() logs, no logs from read() method. Since there's no data passed to processor from reader, processor gets called but doesnt do anything.
Please help me identify the root cause and fix it.

<batch:job id="jobId" restartable="false"
    job-repository="jobRepository">
    <batch:step id="stepdId">
        <batch:tasklet task-executor="batchTaskExecuter">
            <batch:chunk reader="myCustomReader"

                writer="myCustomWriter"
                commit-interval="10"
                >
            </batch:chunk>
        </batch:tasklet>
    </batch:step>
</batch:job>

Edit: added config.

Edit2: I tried removing & adding 'synchornized' for read() method, without any change. When I remove stepExecutionListener and keep only ItemReader in the implementation, then only read method gets called.

I am expecting read() method logs to get printed, i.e. read() method should get called.


问:
Best practise for gathering a collection of child models for pagination
Still very new to Laravel and working on my first-ever project and I have some best practice questions about the architecture of a flashcards app that I'm building.

I have two models topic and flashcard both with corresponding controllers.

topic has a one-to-many relationship to child topics : $topic->children (which allows for a multi-level hierarchy).

topic also has a one-to-many relationship with flashcard : $topic->flashcards.

topic also has a nullable one-to-one relationship with a parent topic : $topic->parent

flashcard has a non-nullable relationship with a topic : $flashcard->topic

a topic can either have a parent-child relationship with topic or with flashcard but not both.

When the user is navigating through topics I want them to be able to click a 'test me' button at any point.

This will collect all of the current topic's flashcards OR all of the flashcards of all of the topics down the hierarchy.

I will then show these flashcards to the user one at a time and test the user.

I will then increment a 'correct' or 'false' value on the flashcard model, probably through a form submission, and then move on to the next card.

I have a couple of questions about how best to implement this testing part:

To collect all of the flashcards belonging to all topics down the hierarchy, should I use eloquent so that I can paginate the forms one by one or build a Collection of flashcards and paginate myself in some way? If it's the latter, are there good ways to do this and keep the Collection in the session?

And from a best practice POV, is it better design to have a recursive method in my TopicController that collects all the flashcards from all subtopics? This "feels" wrong to me, is there a better place to store this method?

Thanks for your advice!


问:
I'm not able to globally load the color tokens using vue3 + vite

my vite config file looks like this.
but it wont load the color tokens and throws error in application run time

i'm using node latest version 18.13.0 and vue 3 with vite 3.2.4 and sass 1.56.1

I want to load color token globally in my application


问:
MailGun API cannot able to add bounce email
When I adding bounce email with mailgun api https://api.mailgun.net/v3/domain/bounces/EMAIL_ADDRESS
Then it return [error] => not found

Here is demo script

```<code>$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/DOMAIN/bounces/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('address' => 'abc@gmail.com'));
        curl_setopt($ch, CURLOPT_USERPWD, 'api' . ':' . 'KEY');

        $result = json_decode(curl_exec($ch),true);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        echo '```'; print_r($result); die('end');
```

Body:
When I adding bounce email with mailgun api https://api.mailgun.net/v3/domain/bounces/EMAIL_ADDRESS
Then it return [error] => not found

Here is demo script

$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/DOMAIN/bounces/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array('address' => 'abc@gmail.com'));
        curl_setopt($ch, CURLOPT_USERPWD, 'api' . ':' . 'KEY');

        $result = json_decode(curl_exec($ch),true);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        echo '
'; print_r($result); die('end');


问:
How to initialize CoreWCF.OperationContext in unit tests?
I have a CoreWCF .NET 6 service that returns custom HTTP status codes with this code:

var requestProp = new HttpResponseMessageProperty(); OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] = requestProp; requestProp.StatusCode = httpStatusCode;

The problem is I cannot initialize or mock the OperationContext.Current in my unit tests.

It is possible to do it in old WCF .NET Framework 4.8 by doing:

var factory = new ChannelFactory<IManagementService>(new BasicHttpBinding(), new EndpointAddress("http://localhost/Program.Interface/ManagementService.svc")); OperationContext.Current = new OperationContext(factory.CreateChannel() as IContextChannel);

This is no longer possible because **ChannelFactory **is from the System.ServiceModel package whereas my IManagementService service contract is using **CoreWCF **package.

I also tried to use the HttpContextAccessor, it is easy to use it in unit tests but the HTTP status code doesn't change in my service !!

Does anyone have an idea on how to initialize the CoreWCF.OperationContext in unit tests ??


问:
Import-Module does not work in PowerShell when working with Remote-SSH
when I work in remote-ssh to a Windows 2019 server (from Win10 client), if I need to run PowerShell commands that need to import a module, the command fails. If I run the same commands in Win10 or when logged on directly onto the Windows server all is good. This is one of those commands:

```<code>Get-ADComputer -Filter { (Enabled -eq $True) } -SearchBase $GsearchBaseOU
</code>```

The error says: Get-ADComputer : Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running. But it is misleading and the problem seems to be that the ActiveDirectory module does not load. I tried loading it manually when in remote-ssh but it doesn't, and no error is thrown. Anybody experiencing the same? Any special config needed in VS Code maybe?

UPDATE: loading the module when connected with putty works. Executing commands as a consequence also works. As I suspect, the problem is with the remote-ssh plugin in VS Code. Anybody experiencing the same?

UPDATE2: by running:

```<code>ssh -T -D 64971 -F "C:\Users\[redacted]\.ssh\config" serverName powershell
</code>```

in a simple cmd prompt, I successfully login, but when I run the PowerShell command above (or any cmd-let that requires to import a module) I have the same results. So it is not a remote-ssh plugin issue. I have removed vs code by doing an in-depth removal, reinstalled everything, reconfigured and I get the same result. On a different machine I configured vs code with remote-ssh and configured ssh access to the same server but without using a config file. So, I have to enter the password everytime I move from one workspace to another. And that works! It seems that by using a ssh config file with keyfile causes the problem, but I don't see how it could be...

Body:
when I work in remote-ssh to a Windows 2019 server (from Win10 client), if I need to run PowerShell commands that need to import a module, the command fails. If I run the same commands in Win10 or when logged on directly onto the Windows server all is good. This is one of those commands:

Get-ADComputer -Filter { (Enabled -eq $True) } -SearchBase $GsearchBaseOU

The error says: Get-ADComputer : Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running. But it is misleading and the problem seems to be that the ActiveDirectory module does not load. I tried loading it manually when in remote-ssh but it doesn't, and no error is thrown. Anybody experiencing the same? Any special config needed in VS Code maybe?

UPDATE: loading the module when connected with putty works. Executing commands as a consequence also works. As I suspect, the problem is with the remote-ssh plugin in VS Code. Anybody experiencing the same?

UPDATE2: by running:

ssh -T -D 64971 -F "C:\Users\[redacted]\.ssh\config" serverName powershell

in a simple cmd prompt, I successfully login, but when I run the PowerShell command above (or any cmd-let that requires to import a module) I have the same results. So it is not a remote-ssh plugin issue. I have removed vs code by doing an in-depth removal, reinstalled everything, reconfigured and I get the same result. On a different machine I configured vs code with remote-ssh and configured ssh access to the same server but without using a config file. So, I have to enter the password everytime I move from one workspace to another. And that works! It seems that by using a ssh config file with keyfile causes the problem, but I don't see how it could be...


问:
client.await_for unresponsive In a Loop Under Cogs Folder | Discord.py
I made a number-guessing command in Discord.py. The command works perfectly fine outside of any cogs folder (main.py). Because my main.py was getting cluttered, I relocated the guess command into one of the cog's folders where I organized my other commands. When I ran the bot and try to use the guess command, I get an error saying:

```<code>loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hooktype
</code>```

Below is the code I used for the guess command inside the cog:

```<code>    @commands.command()
    async def guess(self, ctx):
        try:
            await ctx.send(f"Pick a range of numbers you want and the number of attempts you want."
                           f"Ex: '__**1-10**, **4**__' or '__**600-10**, **200**__'")

            def check(msg):
                return msg.author == ctx.author and msg.channel == ctx.channel

            msg = await client.wait_for('message', check=check)

            user_range = msg.content
            num = re.findall(r'\d+', user_range)  # get the values from the msg.content or user input
            range_1 = int(num[0])
            range_2 = int(num[1])
            attempt = int(num[2])

            if range_1 > range_2:
                range_1 = int(num[1])
                range_2 = int(num[0])
                await ctx.send(
                    f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")

                def check(msg):
                    return msg.author == ctx.author and msg.channel == ctx.channel

                Entry = 0
                ran_picker = random.randrange(range_1, range_2)
                while Entry <= attempt:
                    msg = await client.await_for('message', check=check)
                    Entry = Entry + 1
                    if msg.content == "stop" or msg.content == "Stop":
                        await ctx.send(f"You gave up ")
                        await ctx.send(f"The number was **{ran_picker}**")
                        break
                    elif int(msg.content) == ran_picker:
                        await ctx.send(f"**Good job, it was {ran_picker}!**")
                        break
                    elif int(msg.content) > range_2 or int(msg.content) < range_1:
                        await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
                        Entry = Entry - 1
                        print(Entry)
                    elif Entry == attempt:
                        await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
                        break
                    else:
                        await ctx.send(f"Nope, keep guessing", delete_after=2)
            else:
                await ctx.send(
                    f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")

                def check(msg):
                    return msg.author == ctx.author and msg.channel == ctx.channel

                Entry = 0
                ran_picker = random.randrange(range_1, range_2)
                while Entry <= attempt:
                    msg = await client.await_for('message', check=check)
                    Entry = Entry + 1
                    if msg.content == "stop" or msg.content == "Stop":
                        await ctx.send(f"You gave up ")
                        await ctx.send(f"The number was **{ran_picker}**")
                        break
                    elif int(msg.content) == ran_picker:
                        await ctx.send(f"**Good job, it was {ran_picker}!**")
                        break
                    elif int(msg.content) > range_2 or int(msg.content) < range_1:
                        await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
                        Entry = Entry - 1
                        print(Entry)
                    elif Entry == attempt:
                        await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
                        break
                    else:
                        await ctx.send(f"Nope, keep guessing", delete_after=2)
        except Exception as error:
            print(f"{error}")
            await ctx.send(f"Problem: **[{error}]**")re
</code>```

In fact, other commands that's inside a cog folder involving the function/line

```<code>msg = await client.await_for('message', check=check)

# specifically' client.await_for'
</code>```

I get a similar error.

I am fairly new to Python's language and Discord.py. I tried to read some of the documents for discord.py revolving around "setup_hooktype" and try to see how I can implement it into my code. Every time I change something I get a new error saying: "unexpected keyward argument," "no attributes" and so on. I believe this function has to do with the subclass (which I have for the cog) but I'm not sure how to create an addon for "setup_hook." I could just leave this command in my main.py, but soon or later I'm going to encounter this problem again in the future.

Any help is appreciated, thanks!

Body:
I made a number-guessing command in Discord.py. The command works perfectly fine outside of any cogs folder (main.py). Because my main.py was getting cluttered, I relocated the guess command into one of the cog's folders where I organized my other commands. When I ran the bot and try to use the guess command, I get an error saying:

loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hooktype

Below is the code I used for the guess command inside the cog:

    @commands.command()
    async def guess(self, ctx):
        try:
            await ctx.send(f"Pick a range of numbers you want and the number of attempts you want."
                           f"Ex: '__**1-10**, **4**__' or '__**600-10**, **200**__'")

            def check(msg):
                return msg.author == ctx.author and msg.channel == ctx.channel

            msg = await client.wait_for('message', check=check)

            user_range = msg.content
            num = re.findall(r'\d+', user_range)  # get the values from the msg.content or user input
            range_1 = int(num[0])
            range_2 = int(num[1])
            attempt = int(num[2])

            if range_1 > range_2:
                range_1 = int(num[1])
                range_2 = int(num[0])
                await ctx.send(
                    f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")

                def check(msg):
                    return msg.author == ctx.author and msg.channel == ctx.channel

                Entry = 0
                ran_picker = random.randrange(range_1, range_2)
                while Entry <= attempt:
                    msg = await client.await_for('message', check=check)
                    Entry = Entry + 1
                    if msg.content == "stop" or msg.content == "Stop":
                        await ctx.send(f"You gave up ")
                        await ctx.send(f"The number was **{ran_picker}**")
                        break
                    elif int(msg.content) == ran_picker:
                        await ctx.send(f"**Good job, it was {ran_picker}!**")
                        break
                    elif int(msg.content) > range_2 or int(msg.content) < range_1:
                        await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
                        Entry = Entry - 1
                        print(Entry)
                    elif Entry == attempt:
                        await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
                        break
                    else:
                        await ctx.send(f"Nope, keep guessing", delete_after=2)
            else:
                await ctx.send(
                    f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")

                def check(msg):
                    return msg.author == ctx.author and msg.channel == ctx.channel

                Entry = 0
                ran_picker = random.randrange(range_1, range_2)
                while Entry <= attempt:
                    msg = await client.await_for('message', check=check)
                    Entry = Entry + 1
                    if msg.content == "stop" or msg.content == "Stop":
                        await ctx.send(f"You gave up ")
                        await ctx.send(f"The number was **{ran_picker}**")
                        break
                    elif int(msg.content) == ran_picker:
                        await ctx.send(f"**Good job, it was {ran_picker}!**")
                        break
                    elif int(msg.content) > range_2 or int(msg.content) < range_1:
                        await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
                        Entry = Entry - 1
                        print(Entry)
                    elif Entry == attempt:
                        await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
                        break
                    else:
                        await ctx.send(f"Nope, keep guessing", delete_after=2)
        except Exception as error:
            print(f"{error}")
            await ctx.send(f"Problem: **[{error}]**")re

In fact, other commands that's inside a cog folder involving the function/line

msg = await client.await_for('message', check=check)

# specifically' client.await_for'

I get a similar error.

I am fairly new to Python's language and Discord.py. I tried to read some of the documents for discord.py revolving around "setup_hooktype" and try to see how I can implement it into my code. Every time I change something I get a new error saying: "unexpected keyward argument," "no attributes" and so on. I believe this function has to do with the subclass (which I have for the cog) but I'm not sure how to create an addon for "setup_hook." I could just leave this command in my main.py, but soon or later I'm going to encounter this problem again in the future.

Any help is appreciated, thanks!


问:
Instantly stream download a file in the browser from an external API that requires custom HTTP request headers
An external API requires authentication on the request via the custom header SessionToken.
One of the endpoints allows downloading a file. This works as shown with the simplified snippet below.

The implemented solution is less than ideal: The file is first downloaded in the background without any user feedback. Only when it is completely downloaded - and the Promise resolves - an actual file download is triggered in the browser.

This is mainly an issue for very large files that take some time to download: The user does not have any feedback and only sees the actual file download when it is already downloaded.

Current situation: User only sees file download in the browser after the file has already been completely downloaded in the background.

Desired situation: The file download should be triggered immediately (file download instantly visible in the "Downloads" section of the browser)

There is no control over the external API. Currently using the axios HTTP client is used but using any other library would be OK if it solves the issue.

Snippet:

import axios from 'axios';

/**
 * The external API does not send the Content-Length response header,
 * so no download progress is known until completely downloaded.
 * No real progress can be shown to the user on the page,
 * apart from showing a spinner or indeterminate progress bar
 *
 * @param progressEvent
 */
const onDownloadProgress = (progressEvent) => {
    const {
        loaded, total, progress, bytes, estimated, rate, download = true,
    } = progressEvent;

    console.log('completed: ', progress); // undefined, see docblock
}

const downloadFile = async ({
    url,
    filename,
    sessionToken,
}) => {
    const headers = {
        Accept: 'application/octet-stream',
        SessionToken: sessionToken,
    };
    return new Promise((resolve, reject) => {
        axios.get(url, {
            responseType: 'blob',
            headers,
            onDownloadProgress,
        }).then((response) => {
            // trigger a browser file download by creating a new anchor tag that points to the downloaded data, and clicking it
            const href = URL.createObjectURL(response.data);
            const link = document.createElement('a');
            link.href = href;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();

            // cleanup
            document.body.removeChild(link);
            URL.revokeObjectURL(href);

            resolve({ filename, response });
        }).catch((error) => {
            reject(error);
        });
    });
};

export default downloadFile
```


问:
Pandas get single warning message per line
I have some code that calls Pandas functions millions of times and many of these calls are issuing warning notices. This is a background process, so I wanted to convert them to logs using logging.captureWarnings(True). The logging works fine, but no matter what filter options I seem to set, the warnings are repeated, millions of times. I have set the logger to record each row to a database table, which works fine with thousands of log records, but is slowed down by millions of warning messages as logs.

So, my question, is there any way to make sure the number of warnings is one per call site, which is the default AFAIK. I think this bug may have something to do with it: https://github.com/python/cpython/issues/73858. I did look at the pandas source code but couldn't find an obvious place where the catch_warnings exception manager was being used.

Does anyone have any potential solutions to return the warnings emitted to what should be the default?

A simple test script is instructive:

```<code>import pandas as pd
import warnings

warnings.simplefilter(action='default', category=FutureWarning)

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5, 6]}
df = pd.DataFrame(data=d)
a = ['col1','col2']
df[a]

b = set(a)
for i in range(3):
  df[b]
</code>```

Running it with python3 -Wd::FutureWarning test.py

Yields:

```<code>/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]
/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]
/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]
</code>```

Not the behaviour I expected

Body:
I have some code that calls Pandas functions millions of times and many of these calls are issuing warning notices. This is a background process, so I wanted to convert them to logs using logging.captureWarnings(True). The logging works fine, but no matter what filter options I seem to set, the warnings are repeated, millions of times. I have set the logger to record each row to a database table, which works fine with thousands of log records, but is slowed down by millions of warning messages as logs.

So, my question, is there any way to make sure the number of warnings is one per call site, which is the default AFAIK. I think this bug may have something to do with it: https://github.com/python/cpython/issues/73858. I did look at the pandas source code but couldn't find an obvious place where the catch_warnings exception manager was being used.

Does anyone have any potential solutions to return the warnings emitted to what should be the default?

A simple test script is instructive:

import pandas as pd
import warnings

warnings.simplefilter(action='default', category=FutureWarning)

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5, 6]}
df = pd.DataFrame(data=d)
a = ['col1','col2']
df[a]

b = set(a)
for i in range(3):
  df[b]

Running it with python3 -Wd::FutureWarning test.py

Yields:

/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]
/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]
/home/stephen/test.py:16: FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead.
  df[b]

Not the behaviour I expected


问:
Team wide solution to track which branch was branched from which branch
I wonder if it's possible to have a hook or something like that, that you can setup team wide. The hook should keep track in a .txt file in the repo which branch was branched away from which branch.

We have a strict policy in our company that normally makes this not needed, but in very rare occasions it would be great to just look it up somewhere instead of trying to find merge points.


问:
Websocket connection failed React JS
I just created a new React App and every time i navigate to a new path i get these errors:
image of the error here
I don't know if it's a problem in the packages or what cause i just created this app and this are all the routes that i have in app.js:

```<code>import Home from './views/Home';
import {BrowserRouter, Route, Routes} from 'react-router-dom'
import Test from './views/Test';
import React from 'react';
import Register from './views/Register';
function App() {
return (
<div className="App">
  <BrowserRouter>
  <Routes>
    <Route path='/register' element={<Register />} />
    <Route path='/' element={<Home/>} />
    <Route path='/test' element={<Test />} />
  </Routes>
  </BrowserRouter>

</div>
 );
}

export default App;
</code>```

The application is working normally but i think that error is slowing down the performance of the app

Title: Websocket connection failed React JS

Body:
I just created a new React App and every time i navigate to a new path i get these errors:
image of the error here
I don't know if it's a problem in the packages or what cause i just created this app and this are all the routes that i have in app.js:

import Home from './views/Home';
import {BrowserRouter, Route, Routes} from 'react-router-dom'
import Test from './views/Test';
import React from 'react';
import Register from './views/Register';
function App() {
return (

  <BrowserRouter>
  <Routes>
    <Route path='/register' element={<Register />} />
    <Route path='/' element={<Home/>} />
    <Route path='/test' element={<Test />} />
  </Routes>
  </BrowserRouter>

 );
}

export default App;

The application is working normally but i think that error is slowing down the performance of the app