问:
How to monkey patch a function using pytest
I am trying to test a function that reads in a csv file with some numbers and calculates the area. I am trying to test it by patching a pandas function using pytest, specifically read_csv function such that it returns the same dataframe every time. For some reason I can't seem to monkeypatch it

circle.py

```<code>import math
import pandas as pd
def get_area(r):
    if not type(r) in [int, float]:
        raise TypeError("Non numeric value")
    return math.pi*(r**2)
def read_rads():
    df = pd.read_csv('radii.csv', header=None, index_col=None)
    return( [get_area(x[0]) for x in df.iterrows()])
if __name__ == '__main__':
    print(get_area(2))
    print(read_rads())
</code>```

test_circle.py

```<code>import pytest
import circle
import math
import unittest
from unittest import mock
import pandas as pd
def test_get_area():
    assert circle.get_area(1) == math.pi * 1**2
    assert circle.get_area(3) == math.pi * 3**2
def test_if_get_area_for_string_input():
    with pytest.raises(TypeError):
        circle.get_area('some string')
def test_read_radii(monkeypatch):
    # We have to mock the response of pd.read_csv
    def mock_read_csv(*args, **kwargs):
        return pd.DataFrame([0,1,2,3,5])

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(pd, "read_csv", mock_read_csv)
    res = circle.read_rads()
    assert res == [0.0, 3.141592653589793, 12.566370614359172, 28.274333882308138, 78.53981633974483]
</code>```

radii is just a csv file with a number on each line, nothing special.

I tried following along with https://docs.pytest.org/en/7.1.x/how-to/monkeypatch.html#monkeypatching-returned-objects-building-mock-classes
I understand that they used a class for the test, but why isn't the read_csv function being monkeypatched? And is this the right way to patch in the data for use in the function?

Body:
I am trying to test a function that reads in a csv file with some numbers and calculates the area. I am trying to test it by patching a pandas function using pytest, specifically read_csv function such that it returns the same dataframe every time. For some reason I can't seem to monkeypatch it

circle.py

import math
import pandas as pd
def get_area(r):
    if not type(r) in [int, float]:
        raise TypeError("Non numeric value")
    return math.pi*(r**2)
def read_rads():
    df = pd.read_csv('radii.csv', header=None, index_col=None)
    return( [get_area(x[0]) for x in df.iterrows()])
if __name__ == '__main__':
    print(get_area(2))
    print(read_rads())

test_circle.py

import pytest
import circle
import math
import unittest
from unittest import mock
import pandas as pd
def test_get_area():
    assert circle.get_area(1) == math.pi * 1**2
    assert circle.get_area(3) == math.pi * 3**2
def test_if_get_area_for_string_input():
    with pytest.raises(TypeError):
        circle.get_area('some string')
def test_read_radii(monkeypatch):
    # We have to mock the response of pd.read_csv
    def mock_read_csv(*args, **kwargs):
        return pd.DataFrame([0,1,2,3,5])

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(pd, "read_csv", mock_read_csv)
    res = circle.read_rads()
    assert res == [0.0, 3.141592653589793, 12.566370614359172, 28.274333882308138, 78.53981633974483]

radii is just a csv file with a number on each line, nothing special.

I tried following along with https://docs.pytest.org/en/7.1.x/how-to/monkeypatch.html#monkeypatching-returned-objects-building-mock-classes
I understand that they used a class for the test, but why isn't the read_csv function being monkeypatched? And is this the right way to patch in the data for use in the function?


来源: stackexchange

问:
Apache Reverse proxy with proxy authentication
I have the following setup

Box A (192.168.8.180 - running apache reverse proxy)

Box B (192.168.8.100:808 - Proxy server to connect to internet)

Due to internal reasons, The IP of box A is redirected to http://xyz.mydomain.com/. The reverse proxy uses the proxy running in Box B to connect to internet.

The setup works fine when the proxy does not need any authentication. But When the proxy at Box B needs authentication, all my request to the reverse proxy fails with the following error.

```<code><h1>Unauthorized ...</h1>
<h2>IP Address: 192.168.8.180:1799<br>
MAC Address: <br>
Server Time: 2011-09-21 20:32:16<br>
Auth Result: </h2>
</code>```

Here is my apache configuration

```<code><VirtualHost *:80>
    ServerName xyz.mydomain.com
    ProxyRequests Off
    ProxyPreserveHost Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyRemote * http://192.168.8.100:808/
    ProxyPass / http://xyz.mydomain.com/
    ProxyPassReverse / http://xyz.mydomain.com/
    RequestHeader set Authorization "Basic cGFuZGlhbjpwYW5kaWFu"

    <Location />
        Order allow,deny
        Allow from all
    </Location>

    ErrorLog "logs/myerror.log"
    CustomLog "logs/myaccess.log" common

</VirtualHost>
</code>```

Any ideas?

access log says the following

```<code>127.0.0.1 - - [21/Sep/2011:20:24:55 +0530] "GET / HTTP/1.1" 407 142
127.0.0.1 - - [21/Sep/2011:20:24:57 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:25:33 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:32:07 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:14 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:15 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:33:58 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:03 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:16 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:24 +0530] "GET / HTTP/1.1" 407 142
</code>```

The proxy credentials are correct. verified with browser.

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I have the following setup

Box A (192.168.8.180 - running apache reverse proxy)

Box B (192.168.8.100:808 - Proxy server to connect to internet)

Due to internal reasons, The IP of box A is redirected to http://xyz.mydomain.com/. The reverse proxy uses the proxy running in Box B to connect to internet.

The setup works fine when the proxy does not need any authentication. But When the proxy at Box B needs authentication, all my request to the reverse proxy fails with the following error.

Unauthorized ...

IP Address: 192.168.8.180:1799

MAC Address:

Server Time: 2011-09-21 20:32:16

Auth Result:

Here is my apache configuration

<VirtualHost *:80>
    ServerName xyz.mydomain.com
    ProxyRequests Off
    ProxyPreserveHost Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyRemote * http://192.168.8.100:808/
    ProxyPass / http://xyz.mydomain.com/
    ProxyPassReverse / http://xyz.mydomain.com/
    RequestHeader set Authorization "Basic cGFuZGlhbjpwYW5kaWFu"

    <Location />
        Order allow,deny
        Allow from all
    </Location>

    ErrorLog "logs/myerror.log"
    CustomLog "logs/myaccess.log" common

</VirtualHost>

Any ideas?

access log says the following

127.0.0.1 - - [21/Sep/2011:20:24:55 +0530] "GET / HTTP/1.1" 407 142
127.0.0.1 - - [21/Sep/2011:20:24:57 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:25:33 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:32:07 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:14 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:15 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:33:58 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:03 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:16 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:24 +0530] "GET / HTTP/1.1" 407 142

The proxy credentials are correct. verified with browser.

Thanks


问:
Switch can't connect to controller in Mininet
I am having trouble connecting the spring boot app to mysql.
I use Docker, SpringBoot, Mysql.(not use Docker compose)

when i command "docker build -t springbootmysql .", error occurred
The error is below.

```<code>2023-01-06 00:42:24 2023-01-05 16:42:24.864  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-01-06 00:42:24 2023-01-05 16:42:24.867  WARN 1 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2023-01-06 00:42:25 2023-01-05 16:42:25.935 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
2023-01-06 00:42:25
2023-01-06 00:42:25 com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
2023-01-06 00:42:25
2023-01-06 00:42:25 The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
2023-01-06 00:42:25     at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:24 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2023-01-06 00:42:25     at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
2023-01-06 00:42:25     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
202
</code>```

application.properties is bellow.

```<code>spring.datasource.url=jdbc:mysql://mysqldb:3306/spring_boot_todo
spring.datasource.username=root
spring.datasource.password=xxxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
</code>```

Database is below.

```<code>+--------------------+
| Database           |
+--------------------+     |
| information_schema |
| mysql              |
| performance_schema |
| spring_boot_todo   |
| sys                |
+--------------------+
</code>```

Docker names are below.
enter image description here

I appreciate for your help.

i checked the application.properties...

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble connecting the spring boot app to mysql.
I use Docker, SpringBoot, Mysql.(not use Docker compose)

when i command "docker build -t springbootmysql .", error occurred
The error is below.

2023-01-06 00:42:24 2023-01-05 16:42:24.864  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-01-06 00:42:24 2023-01-05 16:42:24.867  WARN 1 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2023-01-06 00:42:25 2023-01-05 16:42:25.935 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
2023-01-06 00:42:25
2023-01-06 00:42:25 com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
2023-01-06 00:42:25
2023-01-06 00:42:25 The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
2023-01-06 00:42:25     at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:24 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2023-01-06 00:42:25     at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]
2023-01-06 00:42:25     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
2023-01-06 00:42:25     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
202

application.properties is bellow.

spring.datasource.url=jdbc:mysql://mysqldb:3306/spring_boot_todo
spring.datasource.username=root
spring.datasource.password=xxxx
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create

Database is below.

+--------------------+
| Database           |
+--------------------+     |
| information_schema |
| mysql              |
| performance_schema |
| spring_boot_todo   |
| sys                |
+--------------------+

Docker names are below.
enter image description here

I appreciate for your help.

i checked the application.properties...


问:
minuit m.migrad fitting fails
I am trying to fit a gaussian peak + linear background shape to a histogram. The histogram shape is pretty distinct and the fitting with minuit still fails sometimes. I cannot figure out why since it works most of the time with similar histograms with the same initial parameter guess. Here is my function that does the fit:

```<code>def iminuit_fit(
    counts, mu, sigma, slope, b, datax, datay, pdf, model_function, yerr_systematic=0.0
):
    c = cost.UnbinnedNLL(datay, pdf)
    m = Minuit(
        c,
        counts=counts * 0.9,
        mu=mu * 0.9,
        sigma=sigma * 0.9,
        slope=slope * 0.9,
        b=b * 0.9,
    )
    m.errordef = Minuit.LIKELIHOOD
    m.limits["mu"] = (1,2)
    m.limits["counts"] = (0, None)
    m.limits["sigma"] = (0,1)
    m.limits["slope"] = (None, 0)
    m.limits["b"] = (0, None)
    m.print_level = 0
    m.migrad()
    result_p = m.values
    errors_p = m.errors

    fig0, ax0 = plt.subplots()
    ax0.plot(datax, model_function(datax, *result_p), label="initial fit")
    ax0.plot(datax, datay, drawstyle="steps-mid", label="data")
    ax0.set_title("iminuit fit")
    ax0.legend()

    return result_p.to_dict(), errors_p.to_dict()
</code>```

and I set the parameter guesses as below and do the fitting. The parameters are such that total(x) = counts * normal(mu,sigma) + slope * x + b:

```<code>p, err = iminuit_fit(counts=50, mu=1.8, sigma=0.1, slope=-1200, b=3000, datax=axis_interest, datay=hist_interest, pdf=poisson_pmf, model_function=total)
</code>```

I tried with nine similar histograms with exactly the same code and two of the fitting failed as below. The first picture is what most of the nine looks like. If anyone has an idea of how I can improve this, please let me know!

Title: minuit m.migrad fitting fails

Body:
I am trying to fit a gaussian peak + linear background shape to a histogram. The histogram shape is pretty distinct and the fitting with minuit still fails sometimes. I cannot figure out why since it works most of the time with similar histograms with the same initial parameter guess. Here is my function that does the fit:

def iminuit_fit(
    counts, mu, sigma, slope, b, datax, datay, pdf, model_function, yerr_systematic=0.0
):
    c = cost.UnbinnedNLL(datay, pdf)
    m = Minuit(
        c,
        counts=counts * 0.9,
        mu=mu * 0.9,
        sigma=sigma * 0.9,
        slope=slope * 0.9,
        b=b * 0.9,
    )
    m.errordef = Minuit.LIKELIHOOD
    m.limits["mu"] = (1,2)
    m.limits["counts"] = (0, None)
    m.limits["sigma"] = (0,1)
    m.limits["slope"] = (None, 0)
    m.limits["b"] = (0, None)
    m.print_level = 0
    m.migrad()
    result_p = m.values
    errors_p = m.errors

    fig0, ax0 = plt.subplots()
    ax0.plot(datax, model_function(datax, *result_p), label="initial fit")
    ax0.plot(datax, datay, drawstyle="steps-mid", label="data")
    ax0.set_title("iminuit fit")
    ax0.legend()

    return result_p.to_dict(), errors_p.to_dict()

and I set the parameter guesses as below and do the fitting. The parameters are such that total(x) = counts * normal(mu,sigma) + slope * x + b:

p, err = iminuit_fit(counts=50, mu=1.8, sigma=0.1, slope=-1200, b=3000, datax=axis_interest, datay=hist_interest, pdf=poisson_pmf, model_function=total)

I tried with nine similar histograms with exactly the same code and two of the fitting failed as below. The first picture is what most of the nine looks like. If anyone has an idea of how I can improve this, please let me know!


问:
Cubit logout function (User state -> NoUser state) causes "watchers" of that User state to cause errors in the moment before logout actually occurs
~simplified example for brevity~

I have 2 Cubit states in my app: User and NoUser. The User state (object) holds a bunch of local preferences that are loaded when the app is initially opened (theming, color, text-size, accessibility preferences, etc.).

My settings page has a bunch of watchers that check to see which preference is selected. For example, for text-size preferences, I have 3 checkmarks (small, regular, large), each are shown as selected or not on the screen based on code like this:

```<code>CheckMark(
      title: "Small text selected",
      isChecked: context.watch<UserCubit>().stateAsUser.textSizeEnum == TextSizeEnum.small,
),
</code>```

stateAsUser just unconditionally returns the UserState (from the UserCubit), as User (type cast). This is what is causing the problem.

When I logout of the app, I call a UserCubit method that basically switches the state from User to NoUser, then a BlocListener inside my splash screen navigates to the logged out screen after seeing the state go from User to NoUser.

Steps that cause the problem:

State is User.

User presses logout, and UserCubit.logout() is called, which basically just emits NoUser.

The settings that watch this state suddenly are casting a NoUser type to User inside the stateAsUser method for a split-second, causing exceptions to be thrown, before the app is navigated to the logged out screen.

I'd prefer not having to check if the state is truly User for these settings, because then I'd have to still supply a "default value" to be displayed to these setting checkers in the split-second after a NoUser is emitted, and before the navigation occurs.

I sort of just want to "ignore", or "stay with whatever value was there before state became NoUser" for the split second before the user is pushed to another screen and the watchers become inactive.

I just don't know how to fix this. Any input would be great, thanks!

Body:
~simplified example for brevity~

I have 2 Cubit states in my app: User and NoUser. The User state (object) holds a bunch of local preferences that are loaded when the app is initially opened (theming, color, text-size, accessibility preferences, etc.).

My settings page has a bunch of watchers that check to see which preference is selected. For example, for text-size preferences, I have 3 checkmarks (small, regular, large), each are shown as selected or not on the screen based on code like this:

CheckMark(
      title: "Small text selected",
      isChecked: context.watch<UserCubit>().stateAsUser.textSizeEnum == TextSizeEnum.small,
),

stateAsUser just unconditionally returns the UserState (from the UserCubit), as User (type cast). This is what is causing the problem.

When I logout of the app, I call a UserCubit method that basically switches the state from User to NoUser, then a BlocListener inside my splash screen navigates to the logged out screen after seeing the state go from User to NoUser.

Steps that cause the problem:

State is User.

User presses logout, and UserCubit.logout() is called, which basically just emits NoUser.

The settings that watch this state suddenly are casting a NoUser type to User inside the stateAsUser method for a split-second, causing exceptions to be thrown, before the app is navigated to the logged out screen.

I'd prefer not having to check if the state is truly User for these settings, because then I'd have to still supply a "default value" to be displayed to these setting checkers in the split-second after a NoUser is emitted, and before the navigation occurs.

I sort of just want to "ignore", or "stay with whatever value was there before state became NoUser" for the split second before the user is pushed to another screen and the watchers become inactive.

I just don't know how to fix this. Any input would be great, thanks!


问:
What code would you use in R to learn if there is a significant difference between two predictor variables in the way they affect a response variable?
I am trying to learn if Extraversion affects how people follow COVID-19 guidelines when stratified by male/female gender.

The data is set up so Extraversion is the predictor variable, guideline compliance is the respnse variable, and the data is stratified by gender.

I tried to create two models for each gender and then put them through an anova (this is what ChatGPT recommended). But, R didn't like that saying "models were not all fitted to the same size of dataset".

I think the issue is that there are way more females than males in the sample. Also, I would like to use another method to find a significant difference between the two model's results because each model follows the Poisson distribution and ANOVA only likes normal distributions.

```<code>dataMale <- data %>%
  dplyr::filter(Q34 == "Male")

dataFemale <- data %>%
  dplyr::filter(Q34 == "Female")

poisson_male <- glm(CDC ~ Extraversion, data=dataMale, family=poisson())

poisson_female <- glm(CDC ~ Extraversion, data=dataFemale, family=poisson())

anova(poisson_male, poisson_female, test="Chisq")
</code>```

Body:
I am trying to learn if Extraversion affects how people follow COVID-19 guidelines when stratified by male/female gender.

The data is set up so Extraversion is the predictor variable, guideline compliance is the respnse variable, and the data is stratified by gender.

I tried to create two models for each gender and then put them through an anova (this is what ChatGPT recommended). But, R didn't like that saying "models were not all fitted to the same size of dataset".

I think the issue is that there are way more females than males in the sample. Also, I would like to use another method to find a significant difference between the two model's results because each model follows the Poisson distribution and ANOVA only likes normal distributions.

dataMale <- data %>%
  dplyr::filter(Q34 == "Male")

dataFemale <- data %>%
  dplyr::filter(Q34 == "Female")

poisson_male <- glm(CDC ~ Extraversion, data=dataMale, family=poisson())

poisson_female <- glm(CDC ~ Extraversion, data=dataFemale, family=poisson())

anova(poisson_male, poisson_female, test="Chisq")


问:
Solution for tackling multiple process which updates access token for AWS data source connectivity's from Business Intelligence tools
I really need some help to tackle below problem:
We are connecting to several AWS data sources from Business Intelligence tools like Tableau, Alteryx etc (Windows server based) which will work only with temporary tokens which expire every 15 min and some expire in 60 min. In this process several of our users will have these as separate updates for their own non-human user on the server, which means we will end up with 1000's of connections(data source name) for all the teams on each server of the BI cluster. We thought of creating a process which will be added to scheudled task which runs every 10 min to update the token in the ODBC registry entry or use some scheduling tool. For each data source we will have to do the same thing with so many processes running every few min, which doesnt seem to be sustainable. Has anyone come across similar use case, any suggestions of how to tackle this efficiently?
Your time is much appreciated.

We tried Windows Scheudled task and some scheduling tools.


问:
Appium Inspector: Details: Unable to build Espresso server - Process ended with exitcode 1
I'm almost at lost in here. Currently we're having issues locating the elements using Appium (and Appium Inspector) in our Android app. Some content description are not showing as accessibility ID and it's because we are already using Jetpack Compose. I currently have this as the desired capabilities but I'm not sure how to tailor this based on what I need. From what I understood, we only need to change the automationName to espresso but I keep on encountering the same error over and over again. I have Gradle installed already. I'm using MBP M1 chip. From other sources they mentioned we have to tailor appium:espressoBuildConfig based on build.gradle? Any tips on doing that?

Error:

```<code>Failed to create session. A new session could not be created. Details: Unable to build Espresso server - Process ended with exitcode 1 (cmd: './gradlew -PappiumTargetPackage\=com.quipper.school.assignment.rc app\:assembleAndroidTest') Gradle error message: [STDOUT] > Task :app:processDebugMainManifest FAILED, [STDERR] , [STDERR] FAILURE: Build failed with an exception., [STDERR] , [STDERR] * What went wrong:, [STDERR] Execution failed for task ':app:processDebugMainManifest'., [STDOUT] 7 actionable tasks: 1 executed, 6 from cache, [STDERR] > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @3e157a51, [STDERR] , [STDERR] * Try:, [STDERR] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights., [STDERR] , [STDERR] * Get more help at https://help.gradle.org, [STDERR] , [STDERR] BUILD FAILED in 761ms. Check https://github.com/appium/appium-espresso-driver#troubleshooting regarding advanced session startup troubleshooting.
</code>```

Capabilities:

```<code>{
  "platformName": "Android",
  "appium:platformVersion": "11.0",
  "appium:deviceName": "emulator-5554",
  "appium:app": "/Users/faithberroya/Downloads/app-global-rc.apk",
  "appium:automationName": "espresso",
  "appium:appPackage": "com.quipper.school.assignment.rc",
  "appium:appActivity": "com.quipper.school.assignment.ui.SplashActivity",
  "appium:newCommandTimeout": "0",
  "appium:skipUnlock": "true",
  "appium:fullReset": "false",
  "appium:forceEspressoRebuild": "true",
  "appium:showGradleLog": "true",
  "appium:espressoBuildConfig": "{\"additionalAndroidTestDependencies\": [\"androidx.lifecycle:lifecycle-extensions:2.2.0\", \"androidx.activity:activity:6.6.0\",  \"androidx.fragment:fragment:1.2.0\"]}"
}
</code>```

I tried to follow this article but I'm very new to Appium with Espresso and I only see discussion in Youtube than actual Appium with Espresso driver setup. https://medium.com/bumble-tech/automating-android-jetpack-compose-using-appium-edb760fe79b9

Machine specs:

```<code>Macbook Pro M1 Chip
Gradle 7.6
Kotlin: 1.7.10
Groovy: 3.0.13
Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM: 19.0.1 (Oracle Corporation 19.0.1+10-21)
OS: Mac OS X 13.0 aarch64
Android SDK Platform Tools 33.0.3
Android SDK Tools (Obsolete) 26.1.1
</code>```

Body:
I'm almost at lost in here. Currently we're having issues locating the elements using Appium (and Appium Inspector) in our Android app. Some content description are not showing as accessibility ID and it's because we are already using Jetpack Compose. I currently have this as the desired capabilities but I'm not sure how to tailor this based on what I need. From what I understood, we only need to change the automationName to espresso but I keep on encountering the same error over and over again. I have Gradle installed already. I'm using MBP M1 chip. From other sources they mentioned we have to tailor appium:espressoBuildConfig based on build.gradle? Any tips on doing that?

Error:

Failed to create session. A new session could not be created. Details: Unable to build Espresso server - Process ended with exitcode 1 (cmd: './gradlew -PappiumTargetPackage\=com.quipper.school.assignment.rc app\:assembleAndroidTest') Gradle error message: [STDOUT] > Task :app:processDebugMainManifest FAILED, [STDERR] , [STDERR] FAILURE: Build failed with an exception., [STDERR] , [STDERR] * What went wrong:, [STDERR] Execution failed for task ':app:processDebugMainManifest'., [STDOUT] 7 actionable tasks: 1 executed, 6 from cache, [STDERR] > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @3e157a51, [STDERR] , [STDERR] * Try:, [STDERR] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights., [STDERR] , [STDERR] * Get more help at https://help.gradle.org, [STDERR] , [STDERR] BUILD FAILED in 761ms. Check https://github.com/appium/appium-espresso-driver#troubleshooting regarding advanced session startup troubleshooting.

Capabilities:

{
  "platformName": "Android",
  "appium:platformVersion": "11.0",
  "appium:deviceName": "emulator-5554",
  "appium:app": "/Users/faithberroya/Downloads/app-global-rc.apk",
  "appium:automationName": "espresso",
  "appium:appPackage": "com.quipper.school.assignment.rc",
  "appium:appActivity": "com.quipper.school.assignment.ui.SplashActivity",
  "appium:newCommandTimeout": "0",
  "appium:skipUnlock": "true",
  "appium:fullReset": "false",
  "appium:forceEspressoRebuild": "true",
  "appium:showGradleLog": "true",
  "appium:espressoBuildConfig": "{\"additionalAndroidTestDependencies\": [\"androidx.lifecycle:lifecycle-extensions:2.2.0\", \"androidx.activity:activity:6.6.0\",  \"androidx.fragment:fragment:1.2.0\"]}"
}

I tried to follow this article but I'm very new to Appium with Espresso and I only see discussion in Youtube than actual Appium with Espresso driver setup. https://medium.com/bumble-tech/automating-android-jetpack-compose-using-appium-edb760fe79b9

Machine specs:

Macbook Pro M1 Chip
Gradle 7.6
Kotlin: 1.7.10
Groovy: 3.0.13
Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM: 19.0.1 (Oracle Corporation 19.0.1+10-21)
OS: Mac OS X 13.0 aarch64
Android SDK Platform Tools 33.0.3
Android SDK Tools (Obsolete) 26.1.1


问:
CloudFront to API Gateway request returns 403: "The request signature we calculated does not match the signature you provided."
I have an API Gateway fronted by CloudFront. The API Gateway has a regional endpoint with api key disabled. An Authorization header must be sent to the regional endpoint or the endpoint returns "Missing Authentication Token" as expected.

Using the same request on the CloudFront endpoint returns the following 403 Forbidden error:

```<code>{
    "message": "The request signature we calculated does not match the signature you
     provided. Check your AWS Secret Access Key and signing method. Consult the service
     documentation for details.\n\nThe Canonical String for this request should have been\n'POST

    // sensitive data here...
}
</code>```

The Auth token is created from an AWS signature. The signature originates from an IAM role that allows invocation on the endpoint: "Action": "execute-api:Invoke"

Any ideas on why CloudFront isn't able to use these credentials to hit the API Gateway endpoint?

In summary,

"Postman w/ Authorization header -> API Gateway endpoint" works.

"Postman w/ Authorization header -> CloudFront -> API Gateway endpoint" returns the above 403.

UPDATE: Adding information on how I obtain the signature.

IAM Role:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-west-2:{ACCOUNT}:{ENDPOINT}",
            "Effect": "Allow"
        }
    ]
}
</code>```

AccessKey, SecretKey, Session Token are obtained in CloudShell:

```<code>$ aws sts assume-role --role-arn arn:aws:iam::{ACCOUNT}:{ROLE} --role-session-name {SESSION_NAME}
</code>```

These 3 keys are then used in Postman's Authorization tab. I select "AWS Signature" type and provide the AccessKey, SecretKey, and SessionToken.

From here, I can hit the API Gateway endpoint and receive 200 response. With the same request and headers, hitting the CloudFront endpoint results in the 403.

UPDATE #2: Adding information on CloudFront configuration.

The distribution behavior for the API GW origin is using the CachingOptimized policy. Its also allowing all HTTP methods.

Body:
I have an API Gateway fronted by CloudFront. The API Gateway has a regional endpoint with api key disabled. An Authorization header must be sent to the regional endpoint or the endpoint returns "Missing Authentication Token" as expected.

Using the same request on the CloudFront endpoint returns the following 403 Forbidden error:

{
    "message": "The request signature we calculated does not match the signature you
     provided. Check your AWS Secret Access Key and signing method. Consult the service
     documentation for details.\n\nThe Canonical String for this request should have been\n'POST

    // sensitive data here...
}

The Auth token is created from an AWS signature. The signature originates from an IAM role that allows invocation on the endpoint: "Action": "execute-api:Invoke"

Any ideas on why CloudFront isn't able to use these credentials to hit the API Gateway endpoint?

In summary,

"Postman w/ Authorization header -> API Gateway endpoint" works.

"Postman w/ Authorization header -> CloudFront -> API Gateway endpoint" returns the above 403.

UPDATE: Adding information on how I obtain the signature.

IAM Role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-west-2:{ACCOUNT}:{ENDPOINT}",
            "Effect": "Allow"
        }
    ]
}

AccessKey, SecretKey, Session Token are obtained in CloudShell:

$ aws sts assume-role --role-arn arn:aws:iam::{ACCOUNT}:{ROLE} --role-session-name {SESSION_NAME}

These 3 keys are then used in Postman's Authorization tab. I select "AWS Signature" type and provide the AccessKey, SecretKey, and SessionToken.

From here, I can hit the API Gateway endpoint and receive 200 response. With the same request and headers, hitting the CloudFront endpoint results in the 403.

UPDATE #2: Adding information on CloudFront configuration.

The distribution behavior for the API GW origin is using the CachingOptimized policy. Its also allowing all HTTP methods.


问:
How to redirect voice call to another agent on busy in Twilio Frontline app?
can anyone help with this?
How to redirect voice call to another agent on busy in Twilio frontline app?</p>


问:
File `{$path}` does not exist error in media library laravel
Can I save image for 2 tables in db with same file request?

in controller

```<code>$combo                 = new Combo;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
   $combo->addMediaFromRequest('image')->toMediaCollection('combos');
}

$menuItem                 = new MenuItem;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
   $combo->addMediaFromRequest('image')->toMediaCollection('menu-items');
}
</code>```

Can someone help me fix this code to save it? Thank you very much for your help

Body:
Can I save image for 2 tables in db with same file request?

in controller

$combo                 = new Combo;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
   $combo->addMediaFromRequest('image')->toMediaCollection('combos');
}

$menuItem                 = new MenuItem;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
   $combo->addMediaFromRequest('image')->toMediaCollection('menu-items');
}

Can someone help me fix this code to save it? Thank you very much for your help


问:
Could not file Archlinux env file
Could I please have some assistance on finding my env file?

Now I am using zsh and installed Maven successfully. Then I add Maven into the Environment variable like this:

```<code>export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4
export M2=$M2_HOME/bin
export MAVEN_OPTS=-Xms256m -Xmx512m
export PATH=$M2:$PATH
</code>```

It is successful too. Now I can run "mvn -version".

Then I checked those paths by using "printenv". They are all there. For example, the Maven is like:

PATH=/usr/local/apache-maven/apache-maven-3.8.7/

Then I tried to find where I add those Paths to. I tried the following:

/etc/environment
~/.bashrc
~/.pam_environment

~/.xprofile

~/.zshrc

However, I could not find "PATH=/usr/local/apache-maven/apache-maven-3.8.7/" in any of above.

So where could it be stored in? Where is the exact env file storing these paths?

So where could it be stored in? Where is the exact env file storing these paths?

Title: Could not file Archlinux env file

Body:
Could I please have some assistance on finding my env file?

Now I am using zsh and installed Maven successfully. Then I add Maven into the Environment variable like this:

export M2_HOME=/usr/local/apache-maven/apache-maven-3.8.4
export M2=$M2_HOME/bin
export MAVEN_OPTS=-Xms256m -Xmx512m
export PATH=$M2:$PATH

It is successful too. Now I can run "mvn -version".

Then I checked those paths by using "printenv". They are all there. For example, the Maven is like:

PATH=/usr/local/apache-maven/apache-maven-3.8.7/

Then I tried to find where I add those Paths to. I tried the following:

/etc/environment
~/.bashrc
~/.pam_environment

~/.xprofile

~/.zshrc

However, I could not find "PATH=/usr/local/apache-maven/apache-maven-3.8.7/" in any of above.

So where could it be stored in? Where is the exact env file storing these paths?

So where could it be stored in? Where is the exact env file storing these paths?


问:
Python selenium right-clicking wrong elements
I am writing a program that answers questions from a database. I am currently on the last question type (ordering questions). Here is an image of what the question looks like. The user needs to put the elements in the box in order.

As you can see, the bottom of the question gets cut off. This caused errors when trying to click certain elements that were below the page. To try and solve this I scrolled to the bottom of the page but selenium scrolled back to the top before clicking which kept the error in place. And after trying a few other things I decided to try and zoom out on the webpage to see them all at once.

This is the HTML of the list where the
 tag is what I am trying to click on. Actually, I am trying to right-click but same thing. The rest of the
s with the ellipses are the rest of the boxes and are the same as the first one.

```<code>newheader = self.driver.find_element(By.XPATH, "//div[contains(@class, 'responses-container')]")
action = ActionChains(self.driver)
action.context_click(WebDriverWait (newheader, 10).until(EC.presence_of_element_located((By.XPATH, "//p[contains(text(), '"+ dictionary_.get(prompt)[r] +"')]")))).perform()
# dictionary.get(prompt)[r] contains the values we are looking for (ovulation, fertilization, etc)
# I have also tried EC.element_to_be_clickable and had the same results
</code>```

I have tested this on a question that does not overflow the page and it works perfectly. The only time I am getting errors is when I try to zoom out. I have tried refreshing the page before starting the clicking and after zooming out. I have also tried resetting the driver by calling

```<code>self.driver.get(self.driver.current_url)
</code>```

Each of those elements cannot be left-clicked on to select. They can only be right-clicked or tabbed to. Tabbing requires calculations that are complex since each element is being moved dynamically so I chose to right-click instead. It does right-click but in seemingly random places now that it's zoomed out.

Any help is appreciated! Thanks!

Body:
I am writing a program that answers questions from a database. I am currently on the last question type (ordering questions). Here is an image of what the question looks like. The user needs to put the elements in the box in order.

As you can see, the bottom of the question gets cut off. This caused errors when trying to click certain elements that were below the page. To try and solve this I scrolled to the bottom of the page but selenium scrolled back to the top before clicking which kept the error in place. And after trying a few other things I decided to try and zoom out on the webpage to see them all at once.

This is the HTML of the list where the
 tag is what I am trying to click on. Actually, I am trying to right-click but same thing. The rest of the
s with the ellipses are the rest of the boxes and are the same as the first one.

newheader = self.driver.find_element(By.XPATH, "//div[contains(@class, 'responses-container')]")
action = ActionChains(self.driver)
action.context_click(WebDriverWait (newheader, 10).until(EC.presence_of_element_located((By.XPATH, "//p[contains(text(), '"+ dictionary_.get(prompt)[r] +"')]")))).perform()
# dictionary.get(prompt)[r] contains the values we are looking for (ovulation, fertilization, etc)
# I have also tried EC.element_to_be_clickable and had the same results

I have tested this on a question that does not overflow the page and it works perfectly. The only time I am getting errors is when I try to zoom out. I have tried refreshing the page before starting the clicking and after zooming out. I have also tried resetting the driver by calling

self.driver.get(self.driver.current_url)

Each of those elements cannot be left-clicked on to select. They can only be right-clicked or tabbed to. Tabbing requires calculations that are complex since each element is being moved dynamically so I chose to right-click instead. It does right-click but in seemingly random places now that it's zoomed out.

Any help is appreciated! Thanks!


问:
Handle Paste event in DataGridViewTextBoxColumn
I have a DataGridView with a column of the type DataGridViewTextBoxColumn. I want the user to be able to copy column data from Excel and paste it into the DataGridView. I'm capturing Ctrl+V in the key down event so I can parse the text and place it in the correct cells.

The problem I have is that after I assign values to the affected cells, the entire clipboard text is pasted in the active cell. For example, if 1\r\n2\r\n3 is pasted, I can place the 2 and 3 in their respective cells but 1\r\n2\r\n3 ends up in the active cell.

My code in the dgvCell_KeyDown event for reference

```<code> private void dgvCell_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.V && e.Control)
        {
            string text = Clipboard.GetText();
            string[] data = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            int col = dgv.CurrentCell.ColumnIndex;
            int row = dgv.CurrentCell.RowIndex;
            if (data.Length <= dgv.Rows.Count - row)
            {
                for (int i = 0; i < data.Length; i++)
                {
                    dgv.Rows[row + i].Cells[col].Value = data[i];
                }
            }
        }
    }
</code>```

Is there an event that fires when a paste occurs or is there some way I can cancel the paste from the Key down event?

Right now, I have a hack in place where I'm setting a bool true in the key down event and then calling e.Cancel = true; in the key press event to stop the paste from happening; there has got to be a better way!

Body:
I have a DataGridView with a column of the type DataGridViewTextBoxColumn. I want the user to be able to copy column data from Excel and paste it into the DataGridView. I'm capturing Ctrl+V in the key down event so I can parse the text and place it in the correct cells.

The problem I have is that after I assign values to the affected cells, the entire clipboard text is pasted in the active cell. For example, if 1\r\n2\r\n3 is pasted, I can place the 2 and 3 in their respective cells but 1\r\n2\r\n3 ends up in the active cell.

My code in the dgvCell_KeyDown event for reference

 private void dgvCell_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.V && e.Control)
        {
            string text = Clipboard.GetText();
            string[] data = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            int col = dgv.CurrentCell.ColumnIndex;
            int row = dgv.CurrentCell.RowIndex;
            if (data.Length <= dgv.Rows.Count - row)
            {
                for (int i = 0; i < data.Length; i++)
                {
                    dgv.Rows[row + i].Cells[col].Value = data[i];
                }
            }
        }
    }

Is there an event that fires when a paste occurs or is there some way I can cancel the paste from the Key down event?

Right now, I have a hack in place where I'm setting a bool true in the key down event and then calling e.Cancel = true; in the key press event to stop the paste from happening; there has got to be a better way!


问:
Why does the color set by vertex and fragment shaders in three js depend on the camera position of the scene?
I made 1000 points and gave them coordinates to create a ring shape. I then gave a shader material to the points and pointed to the vertex and fragment shaders.

Vertex Shader:

```<code>const vertexShader = `
uniform float uTime;
uniform float uRadius;

varying vec3 vColor;
varying float vDistance;

void main() {

  vDistance = distance(position, vec3(0.0));

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );
  gl_PointSize = 5.0;
}

`

export default vertexShader
</code>```

Fragment Shader:

```<code>const fragmentShader = `
uniform float uDistance[1000];
uniform float uResolutionWidth;
uniform float uResolutionHeight;

varying float vDistance;

  void main() {

    vec2 resolution = vec2(uResolutionWidth, uResolutionHeight);

    vec2 st = gl_FragCoord.xy/resolution;

    float pct = distance(st, vec2(1.0));

    vec3 color = vec3(mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), pct));

    gl_FragColor = vec4( color, 1.0 );
  }

`

export default fragmentShader
</code>```

What I had wanted to do was assign a color to each point based on its distance to the origin. However I realized what I did is assign a color based on the pointer distance to the camera, or at least it's what its looking like

EDIT:

I tried to pass along a varying vDistance like so

```<code>varying vec3 vRealPosition;

void main() {

  vDistance = distance(position, vec3(0.0));
  vColor = mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), vDistance);
  vRealPosition = position;

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );
  gl_PointSize = 5.0;
}
</code>```

But when I used it in fragment shader all points are just blue

```<code>varying vec3 vRealPosition;

void main() {

    vec2 resolution = vec2(uResolutionWidth, uResolutionHeight);

    vec2 st = gl_FragCoord.xy/resolution;

    float pct = distance(vRealPosition, vec3(0.0));

    vec3 color = vec3(mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), pct));

    gl_FragColor = vec4( vColor, 1.0 );
  }

</code>```

Body:
I made 1000 points and gave them coordinates to create a ring shape. I then gave a shader material to the points and pointed to the vertex and fragment shaders.

Vertex Shader:

const vertexShader = `
uniform float uTime;
uniform float uRadius;

varying vec3 vColor;
varying float vDistance;

void main() {

  vDistance = distance(position, vec3(0.0));

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );
  gl_PointSize = 5.0;
}

`

export default vertexShader

Fragment Shader:

const fragmentShader = `
uniform float uDistance[1000];
uniform float uResolutionWidth;
uniform float uResolutionHeight;

varying float vDistance;

  void main() {

    vec2 resolution = vec2(uResolutionWidth, uResolutionHeight);

    vec2 st = gl_FragCoord.xy/resolution;

    float pct = distance(st, vec2(1.0));

    vec3 color = vec3(mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), pct));

    gl_FragColor = vec4( color, 1.0 );
  }

`

export default fragmentShader

What I had wanted to do was assign a color to each point based on its distance to the origin. However I realized what I did is assign a color based on the pointer distance to the camera, or at least it's what its looking like

EDIT:

I tried to pass along a varying vDistance like so

varying vec3 vRealPosition;

void main() {

  vDistance = distance(position, vec3(0.0));
  vColor = mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), vDistance);
  vRealPosition = position;

  // Do Not Touch
  gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );
  gl_PointSize = 5.0;
}

But when I used it in fragment shader all points are just blue

varying vec3 vRealPosition;

void main() {

    vec2 resolution = vec2(uResolutionWidth, uResolutionHeight);

    vec2 st = gl_FragCoord.xy/resolution;

    float pct = distance(vRealPosition, vec3(0.0));

    vec3 color = vec3(mix(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), pct));

    gl_FragColor = vec4( vColor, 1.0 );
  }


问:
I don't understand this mistake about #pragma
This is the first part of my code and I can't understand the mistake written at the end of the message. Maybe I don't know enough to understand it. I would be very grateful if someone can explain me how #pragma works and what means the mistake. Please!!

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//estructura
#pragma pack(push, 2)
typedef struct {
char telefono[10];
char nombre[26];
char direccion[30];
int cod_cont;
}Agenda;
#pragma pack(pop)
</code>```
```<code>D:/msys64/mingw64/include/vadefs.h:14:9: error: expected '=', ',', ';', 'asm' or '__attribute__' before '#pragma'
   14 | #pragma pack(push,_CRT_PACKING)
      |         ^~~~
</code>```

I tried adding this parts:

```<code>#pragma pack(push, 2)
#pragma pack(pop)
</code>```

but the mistake keeps popping up

Body:
This is the first part of my code and I can't understand the mistake written at the end of the message. Maybe I don't know enough to understand it. I would be very grateful if someone can explain me how #pragma works and what means the mistake. Please!!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//estructura
#pragma pack(push, 2)
typedef struct {
char telefono[10];
char nombre[26];
char direccion[30];
int cod_cont;
}Agenda;
#pragma pack(pop)

D:/msys64/mingw64/include/vadefs.h:14:9: error: expected '=', ',', ';', 'asm' or '__attribute__' before '#pragma'
   14 | #pragma pack(push,_CRT_PACKING)
      |         ^~~~

I tried adding this parts:

#pragma pack(push, 2)
#pragma pack(pop)

but the mistake keeps popping up


问:
MS Access Print current data from form
In MS Access, how to print current record from the current form and then refresh the record after the printing?

I can print, but it will print the whole data from the source.

Title: MS Access Print current data from form


问:
QTreeWidget column alignment being ignored, why?
I'm running against a wall with Python and PyQt6. I'm simply trying to align each QTreeWidgetItem to the left. This works by default fine for the second column, but for some reason it refuses to align the first column's items to the left.

Here's my full code, it would be great if somebody could let me know why this isn't working:

```<code>import sys
from PyQt6.QtWidgets import QDialog, QTreeWidget, QTreeWidgetItem, QApplication
from PyQt6.QtCore import Qt

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Create the QDialog
    dialog = QDialog()
    dialog.setMinimumSize(200, 200)

    # Create the QTreeWidget
    tree = QTreeWidget(dialog)
    tree.setColumnCount(2)
    tree.setHeaderLabels(["age", "name"])

    # Add some data to the QTreeWidget
    data = [("20", "Alice"), ("25", "Bob"), ("30", "Eve")]
    for age, name in data:
        item = QTreeWidgetItem([age, name])
        item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)
        tree.addTopLevelItem(item)

    tree.headerItem().setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)

    # Show the QDialog
    dialog.show()

    app.exec()
</code>```

Here's my output when I run this program:

I experimented with 2 ways of doing this, both being ignored:

item.setData(0, Qt.ItemDataRole.TextAlignmentRole, Qt.AlignmentFlag.AlignLeft)

item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)

Body:
I'm running against a wall with Python and PyQt6. I'm simply trying to align each QTreeWidgetItem to the left. This works by default fine for the second column, but for some reason it refuses to align the first column's items to the left.

Here's my full code, it would be great if somebody could let me know why this isn't working:

import sys
from PyQt6.QtWidgets import QDialog, QTreeWidget, QTreeWidgetItem, QApplication
from PyQt6.QtCore import Qt

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Create the QDialog
    dialog = QDialog()
    dialog.setMinimumSize(200, 200)

    # Create the QTreeWidget
    tree = QTreeWidget(dialog)
    tree.setColumnCount(2)
    tree.setHeaderLabels(["age", "name"])

    # Add some data to the QTreeWidget
    data = [("20", "Alice"), ("25", "Bob"), ("30", "Eve")]
    for age, name in data:
        item = QTreeWidgetItem([age, name])
        item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)
        tree.addTopLevelItem(item)

    tree.headerItem().setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)

    # Show the QDialog
    dialog.show()

    app.exec()

Here's my output when I run this program:

I experimented with 2 ways of doing this, both being ignored:

item.setData(0, Qt.ItemDataRole.TextAlignmentRole, Qt.AlignmentFlag.AlignLeft)

item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)


问:
GetWeeklySchedule directive not being sent by Amazon
I have my own nodejs alexa interface with AWS/skill and I've made a thermostat. I can't figure out how to get alexa to send the GetWeeklySchedule directive. This is working and I get back setpoint, currrent temperature, and Controlled BY Schedule in the Alexa App. I cannot get the option to change the schedule in the Alexa App

My discovery response:

{
    endpointId: endpointId,
    manufacturerName: 'Me',
    description: description,
    friendlyName: friendlyName,
    displayCategories: ["THERMOSTAT"],
    cookie: {},
    capabilities:
    [
      {
        interface: 'Alexa.ThermostatController',
        version: '3.1',
        type: 'AlexaInterface',
        properties: {
          supported: [
            {
              name: 'targetSetpoint'
            },
            {
              name: 'thermostatMode'
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
        configuration:
        {
          supportedModes: ["HEAT", "OFF"],
          supportsScheduling: true
        }
      },
      {
        type: 'AlexaInterface',
        interface: 'Alexa.TemperatureSensor',
        version: '3',
        properties: {
          supported: [
            {
              name: 'temperature'
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
      },
      {
        type: "AlexaInterface",
        interface: "Alexa.ThermostatController.Schedule",
        version: "3.2",
        properties: {
          supported: [
            {
              name: "scheduleEnabled"
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
        configuration: {
          supportedFanModes: ["AUTO"],
          supportsAdaptiveRecovery: false
        }
      },
      {
        type: 'AlexaInterface',
        interface: 'Alexa',
        version: '3'
      }
    ]
  }
```
<p>My ReportState response:</p>
<pre class="lang-json prettyprint-override"><code>{
  namespace: 'Alexa.ThermostatController',
  name: 'thermostatMode',
  value: info.deviceMode,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController',
  name: 'targetSetpoint',
  value:
  {
    value: info.deviceSetPoint,
    scale: 'FAHRENHEIT'
  },
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.TemperatureSensor',
  name: 'temperature',
  value:
  {
    value: info.deviceTemperature,
    scale: 'FAHRENHEIT'
  },
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController.Schedule',
  name: 'adaptiveRecoveryEnabled',
  value: false,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController.Schedule',
  name: 'scheduleEnabled',
  value: true,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
</code>```

Body:
I have my own nodejs alexa interface with AWS/skill and I've made a thermostat. I can't figure out how to get alexa to send the GetWeeklySchedule directive. This is working and I get back setpoint, currrent temperature, and Controlled BY Schedule in the Alexa App. I cannot get the option to change the schedule in the Alexa App

My discovery response:

{
    endpointId: endpointId,
    manufacturerName: 'Me',
    description: description,
    friendlyName: friendlyName,
    displayCategories: ["THERMOSTAT"],
    cookie: {},
    capabilities:
    [
      {
        interface: 'Alexa.ThermostatController',
        version: '3.1',
        type: 'AlexaInterface',
        properties: {
          supported: [
            {
              name: 'targetSetpoint'
            },
            {
              name: 'thermostatMode'
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
        configuration:
        {
          supportedModes: ["HEAT", "OFF"],
          supportsScheduling: true
        }
      },
      {
        type: 'AlexaInterface',
        interface: 'Alexa.TemperatureSensor',
        version: '3',
        properties: {
          supported: [
            {
              name: 'temperature'
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
      },
      {
        type: "AlexaInterface",
        interface: "Alexa.ThermostatController.Schedule",
        version: "3.2",
        properties: {
          supported: [
            {
              name: "scheduleEnabled"
            }
          ],
          proactivelyReported: false,
          retrievable: true
        },
        configuration: {
          supportedFanModes: ["AUTO"],
          supportsAdaptiveRecovery: false
        }
      },
      {
        type: 'AlexaInterface',
        interface: 'Alexa',
        version: '3'
      }
    ]
  }

My ReportState response:

{
  namespace: 'Alexa.ThermostatController',
  name: 'thermostatMode',
  value: info.deviceMode,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController',
  name: 'targetSetpoint',
  value:
  {
    value: info.deviceSetPoint,
    scale: 'FAHRENHEIT'
  },
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.TemperatureSensor',
  name: 'temperature',
  value:
  {
    value: info.deviceTemperature,
    scale: 'FAHRENHEIT'
  },
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController.Schedule',
  name: 'adaptiveRecoveryEnabled',
  value: false,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}
{
  namespace: 'Alexa.ThermostatController.Schedule',
  name: 'scheduleEnabled',
  value: true,
  timeOfSample: new Date().toISOString(),
  uncertaintyInMilliseconds: 500
}


问:
Windows 10: Fault type errors change from 4 to 5 after several steps. Why?
I have an application that I developed that is only affecting some Windows 10 users but not all of them. The application would open then immediately shut down. I saw in the event viewer that it produced an Application Error 1000, Fault Type 4 error when this happens. I looked up some information and did several steps, including SFC, clean booting, reinstalling .NET Framework, etc. None of that worked. Then randomly out of habit I defragmented my drive and suddenly the application now opens. It still produces an Application Error 1000, but type 5 this time. It does not affect the application performance whatsoever.

My question is this: Why? And what can I do to ensure this does not happen for users of this application?

I am posting the actual error details below.

Fault 4 error cycle:

Fault bucket 1923725877593378771, type 4
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: Interstream_Windows.exe
P2: 8.0.8.58005
P3: 5d44b1d2
P4: Interstream_Windows.exe
P5: 8.0.8.58005
P6: 5d44b1d2
P7: c0000005
P8: 000000000090a90f
P9:
P10:

Analysis symbol:
Rechecking for solution: 0
Report Id: e67385ca-22aa-4211-9cf4-ed3fc989c5e1
Report Status: 268435456
Hashed bucket: c712bd3c5c6c3c2d6ab2727e4b2e0fd3
Cab Guid: 0

This is accompanied by:
Faulting application name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Faulting module name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Exception code: 0xc0000005
Fault offset: 0x000000000090a90f
Faulting process id: 0x58dc
Faulting application start time: 0x01d9213ffe2c75f1
Faulting application path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Faulting module path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Report Id: e67385ca-22aa-4211-9cf4-ed3fc989c5e1
Faulting package full name:
Faulting package-relative application ID:

Fault 5 is different, here is this code:
Fault bucket 1733984756823260336, type 5
Event Name: BEX64
Response: Not available
Cab Id: 0

Problem signature:
P1: Interstream_Windows.exe
P2: 8.0.8.58005
P3: 5d44b1d2
P4: ucrtbase.dll
P5: 10.0.18362.1110
P6: b4cacc38
P7: 000000000006dace
P8: c0000409
P9: 0000000000000007
P10:

Analysis symbol:
Rechecking for solution: 0
Report Id: 5c9cea6d-60d0-4b5f-ad90-99be23184f85
Report Status: 268435456
Hashed bucket: 66ccab7de70f21c6181059f304647cb0
```
<p>accompanied by:</p>
<pre class="lang-none prettyprint-override"><code>Faulting application name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Faulting module name: ucrtbase.dll, version: 10.0.18362.1110, time stamp: 0xb4cacc38
Exception code: 0xc0000409
Fault offset: 0x000000000006dace
Faulting process id: 0x1678
Faulting application start time: 0x01d9216b9f3abbe8
Faulting application path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Faulting module path: C:\WINDOWS\System32\ucrtbase.dll
Report Id: 5c9cea6d-60d0-4b5f-ad90-99be23184f85
Faulting package full name:
Faulting package-relative application ID:
</code>```

It is strange how different the codes are. Why?

Body:
I have an application that I developed that is only affecting some Windows 10 users but not all of them. The application would open then immediately shut down. I saw in the event viewer that it produced an Application Error 1000, Fault Type 4 error when this happens. I looked up some information and did several steps, including SFC, clean booting, reinstalling .NET Framework, etc. None of that worked. Then randomly out of habit I defragmented my drive and suddenly the application now opens. It still produces an Application Error 1000, but type 5 this time. It does not affect the application performance whatsoever.

My question is this: Why? And what can I do to ensure this does not happen for users of this application?

I am posting the actual error details below.

Fault 4 error cycle:

Fault bucket 1923725877593378771, type 4
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: Interstream_Windows.exe
P2: 8.0.8.58005
P3: 5d44b1d2
P4: Interstream_Windows.exe
P5: 8.0.8.58005
P6: 5d44b1d2
P7: c0000005
P8: 000000000090a90f
P9:
P10:

Analysis symbol:
Rechecking for solution: 0
Report Id: e67385ca-22aa-4211-9cf4-ed3fc989c5e1
Report Status: 268435456
Hashed bucket: c712bd3c5c6c3c2d6ab2727e4b2e0fd3
Cab Guid: 0

This is accompanied by:
Faulting application name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Faulting module name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Exception code: 0xc0000005
Fault offset: 0x000000000090a90f
Faulting process id: 0x58dc
Faulting application start time: 0x01d9213ffe2c75f1
Faulting application path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Faulting module path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Report Id: e67385ca-22aa-4211-9cf4-ed3fc989c5e1
Faulting package full name:
Faulting package-relative application ID:

Fault 5 is different, here is this code:
Fault bucket 1733984756823260336, type 5
Event Name: BEX64
Response: Not available
Cab Id: 0

Problem signature:
P1: Interstream_Windows.exe
P2: 8.0.8.58005
P3: 5d44b1d2
P4: ucrtbase.dll
P5: 10.0.18362.1110
P6: b4cacc38
P7: 000000000006dace
P8: c0000409
P9: 0000000000000007
P10:

Analysis symbol:
Rechecking for solution: 0
Report Id: 5c9cea6d-60d0-4b5f-ad90-99be23184f85
Report Status: 268435456
Hashed bucket: 66ccab7de70f21c6181059f304647cb0

accompanied by:

Faulting application name: Interstream_Windows.exe, version: 8.0.8.58005, time stamp: 0x5d44b1d2
Faulting module name: ucrtbase.dll, version: 10.0.18362.1110, time stamp: 0xb4cacc38
Exception code: 0xc0000409
Fault offset: 0x000000000006dace
Faulting process id: 0x1678
Faulting application start time: 0x01d9216b9f3abbe8
Faulting application path: C:\Users\jbernagozzi\Desktop\Interstream_Windows\Interstream_Windows.exe
Faulting module path: C:\WINDOWS\System32\ucrtbase.dll
Report Id: 5c9cea6d-60d0-4b5f-ad90-99be23184f85
Faulting package full name:
Faulting package-relative application ID:

It is strange how different the codes are. Why?


问:
Image throw 502 error on same domain Nextjs
My website is at example.com and I have an image at example.com/images/myimage.png (images folder is inside the /public folder.

I am trying to load that image on my website; For example

<Image
   src={`${host}/images/myimage.png`}... />
```
<p>with ${host} being http://localhost or https://example.com on production</p>
<p>My <code>next.config.js</code>:</p>
```        domains: [
            "localhost:3000",
            "localhost",
            "example.com"
        ],
```

It works perfectly on localhost (images load fine) but fails on production via Vercel;

All I get is a 502 Error with OPTIMIZED_EXTERNAL_IMAGE_REQUEST_UNAUTHORIZED as error code.

Why is this happening and how can I prevent it?

Body:
My website is at example.com and I have an image at example.com/images/myimage.png (images folder is inside the /public folder.

I am trying to load that image on my website; For example

<Image
   src={`${host}/images/myimage.png`}... />

with ${host} being http://localhost or https://example.com on production

My next.config.js:

        domains: [
            "localhost:3000",
            "localhost",
            "example.com"
        ],

It works perfectly on localhost (images load fine) but fails on production via Vercel;

All I get is a 502 Error with OPTIMIZED_EXTERNAL_IMAGE_REQUEST_UNAUTHORIZED as error code.

Why is this happening and how can I prevent it?


问:
Return Integer Array actual value on Java
This is for Codewars Kata, with Java.

the brief is :
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

If a value is present in b, all of its occurrences must be removed from the other:
Kata.arrayDiff(new int[] {1, 2, 2, 2, 3}, new int[] {2}) => new int[] {1, 3}

the Problem:
I already have solved the brief, but when return it, instead of the value i got the memory address of the arrays.

code image
Result

```<code>
import java.util.*;

public class Kata {
    public static int[] arrayDiff(int[] a, int[] b) {

        ArrayList<Integer> listA = new ArrayList<Integer>();
        ArrayList<Integer> listB = new ArrayList<Integer>();

        for (int i = 0; i < a.length; i++) {
            listA.add(a[i]);
//            listA.get(i);
        }

        for (int j = 0; j < b.length; j++) {
            listB.add(b[j]);
//            listB.get(j);
        }

        int[] newA = convertToInt(listA); //convert ArrayList to Int[]
        int[] newB = convertToInt(listB); //convert ArrayList to Int[]
        //Merge Arrays
        int al = newA.length;
        int bl = newB.length;
        int[] res = new int[al + bl];
        System.arraycopy(newA, 0, res, 0, al);
        System.arraycopy(newB, 0, res, al, bl);

//        System.out.println(Arrays.toString(res));
        // End of Merging
        removeDups(res);
        Arrays.sort(res);
        System.out.println("Sort: "+Arrays.toString(res));

//        System.out.println(listA);
//        System.out.println(listB);

        return res;
    }

    private static int[] convertToInt(ArrayList<Integer> listA) {
        Object[] obj_arr = listA.toArray();
        int[] arr = new int[listA.size()];
        for (int i = 0; i < obj_arr.length; i++) {
            arr[i] = (int) obj_arr[i];
        }

//        for (int i=0;i<arr.length;i++)
//        {
//            System.out.println(arr[i]);
//        }

        return arr;
    }

    public static void removeDups(int[] a){
        LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

        // adding elements to LinkedHashSet
        for (int i = 0; i < a.length; i++)
            set.add(a[i]);

        // Print the elements of LinkedHashSet
//        System.out.print(set);
    }
}
</code>```

Can somebody help me?

Body:
This is for Codewars Kata, with Java.

the brief is :
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

If a value is present in b, all of its occurrences must be removed from the other:
Kata.arrayDiff(new int[] {1, 2, 2, 2, 3}, new int[] {2}) => new int[] {1, 3}

the Problem:
I already have solved the brief, but when return it, instead of the value i got the memory address of the arrays.

code image
Result

import java.util.*;

public class Kata {
    public static int[] arrayDiff(int[] a, int[] b) {

        ArrayList<Integer> listA = new ArrayList<Integer>();
        ArrayList<Integer> listB = new ArrayList<Integer>();

        for (int i = 0; i < a.length; i++) {
            listA.add(a[i]);
//            listA.get(i);
        }

        for (int j = 0; j < b.length; j++) {
            listB.add(b[j]);
//            listB.get(j);
        }

        int[] newA = convertToInt(listA); //convert ArrayList to Int[]
        int[] newB = convertToInt(listB); //convert ArrayList to Int[]
        //Merge Arrays
        int al = newA.length;
        int bl = newB.length;
        int[] res = new int[al + bl];
        System.arraycopy(newA, 0, res, 0, al);
        System.arraycopy(newB, 0, res, al, bl);

//        System.out.println(Arrays.toString(res));
        // End of Merging
        removeDups(res);
        Arrays.sort(res);
        System.out.println("Sort: "+Arrays.toString(res));

//        System.out.println(listA);
//        System.out.println(listB);

        return res;
    }

    private static int[] convertToInt(ArrayList<Integer> listA) {
        Object[] obj_arr = listA.toArray();
        int[] arr = new int[listA.size()];
        for (int i = 0; i < obj_arr.length; i++) {
            arr[i] = (int) obj_arr[i];
        }

//        for (int i=0;i<arr.length;i++)
//        {
//            System.out.println(arr[i]);
//        }

        return arr;
    }

    public static void removeDups(int[] a){
        LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

        // adding elements to LinkedHashSet
        for (int i = 0; i < a.length; i++)
            set.add(a[i]);

        // Print the elements of LinkedHashSet
//        System.out.print(set);
    }
}

Can somebody help me?


问:
How to synchronize video and audio using FFMpeg
I used the following ffmpeg command to extract jepgs from a video.

```<code>ffmpeg -i video.mp4 output%4d.jpg
</code>```

Then I used the following ffmpeg command to extract audio from the same video

```<code>ffmpeg -i video.mp4 -vn -acodec copy output-audio.aac
</code>```

After processing the Jpeg images, I used ffmpeg to encode the jpeg sequence into another video.

```<code>ffmpeg -r 25 -f image2 -s 1000x800 -start_number 1 -i output%04d.jpg -vcodec libx265 -crf 25  -pix_fmt yuv420p video2.mp4
</code>```

However, the new video and audio don't match in the new video.
How can I synchronize the video and audio with ffmpeg?
I double check the framerate of both video and audio to be the same.

Thank you for your help.
I'd appreciate for any hints.

Body:
I used the following ffmpeg command to extract jepgs from a video.

ffmpeg -i video.mp4 output%4d.jpg

Then I used the following ffmpeg command to extract audio from the same video

ffmpeg -i video.mp4 -vn -acodec copy output-audio.aac

After processing the Jpeg images, I used ffmpeg to encode the jpeg sequence into another video.

ffmpeg -r 25 -f image2 -s 1000x800 -start_number 1 -i output%04d.jpg -vcodec libx265 -crf 25  -pix_fmt yuv420p video2.mp4

However, the new video and audio don't match in the new video.
How can I synchronize the video and audio with ffmpeg?
I double check the framerate of both video and audio to be the same.

Thank you for your help.
I'd appreciate for any hints.


问:
How to center a PrettyTable table in python?
I have some example code for PrettyTable module but I was wondering if there was a way to center the table in the middle of the terminal.

Code:

from prettytable import PrettyTable

# Create a new table with column names "City" and "Country"
table = PrettyTable(["City", "Country"])

# Add a row with data
table.add_row(["Paris", "France"])

# Add a column with data
table.add_column("Population", [2_141_000])

# Add another row with data
table.add_row(["Berlin", "Germany", 3_769_000])

# Print the table
print(table)
```


问:
How can I keep my Capacitor Plugin connected to an android package's foreground service on app destroy?
I'm writing a Capacitor Plugin that uses a native Android package which starts a foreground service. The Capacitor Plugin has listeners connected to the Android package for periodic updates.

While the app is in the foreground or background, the listener works and the capacitor app receives the listener callbacks.

But when the app is swiped away, the foreground service of the android package is still alive (notification status bar is active and I still see "notifying listeners" in the logs), but the capacitor plugin no longer receives any listener callbacks.

I was looking into if I need to create a bound service from the capacitor plugin to the android package somehow? Or how else can I keep the capacitor app alive while the native package's foreground service is alive

https://developer.android.com/guide/components/bound-services

The android package calls startForegroundService(intent.extras) internally, but the foreground service class is not exposed by the package

In the capacitor plugin javascript the listeners look like

```<code>export interface MyPlugin {
  addListener(eventName: 'events', listenerFunc: (result: { events: Event[] }) => void): Promise<PluginListenerHandle> & PluginListenerHandle;
  ...
}
</code>```

and in the capacitor plugin android code

```<code>public class MyPlugin extends Plugin {

    private static final String TAG = "MyPlugin";
    protected static MyPlugin sPlugin;

    @Override
    public void load() {
        sPlugin = this;

        MyPackage.setReceiver(new MyPackageReceiver() {
            @Override
            public void onEventsReceived(@NonNull Context context, @NonNull Event[] events) {
                if (sPlugin == null) {
                    return;
                }

                try {
                    JSObject ret = new JSObject();
                    ret.put("events", events);
                    sPlugin.notifyListeners("events", ret);
                } catch (Exception e) {
                    Log.e(TAG, "Exception", e);
                }
            }
        }
    }
}
</code>```

Body:
I'm writing a Capacitor Plugin that uses a native Android package which starts a foreground service. The Capacitor Plugin has listeners connected to the Android package for periodic updates.

While the app is in the foreground or background, the listener works and the capacitor app receives the listener callbacks.

But when the app is swiped away, the foreground service of the android package is still alive (notification status bar is active and I still see "notifying listeners" in the logs), but the capacitor plugin no longer receives any listener callbacks.

I was looking into if I need to create a bound service from the capacitor plugin to the android package somehow? Or how else can I keep the capacitor app alive while the native package's foreground service is alive

https://developer.android.com/guide/components/bound-services

The android package calls startForegroundService(intent.extras) internally, but the foreground service class is not exposed by the package

In the capacitor plugin javascript the listeners look like

export interface MyPlugin {
  addListener(eventName: 'events', listenerFunc: (result: { events: Event[] }) => void): Promise<PluginListenerHandle> & PluginListenerHandle;
  ...
}

and in the capacitor plugin android code

public class MyPlugin extends Plugin {

    private static final String TAG = "MyPlugin";
    protected static MyPlugin sPlugin;

    @Override
    public void load() {
        sPlugin = this;

        MyPackage.setReceiver(new MyPackageReceiver() {
            @Override
            public void onEventsReceived(@NonNull Context context, @NonNull Event[] events) {
                if (sPlugin == null) {
                    return;
                }

                try {
                    JSObject ret = new JSObject();
                    ret.put("events", events);
                    sPlugin.notifyListeners("events", ret);
                } catch (Exception e) {
                    Log.e(TAG, "Exception", e);
                }
            }
        }
    }
}


问:
Angular - Plugin chartjs-plugin-crosshair does not work

Question

I want to use the chartjs-plugin-crosshair in my angular project to show  crosshair lines in 2 linked charts. I've installed following packages using rpm:

"chart.js": "^4.1.2"

"chartjs-plugin-crosshair": "^1.2.0"

It seems that the import of the library is not done correctly and therefore it does not take the settings of the plugin. I get following errors:

error TS2305: Module '"chartjs-plugin-crosshair"' has no exported member 'Interpolate'.

error TS2339: Property 'interpolate' does not exist on type 'InteractionModeMap'.

You can take a look at the StackBlitz code. If I've made a mistake, please let me know.

Answer

Basically to fix it you have to create a file named index.d.ts and add this:

```<code>declare module 'chartjs-plugin-crosshair';
</code>```

Body:
Question

I want to use the chartjs-plugin-crosshair in my angular project to show  crosshair lines in 2 linked charts. I've installed following packages using rpm:

"chart.js": "^4.1.2"

"chartjs-plugin-crosshair": "^1.2.0"

It seems that the import of the library is not done correctly and therefore it does not take the settings of the plugin. I get following errors:

error TS2305: Module '"chartjs-plugin-crosshair"' has no exported member 'Interpolate'.

error TS2339: Property 'interpolate' does not exist on type 'InteractionModeMap'.

You can take a look at the StackBlitz code. If I've made a mistake, please let me know.

Answer

Basically to fix it you have to create a file named index.d.ts and add this:

declare module 'chartjs-plugin-crosshair';


问:
Trained randomforest model giving different predictions for the exact same set of data
I have a regression random forest model in R which I'm feeding new data through to predict (I generated the tree using the MUVR package to basically make a randomforest model). There is an issue where every sample in my new data was predicted as the exact same value.

To investigate, I fed the model the same data used to generate it as below:

```<code>predict(regrModel$Fit$rfFitMid$model, newdata=train_data)
295      296      297      298      299      300      301
82.92157 76.95937 78.32652 76.52974 81.90708 82.97120 85.89425
</code>```

Which is giving me the results I expect. But when I feed it a subset of my train data I get the following:

```<code>predict(regrModel$Fit$rfFitMid$model, newdata=train_data[298,])
    298
83.3108
</code>```

I have checked with different indexes,but the outputted prediction is always 83.3108

Apologies for the lack of code to generate the data abovbe. At this point this is more of a hail mary in trying to understand what is going wrong, so open to any/all suggestions.

Body:
I have a regression random forest model in R which I'm feeding new data through to predict (I generated the tree using the MUVR package to basically make a randomforest model). There is an issue where every sample in my new data was predicted as the exact same value.

To investigate, I fed the model the same data used to generate it as below:

predict(regrModel$Fit$rfFitMid$model, newdata=train_data)
295      296      297      298      299      300      301
82.92157 76.95937 78.32652 76.52974 81.90708 82.97120 85.89425

Which is giving me the results I expect. But when I feed it a subset of my train data I get the following:

predict(regrModel$Fit$rfFitMid$model, newdata=train_data[298,])
    298
83.3108

I have checked with different indexes,but the outputted prediction is always 83.3108

Apologies for the lack of code to generate the data abovbe. At this point this is more of a hail mary in trying to understand what is going wrong, so open to any/all suggestions.


问:
Rust russh async read/write
Hey I started with rust and I am trying to implement a SSH passthrough program.
I want to just pass through all stdin via ssh to a remote server and print the stdout.
The problem now is the return value of some commands are not terminating but are streaming.

My current not working approach is this:

async fn start_ssh_driver(host: String, user: String, private_key_path: String, run_command: String) -> Result<(), Box<dyn std::error::Error>> {

    // Open SSH Session
    let key_pair = load_secret_key(private_key_path, None)?;
    let config = client::Config {
        connection_timeout: Some(Duration::from_secs(5)),
        ..<_>::default()
    };
    let config = Arc::new(config);
    let sh = Client {};
    let mut session = client::connect(config, SocketAddr::from_str(&host).unwrap(), sh).await?;
    let _auth_res = session
        .authenticate_publickey(user, Arc::new(key_pair))
        .await?;

    // Create new channel
    let mut channel = session.channel_open_session().await.unwrap();

    // Remote stdin
    tokio::spawn(async move {
        println!("Waiting for data");
        while let Some(msg) = channel.wait().await {
            match msg {
                russh::ChannelMsg::Data { ref data } => {
                    match str::from_utf8(data) {
                        Ok(v) => println!("{}", v),
                        Err(_) => {/* ignored */},
                    };
                }
                _ => {}
            }
        }
        println!("Exited reading");
    });

    channel.exec(false, &run_command).await.unwrap();

    let stdin = stdin();
    let mut reader = BufReader::new(stdin);
    let mut line = String::new();
    loop {
        println!("> ");
        reader.read_line(&mut line).await.unwrap();
        channel.exec(false, &line).await.unwrap();
        line.clear();
    }
}
```

I get following error: borrow of moved value: 'channel' value borrowed here after move. Is there a way to copy the channel inside the task?

Title: Rust russh async read/write

Body:
Hey I started with rust and I am trying to implement a SSH passthrough program.
I want to just pass through all stdin via ssh to a remote server and print the stdout.
The problem now is the return value of some commands are not terminating but are streaming.

My current not working approach is this:

async fn start_ssh_driver(host: String, user: String, private_key_path: String, run_command: String) -> Result<(), Box<dyn std::error::Error>> {

    // Open SSH Session
    let key_pair = load_secret_key(private_key_path, None)?;
    let config = client::Config {
        connection_timeout: Some(Duration::from_secs(5)),
        ..<_>::default()
    };
    let config = Arc::new(config);
    let sh = Client {};
    let mut session = client::connect(config, SocketAddr::from_str(&host).unwrap(), sh).await?;
    let _auth_res = session
        .authenticate_publickey(user, Arc::new(key_pair))
        .await?;

    // Create new channel
    let mut channel = session.channel_open_session().await.unwrap();

    // Remote stdin
    tokio::spawn(async move {
        println!("Waiting for data");
        while let Some(msg) = channel.wait().await {
            match msg {
                russh::ChannelMsg::Data { ref data } => {
                    match str::from_utf8(data) {
                        Ok(v) => println!("{}", v),
                        Err(_) => {/* ignored */},
                    };
                }
                _ => {}
            }
        }
        println!("Exited reading");
    });

    channel.exec(false, &run_command).await.unwrap();

    let stdin = stdin();
    let mut reader = BufReader::new(stdin);
    let mut line = String::new();
    loop {
        println!("> ");
        reader.read_line(&mut line).await.unwrap();
        channel.exec(false, &line).await.unwrap();
        line.clear();
    }
}

I get following error: borrow of moved value: 'channel' value borrowed here after move. Is there a way to copy the channel inside the task?


问:
VBA: How to copy multiline text within an excel cell into word with the same format
I have an excel spreadsheet register with multiple columns and rows, I need to fill standard forms with the answers from those cells, I managed to get the VBA code to populate in the correct location, however I have 2 fields which have multiline texts within the cell and the VBA code does not account for the "Alt+Enter" within the cell and just copies it as a one long string, I would like it to copy across to the word template with the same format as the excel cell.</p>
```<code>Option Explicit
Sub CreateDoc()
Dim CustRow, CustCol, LastRow, ID, FrID, ToID As Long
Dim DocLoc, TagName, TagValue, TemplName, FileName As String
Dim WordDoc, WordApp As Object
Dim WordContent As Word.Range

With Sheet16

    If .Range("H4").Value = Empty Then
        MsgBox "Please select add a correct template"
        .Range("H4").Select
        Exit Sub

    End If
        TemplName = .Range("H4").Value                    'Set Template Name
        FrID = .Range("N4").Value                         'Set From ID
        ToID = .Range("P4").Value                         'Set to ID
        DocLoc = Sheet16.Range("J4").Value                'Word Document Filename

        'Open Word Teemplate
        On Error Resume Next                           'If Word is already running
        Set WordApp = GetObject("Word.Application")
        If Err.Number <> 0 Then                        'Launch a new instance of Word
        Err.Clear                                      'On Error GoTo Error_Handler
        Set WordApp = CreateObject("Word.Application")
        WordApp.Visble = True                          'Make the application visible to the user
        End If

        LastRow = Range("E9999").End(xlUp).Row        'Determine Last Row in Table
            For CustRow = 8 To LastRow
                ID = .Range("F" & CustRow).Value
                    If ID >= FrID And ID <= ToID Then
                        Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
                        For CustCol = 5 To 46                                                   'Move Through Columns
                            TagName = .Cells(7, CustCol).Value                                  'TagName
                            TagValue = .Cells(CustRow, CustCol).Value                           'Tag Value
                            With WordDoc.Content.Find
                                .Text = TagName
                                .Replacement.Text = TagValue
                                .Wrap = wdFindContinue
                                .Execute Replace:=wdReplaceAll                                  ', Foward:=True, Wrap:=wdFindContinue
                            End With
                        Next CustCol
                        If .Range("L4").Value = "PDF" Then
                            FileName = ThisWorkbook.Path & "\" & .Range("E4") & "\" & .Range("E" & CustRow) & " - " & .Range("H" & CustRow).Value & ".Pdf"
                            'Create full file name
                            WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
                            WordDoc.Close False

                        Else:
                            FileName = ThisWorkbook.Path & "\" & .Range("E4") & "\" & .Range("E" & CustRow) & " - " & .Range("H" & CustRow).Value & ".docx"
                            WordDoc.SaveAs FileName
                        End If
                    End If
    Next CustRow
    WordApp.Quit
End With
End Sub

</code>```

Body:
I have an excel spreadsheet register with multiple columns and rows, I need to fill standard forms with the answers from those cells, I managed to get the VBA code to populate in the correct location, however I have 2 fields which have multiline texts within the cell and the VBA code does not account for the "Alt+Enter" within the cell and just copies it as a one long string, I would like it to copy across to the word template with the same format as the excel cell.

Option Explicit
Sub CreateDoc()
Dim CustRow, CustCol, LastRow, ID, FrID, ToID As Long
Dim DocLoc, TagName, TagValue, TemplName, FileName As String
Dim WordDoc, WordApp As Object
Dim WordContent As Word.Range

With Sheet16

    If .Range("H4").Value = Empty Then
        MsgBox "Please select add a correct template"
        .Range("H4").Select
        Exit Sub

    End If
        TemplName = .Range("H4").Value                    'Set Template Name
        FrID = .Range("N4").Value                         'Set From ID
        ToID = .Range("P4").Value                         'Set to ID
        DocLoc = Sheet16.Range("J4").Value                'Word Document Filename

        'Open Word Teemplate
        On Error Resume Next                           'If Word is already running
        Set WordApp = GetObject("Word.Application")
        If Err.Number <> 0 Then                        'Launch a new instance of Word
        Err.Clear                                      'On Error GoTo Error_Handler
        Set WordApp = CreateObject("Word.Application")
        WordApp.Visble = True                          'Make the application visible to the user
        End If

        LastRow = Range("E9999").End(xlUp).Row        'Determine Last Row in Table
            For CustRow = 8 To LastRow
                ID = .Range("F" & CustRow).Value
                    If ID >= FrID And ID <= ToID Then
                        Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
                        For CustCol = 5 To 46                                                   'Move Through Columns
                            TagName = .Cells(7, CustCol).Value                                  'TagName
                            TagValue = .Cells(CustRow, CustCol).Value                           'Tag Value
                            With WordDoc.Content.Find
                                .Text = TagName
                                .Replacement.Text = TagValue
                                .Wrap = wdFindContinue
                                .Execute Replace:=wdReplaceAll                                  ', Foward:=True, Wrap:=wdFindContinue
                            End With
                        Next CustCol
                        If .Range("L4").Value = "PDF" Then
                            FileName = ThisWorkbook.Path & "\" & .Range("E4") & "\" & .Range("E" & CustRow) & " - " & .Range("H" & CustRow).Value & ".Pdf"
                            'Create full file name
                            WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
                            WordDoc.Close False

                        Else:
                            FileName = ThisWorkbook.Path & "\" & .Range("E4") & "\" & .Range("E" & CustRow) & " - " & .Range("H" & CustRow).Value & ".docx"
                            WordDoc.SaveAs FileName
                        End If
                    End If
    Next CustRow
    WordApp.Quit
End With
End Sub


问:
How to fix the error [Failed to launch the site preview in 30 seconds] in Blogdown?
I'm trying to build a website using blogdown on my windows 10 laptop and when I run blogdown::serve_site(), Rstudio tells me:

Launching the server via the command: C:/Users/Tuan/AppData/Roaming/Hugo/0.109.0/hugo.exe server --bind 127.0.0.1 -p 4321 --themesDir themes -D -F --navigateToChanged SUCCESS: The process with PID 808 (child process of PID 7592) has been terminated. SUCCESS: The process with PID 7592 (child process of PID 9480) has been terminated.

And also this error:

Error: Failed to launch the site preview in 30 seconds. Try to give it more time via the global option "blogdown.server.timeout", e.g., options(blogdown.server.timeout = 600).

I've tried restart R, reinstalling blogdown and updating packages but it's still the same.

How can I get rid of this?

Thank you.


问:
Ellipses on BIGQUERY Result Panel
I need to expand column and get rid of the ellipses (....) on the results panel of BIGQUERY SQL to show complete values

I have tried to hover the cursor on the results like in excel but it would not change the cursor so I can drag or adjust

Title: Ellipses on BIGQUERY Result Panel


问:
ImportError: cannot import name '_FunctionWrapper' from 'scipy._lib._util' (/usr/local/lib/python3.8/dist-packages/scipy/_lib/_util.py)
I'm trying to transform wav files into MEI spectrograms.

My code is as follow :

```<code>import glob
import librosa
import mei

# Create an empty list to store the spectrograms
spectrograms = []

# Set the directory containing the WAV files
mydir = "/content/drive/My Drive/Musical Classification/gtzan-fixed/Data/genres_original/disco"

# Get a list of all WAV files in the directory
file_list = glob.glob(mydir + "/*.wav")

# Iterate over all WAV files in the list
for file in file_list:
  # Load the WAV file
  data, sample_rate = librosa.load(file, sr=None)

  # Create the MEI spectrogram
  spectrogram = mei.mei(data, sample_rate, 512)

  # Add the spectrogram to the list
  spectrograms.append(spectrogram)

</code>```

ImportError                               Traceback (most recent call last)
 in
1 import glob
----> 2 import librosa
3 import mei
4
5 # Create an empty list to store the spectrograms

6 frames
/usr/local/lib/python3.8/dist-packages/scipy/optimize/_differentialevolution.py in
8 from scipy.optimize import OptimizeResult, minimize
9 from scipy.optimize._optimize import _status_message
---> 10 from scipy._lib._util import check_random_state, MapWrapper, _FunctionWrapper
11
12 from scipy.optimize._constraints import (Bounds, new_bounds_to_old,

ImportError: cannot import name '_FunctionWrapper' from 'scipy._lib._util' (/usr/local/lib/python3.8/dist-packages/scipy/_lib/_util.py)

NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.

Can you please help me thanks you.

I tried to uninstall it and reinstall it

Body:
I'm trying to transform wav files into MEI spectrograms.

My code is as follow :

import glob
import librosa
import mei

# Create an empty list to store the spectrograms
spectrograms = []

# Set the directory containing the WAV files
mydir = "/content/drive/My Drive/Musical Classification/gtzan-fixed/Data/genres_original/disco"

# Get a list of all WAV files in the directory
file_list = glob.glob(mydir + "/*.wav")

# Iterate over all WAV files in the list
for file in file_list:
  # Load the WAV file
  data, sample_rate = librosa.load(file, sr=None)

  # Create the MEI spectrogram
  spectrogram = mei.mei(data, sample_rate, 512)

  # Add the spectrogram to the list
  spectrograms.append(spectrogram)

ImportError                               Traceback (most recent call last)
 in
1 import glob
----> 2 import librosa
3 import mei
4
5 # Create an empty list to store the spectrograms

6 frames
/usr/local/lib/python3.8/dist-packages/scipy/optimize/_differentialevolution.py in
8 from scipy.optimize import OptimizeResult, minimize
9 from scipy.optimize._optimize import _status_message
---> 10 from scipy._lib._util import check_random_state, MapWrapper, _FunctionWrapper
11
12 from scipy.optimize._constraints import (Bounds, new_bounds_to_old,

ImportError: cannot import name '_FunctionWrapper' from 'scipy._lib._util' (/usr/local/lib/python3.8/dist-packages/scipy/_lib/_util.py)

NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.

Can you please help me thanks you.

I tried to uninstall it and reinstall it