问:
Replace empty values in SQL query with symbol
I need to rebuild my query:

```<code>foreach ($myDbin $dbsArr) {
 $SqlCmd.CommandText = "use [$myDb]
        Select LAST_NAME from test.[USER]
        Where ID = (Select Test_User_ID from test.UPGRADE
        Where KEYED_NAME Like '%$db%'
        and STATE = 'Active')"
}
 while ($objReader.read()) {

        foreach ($dbValue in $objReader.GetValue(0)) {
            $dbsArr +=  @($dbValue )

        }

    }
</code>```

So this query is actually shows me some info, BUT, some columns might be empty so my further array to which I put these values breaks through.

How can I add some logic to this query like:

```<code>If (LAST_NAME is empty) {
LAST_NAME = '-'
}
</code>```

But it's all should be done in SQL query, so for now I get like:

```<code>John
Bob

Sam

</code>```

in this case, my 3d and 5th values are empty(not null)
and I need to change these empty values by '-' such symbol for example.

So the result query will give me smth like:

```<code>John
Bob
-
Sam
-
</code>```

Body:
I need to rebuild my query:

foreach ($myDbin $dbsArr) {
 $SqlCmd.CommandText = "use [$myDb]
        Select LAST_NAME from test.[USER]
        Where ID = (Select Test_User_ID from test.UPGRADE
        Where KEYED_NAME Like '%$db%'
        and STATE = 'Active')"
}
 while ($objReader.read()) {

        foreach ($dbValue in $objReader.GetValue(0)) {
            $dbsArr +=  @($dbValue )

        }

    }

So this query is actually shows me some info, BUT, some columns might be empty so my further array to which I put these values breaks through.

How can I add some logic to this query like:

If (LAST_NAME is empty) {
LAST_NAME = '-'
}

But it's all should be done in SQL query, so for now I get like:

John
Bob

Sam

in this case, my 3d and 5th values are empty(not null)
and I need to change these empty values by '-' such symbol for example.

So the result query will give me smth like:

John
Bob
-
Sam
-


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How to get the exact location where a value from a symmetric matrix is above a threshold

Body:
I have multiple symmetric matrics of different lengths, I wanna get the index of the value that is above a threshold

Example

score = [array([[1.        , 0.01279797],
        [0.01279797, 1.        ]]), array([[1.        , 0.03574311],
        [0.03574311, 1.        ]]), array([[1.        , 0.0239954 , 0.02817505],
        [0.0239954 , 1.        , 0.99474305],
        [0.02817505, 0.99474305, 1.        ]]), array([[1.        , 0.36028866, 0.04977658],
        [0.36028866, 1.        , 0.3766213 ],
        [0.04977658, 0.3766213 , 1.        ]]), array([[1.        , 0.01812659],
        [0.01812659, 1.        ]]), array([[1.        , 0.06357861, 0.03934581, 0.04123461],
        [0.06357861, 1.        , 0.28277748, 0.09248888],
        [0.03934581, 0.28277748, 1.        , 0.47969105],
        [0.04123461, 0.09248888, 0.47969105, 1.        ]]), array([[1.        , 0.03861763],
        [0.03861763, 1.        ]]), array([[1.        , 0.24099389],
        [0.24099389, 1.        ]]), array([[1.        , 0.86898379],
        [0.86898379, 1.        ]]), array([[1.        , 0.18477927],
        [0.18477927, 1.        ]])]

I get the triangle above by

import numpy as np
data = []
longest  = 100
for k in range(longest):
  for i in range(len(score)):
    if len(score[i])==k:
      data.extend(score[i][np.triu_indices(score[i].shape[0], k = 1)])

x = np.array(data)
df1= np.where(x > 0.995)

df1 return the index inside data but I want to go back and get the index in the matrix

is that possible ?

I need a way to extract it, so for matrices (2*2) it is easy since the upper triangle is one number, but when a matrix is of more than 3**3 I don't know how to solve it


问:
CV2 object detection python to C++
I'm trying to create a detection which will click on the object of the defined color using cv2. But detection in python is very slow, how would the code be in c++ and how impactful is the difference between one and the other

```<code>import cv2
import dxcam
import numpy as np
from win32api import GetAsyncKeyState
import serial

fov = 38
xspd = 1
yspd = 1

# Detect yellow objects
lower = np.array([30, 160, 240])
upper = np.array([30, 255, 255])

arduino = serial.Serial('COM3', 115200)
center = fov/2
camera = dxcam.create(device_idx= 0, output_color= "BGRA")
left, top = (1920 - fov) // 2, (1080 - fov) // 2
right, bottom = left + fov, top + fov
region = (left, top, right, bottom)

camera.start(region=(region), target_fps=144)

# Click in objects
def mousemove(x,y):
        data = f"{int(x)}:{int(y-2.8)}"
        arduino.write(data.encode())

while True:
    img = camera.get_latest_frame()
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower,upper)
    kernel = np.ones((3,3), np.uint8)
    dilated = cv2.dilate(mask,kernel,iterations= 5)
    thresh = cv2.threshold(dilated, 60, 255, cv2.THRESH_BINARY)[1]
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if len(contours) != 0:
        M = cv2.moments(thresh)
        # Centroid
        point_to_aim = (int(M["m10"] / M["m00"]), (int(M["m01"] / M["m00"])))
        closestX = int(point_to_aim[0] - center) * xspd
        closestY = int((point_to_aim[1])  - center) * xspd
        mousemove(closestX, closestY)

</code>```

If it is possible to do the conversion to c++ and some explanation if the detection speed really improves with c++.

Title: CV2 object detection python to C++

Body:
I'm trying to create a detection which will click on the object of the defined color using cv2. But detection in python is very slow, how would the code be in c++ and how impactful is the difference between one and the other

import cv2
import dxcam
import numpy as np
from win32api import GetAsyncKeyState
import serial

fov = 38
xspd = 1
yspd = 1

# Detect yellow objects
lower = np.array([30, 160, 240])
upper = np.array([30, 255, 255])

arduino = serial.Serial('COM3', 115200)
center = fov/2
camera = dxcam.create(device_idx= 0, output_color= "BGRA")
left, top = (1920 - fov) // 2, (1080 - fov) // 2
right, bottom = left + fov, top + fov
region = (left, top, right, bottom)

camera.start(region=(region), target_fps=144)

# Click in objects
def mousemove(x,y):
        data = f"{int(x)}:{int(y-2.8)}"
        arduino.write(data.encode())

while True:
    img = camera.get_latest_frame()
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower,upper)
    kernel = np.ones((3,3), np.uint8)
    dilated = cv2.dilate(mask,kernel,iterations= 5)
    thresh = cv2.threshold(dilated, 60, 255, cv2.THRESH_BINARY)[1]
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if len(contours) != 0:
        M = cv2.moments(thresh)
        # Centroid
        point_to_aim = (int(M["m10"] / M["m00"]), (int(M["m01"] / M["m00"])))
        closestX = int(point_to_aim[0] - center) * xspd
        closestY = int((point_to_aim[1])  - center) * xspd
        mousemove(closestX, closestY)

If it is possible to do the conversion to c++ and some explanation if the detection speed really improves with c++.


问:
How to perform a left join inside a CASE WHEN condition
I'm trying to get all the customers that are in wallet CTE but not in the latest_call CTE to be included as an 'INVALID' condition in the CASE WHEN expression within a third CTE (parameters).

This is how I am building the query so far:

```<code>WITH wallet AS (
    SELECT *
    FROM tb_user_wallet
    WHERE id_user='123'
),
latest_call AS (
    SELECT *
    FROM
      (SELECT c.*, ROW_NUMBER() OVER (PARTITION BY c.id_customer ORDER BY c.date DESC) AS Rnum
      FROM wallet
      join tb_calls c
      ON c.id_customer = wallet.id_customer) c
    WHERE Rnum=1
    and c.status_call='sucess'
),
parameters AS (
    SELECT lc.id_customer,
        CASE
            WHEN(lc.date='2022-12-12') THEN 'VALID'
                        WHEN(lc.date='2022-12-13') THEN 'INVALID'
                        WHEN(w.id_customer not in lc) THEN  'INVALID' -- CONDITION THAT I'M TRYING TO FIGURE OUT HOW TO EXECUTE
        END AS CONDITION
    FROM latest_call as lc
    JOIN wallet as w
    on w.id_customer = lc.id_customer
    GROUP BY w.id_customer, lc.id_customer, lc.date)
 SELECT CONDITION, COUNT (CONDTION) AS TOTAL
 FROM PARAMETERS
 GROUP BY COND;
</code>```

The final select should look like this:

CONDTION
QTD

VALID
10

INVALID
21

Body:
I'm trying to get all the customers that are in wallet CTE but not in the latest_call CTE to be included as an 'INVALID' condition in the CASE WHEN expression within a third CTE (parameters).

This is how I am building the query so far:

WITH wallet AS (
    SELECT *
    FROM tb_user_wallet
    WHERE id_user='123'
),
latest_call AS (
    SELECT *
    FROM
      (SELECT c.*, ROW_NUMBER() OVER (PARTITION BY c.id_customer ORDER BY c.date DESC) AS Rnum
      FROM wallet
      join tb_calls c
      ON c.id_customer = wallet.id_customer) c
    WHERE Rnum=1
    and c.status_call='sucess'
),
parameters AS (
    SELECT lc.id_customer,
        CASE
            WHEN(lc.date='2022-12-12') THEN 'VALID'
                        WHEN(lc.date='2022-12-13') THEN 'INVALID'
                        WHEN(w.id_customer not in lc) THEN  'INVALID' -- CONDITION THAT I'M TRYING TO FIGURE OUT HOW TO EXECUTE
        END AS CONDITION
    FROM latest_call as lc
    JOIN wallet as w
    on w.id_customer = lc.id_customer
    GROUP BY w.id_customer, lc.id_customer, lc.date)
 SELECT CONDITION, COUNT (CONDTION) AS TOTAL
 FROM PARAMETERS
 GROUP BY COND;

The final select should look like this:

CONDTION
QTD

VALID
10

INVALID
21


问:
Is it possible to overload macros that contain VA_ARGS for logs?
I try overload WriteLogs macro with 1 and 2 params:

```<code>template <typename... Args>
void WriteLog(const LogContext& logContext, const LogSettings& logSettings, std::string formatMsg, Args... args) {
    // ...
    printf("formatMsg", args...);
    // ...
}

#define WriteLog_1(message, ...) WriteLog(LogContext{__LINE__, __FILE__, __FUNCTION__}, LogSettings{false, 0}, message, ##__VA_ARGS__)
#define WriteLog_2(settings, message, ...) WriteLog(LogContext{__LINE__, __FILE__, __FUNCTION__}, settings, message, ##__VA_ARGS__)

#define EXPAND(x) x
#define GET_MACRO(_1, _2, NAME, ...) NAME
#define WriteLogs(...) EXPAND(GET_MACRO(__VA_ARGS__, WriteDebug2, WriteDebug1)(__VA_ARGS__))
</code>```

so is it possible to overload them for usage:

```<code>int main() {
   WriteLogs("hello %s, %d + %d = %d", "world", 2, 2, 5); // WriteLog_1
   WriteLogs(LogSettings{true, 0}, "hello %s, %d + %d = %d", "world", 2, 2, 5); // WriteLog_2
}
</code>```

Body:
I try overload WriteLogs macro with 1 and 2 params:

template <typename... Args>
void WriteLog(const LogContext& logContext, const LogSettings& logSettings, std::string formatMsg, Args... args) {
    // ...
    printf("formatMsg", args...);
    // ...
}

#define WriteLog_1(message, ...) WriteLog(LogContext{__LINE__, __FILE__, __FUNCTION__}, LogSettings{false, 0}, message, ##__VA_ARGS__)
#define WriteLog_2(settings, message, ...) WriteLog(LogContext{__LINE__, __FILE__, __FUNCTION__}, settings, message, ##__VA_ARGS__)

#define EXPAND(x) x
#define GET_MACRO(_1, _2, NAME, ...) NAME
#define WriteLogs(...) EXPAND(GET_MACRO(__VA_ARGS__, WriteDebug2, WriteDebug1)(__VA_ARGS__))

so is it possible to overload them for usage:

int main() {
   WriteLogs("hello %s, %d + %d = %d", "world", 2, 2, 5); // WriteLog_1
   WriteLogs(LogSettings{true, 0}, "hello %s, %d + %d = %d", "world", 2, 2, 5); // WriteLog_2
}


问:
Dataframe shows less rows that are in file
I want to create dataframe with pandas that consists a txt file of 12000 rows and 3 columns. Whenever i try to read_csv it says that dataframe is 1998x3. I tried header=None but still does not show right dimensions. There is no header in dataset, just raw data. example first row in txt: 1.03, 3.01, 2.01
What can i do?


问:
How to add an option to enable changes in perlscript using the environment variables method?
Using either the -rundir or the environment variable method i want to add an option to the perlscript to enable changes and Check if current memory(sum of the pid process+ subprocess memory)is more than previous max, log the memory of each process which is being used to compute the total memory then log the time of this max memory usage

Couldn’t really find out how to do so


问:
CircleCI + Rails 7 + Yarn + assets:precompile - `yarn: not found`
I am using Circle CI to run RSpec tests on a Rails project. I'm new to CircleCI, so I'm piecing together a build script from examples.

My tests are failing because application.css is not in the asset pipeline. Here is the exact error:

```<code>ActionView::Template::Error:
  The asset "application.css" is not present in the asset pipeline.
</code>```

I figured this is because the assets are not being precompiled. So I added bundle exec rails assets:precompile to my config.yml. I also included cimg/node:19.2.0 to provide yarn.

However, when the build runs, CircleCI reports that the yarn command cannot be found. Here is the exact error:

```<code>#!/bin/bash -eo pipefail
bundle exec rake assets:precompile
sh: 1: yarn: not found
rake aborted!
jsbundling-rails: Command build failed, ensure yarn is installed and `yarn build` runs without errors
/home/circleci/my_project/vendor/bundle/ruby/3.1.0/gems/jsbundling-rails-1.0.3/lib/tasks/jsbundling/build.rake:5:in `block (2 levels) in <main>'
/home/circleci/my_project/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/exe/rake:27:in `<top (required)>'
/home/circleci/.rubygems/bin/bundle:25:in `load'
/home/circleci/.rubygems/bin/bundle:25:in `<main>'
Tasks: TOP => assets:precompile => javascript:build
(See full trace by running task with --trace)

Exited with code exit status 1
CircleCI received exit code 1
</code>```

My understanding is that yarn should be provided by the cimg/node:19.2.0, so I'm not sure why it cannot be found.

I've posted my config.yml as a Gist here: https://gist.github.com/johnnyicon/d805a1c178563d37c837b4eb2e5bb776

Line 22 is where I added cimg/node:19.2.0

Lines 53-55 is where I added bundle exec assets:precompile

It might be important to note that my tests were running fine (and passing) until I started testing view-related code.

Body:
I am using Circle CI to run RSpec tests on a Rails project. I'm new to CircleCI, so I'm piecing together a build script from examples.

My tests are failing because application.css is not in the asset pipeline. Here is the exact error:

ActionView::Template::Error:
  The asset "application.css" is not present in the asset pipeline.

I figured this is because the assets are not being precompiled. So I added bundle exec rails assets:precompile to my config.yml. I also included cimg/node:19.2.0 to provide yarn.

However, when the build runs, CircleCI reports that the yarn command cannot be found. Here is the exact error:

#!/bin/bash -eo pipefail
bundle exec rake assets:precompile
sh: 1: yarn: not found
rake aborted!
jsbundling-rails: Command build failed, ensure yarn is installed and `yarn build` runs without errors
/home/circleci/my_project/vendor/bundle/ruby/3.1.0/gems/jsbundling-rails-1.0.3/lib/tasks/jsbundling/build.rake:5:in `block (2 levels) in '
/home/circleci/my_project/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/exe/rake:27:in `<top (required)>'
/home/circleci/.rubygems/bin/bundle:25:in `load'
/home/circleci/.rubygems/bin/bundle:25:in `'
Tasks: TOP => assets:precompile => javascript:build
(See full trace by running task with --trace)

Exited with code exit status 1
CircleCI received exit code 1

My understanding is that yarn should be provided by the cimg/node:19.2.0, so I'm not sure why it cannot be found.

I've posted my config.yml as a Gist here: https://gist.github.com/johnnyicon/d805a1c178563d37c837b4eb2e5bb776

Line 22 is where I added cimg/node:19.2.0

Lines 53-55 is where I added bundle exec assets:precompile

It might be important to note that my tests were running fine (and passing) until I started testing view-related code.


问:
I need help creating a script where it analyse only Okiru Label including the column that is in the script
Currently I have an issue with my script it shows ValueError, Couldn't figure out what cause it. The line would be this line

```<code>SVM_classifier = SVC(C=1.0, cache_size=1500, verbose=True).fit(X_train, Y_train)
</code>```

The line is from this block

```<code>start = time.time()
print('program start...')
print()

SVM_classifier = SVC(C=1.0, cache_size=1500, verbose=True).fit(X_train, Y_train)
print()
print(SVM_classifier.score(X_test, Y_test))
print()

y_pred = SVM_classifier.predict(X_test)
print(y_pred)
print()

end = time.time()
print('program end...')
print()
print('time cost: ')
print(end - start, 'seconds')
</code>```

Body:
Currently I have an issue with my script it shows ValueError, Couldn't figure out what cause it. The line would be this line

SVM_classifier = SVC(C=1.0, cache_size=1500, verbose=True).fit(X_train, Y_train)

The line is from this block

start = time.time()
print('program start...')
print()

SVM_classifier = SVC(C=1.0, cache_size=1500, verbose=True).fit(X_train, Y_train)
print()
print(SVM_classifier.score(X_test, Y_test))
print()

y_pred = SVM_classifier.predict(X_test)
print(y_pred)
print()

end = time.time()
print('program end...')
print()
print('time cost: ')
print(end - start, 'seconds')


问:
How to handle powershell requiring script to RunAsAdministrator to use get-counter on vmware.exe when using VS code

I could change the acl to put me as an admin in all the vmware stuff on my host, or

run VS code as an administrator

In powershell_ise, this works fine (Administrator):

```<code>ADMIN > Get-Counter -Counter '\Process(vmware)\% Processor Time'

Timestamp                  CounterSamples
---------                  --------------
12/13/2022 5:17:02 PM      \\i7\process(vmware)\% processor time :
                           0

                                                                                ADMIN >
</code>```

In powershell_ise, this does not (not Administrator):
S> Get-Counter -Counter '\Process(vmware)% Processor Time'
Get-Counter : The \Process(vmware)% Processor Time performance counter path  is not valid.

I am worried I am going to break something by choosing 1 or 2. To change the network settings in VMware, it prompts for UAC.

But, changing the whole VS code as an administrator. That seems dangerous to me.
This is all run on a home, not enterprise, computer. So, I control everything.

I am not going to try anything further until I look over the options.

Body:
I could change the acl to put me as an admin in all the vmware stuff on my host, or

run VS code as an administrator

In powershell_ise, this works fine (Administrator):

ADMIN > Get-Counter -Counter '\Process(vmware)\% Processor Time'

Timestamp                  CounterSamples
---------                  --------------
12/13/2022 5:17:02 PM      \\i7\process(vmware)\% processor time :
                           0

                                                                                ADMIN >

In powershell_ise, this does not (not Administrator):
S> Get-Counter -Counter '\Process(vmware)% Processor Time'
Get-Counter : The \Process(vmware)% Processor Time performance counter path  is not valid.

I am worried I am going to break something by choosing 1 or 2. To change the network settings in VMware, it prompts for UAC.

But, changing the whole VS code as an administrator. That seems dangerous to me.
This is all run on a home, not enterprise, computer. So, I control everything.

I am not going to try anything further until I look over the options.


问:
Interaction between frontend and backend Docker-containers
I have created simple application: backend on Spring Boot, database: Postgres, frontend on AngularJS. Frontend and backend - are 2 different projects. I can run it locally on computer, and it works! Then i have created 2 images and upload them to Docker Hub. And now i am trying to run an application in Docker-containers. I am trying to create docker-compose file with 3 services. Now this file looks like that:

```<code>version: '3.0'

services:

    database:
        # service description here ...

    backend:
        image: my_back_image
        environment:
            - 'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'
            - 'DATASOURCE_USER=admin1'
            - 'DATASOURCE_PSWD=123'
        depends_on:
            - database
        networks:
            - net

    frontend:
        image: my_front_image
        ports:
            - 8099:80
        depends_on:
            - backend
        networks:
            - net

volumes:
    data-prod:

networks:
    net:
        driver: bridge
</code>```

Next, I have run this file. I have no problem with creating a connection between the backend-container and database-container. I create access using service name, like this:

```<code>'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'  # access using service name 'database'
</code>```

The problem was: firstly i could not connect the frontend-container with backend container.

My frontend is a very simple application. It consists with 2 files: index.html and index.js. I am using AngularJS, and index.js file has path for requests:

```<code>const apiPath = 'http://localhost:8082/api/v1';
</code>```

8082 because Tomcat-server on backend start on port 8082.

But inside the container frontend will send a request to its internal localhost:8082. And therefore, the data from the backend is not pulled up and I see only my html-layout, and i also see errors in the browser-console:

Then i tried to open the port of backend-server. I have added this 2 lines to docker-compose:

```<code>ports:
    - 8082:8082
</code>```

and now backend-service look like this:

```<code># .....

backend:
    image: my_back_image

    # Why this help to me???
    ports:
        - 8082:8082

    environment:
        - 'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'
        - 'DATASOURCE_USER=admin1'
        - 'DATASOURCE_PSWD=123'
    depends_on:
        - database
    networks:
        - net

# .....
</code>```

then i start docker-compose file again.
Now i go to browser, and again open http://localhost:8099/

and now everything is OK, application is working!

I don't understand: why opening the server port (8082) is helped me? If I understand correctly, at this moment the scheme of my containers like this:

Port 8099:80 is open on the frontend. Therefore, when I type localhost:8099 in the browser on the local computer, i go inside the container with frontend. Inside frontend-container, my angular-application is running on the nginx server. It sends a request to localhost:8082 but that is localhost inside this container!

And in the backend container, port 8082:8082 is open. But it is open for access from the host-computer, not from the front-container!

But for some reason it is work now!

Can you explain me, why if i open 8082:8082 on the backend-container the application begin to work?

P.S.: when i created frontend-image i wrote the Dockerfile:

```<code>FROM nginx
WORKDIR /usr/share/nginx/html
COPY html/ .
</code>```

but i never create any nginx-configuration files, such as nginx.conf, or default.nginx or others. Maybe it would be better to create some kind of nginx configuration file?

Body:
I have created simple application: backend on Spring Boot, database: Postgres, frontend on AngularJS. Frontend and backend - are 2 different projects. I can run it locally on computer, and it works! Then i have created 2 images and upload them to Docker Hub. And now i am trying to run an application in Docker-containers. I am trying to create docker-compose file with 3 services. Now this file looks like that:

version: '3.0'

services:

    database:
        # service description here ...

    backend:
        image: my_back_image
        environment:
            - 'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'
            - 'DATASOURCE_USER=admin1'
            - 'DATASOURCE_PSWD=123'
        depends_on:
            - database
        networks:
            - net

    frontend:
        image: my_front_image
        ports:
            - 8099:80
        depends_on:
            - backend
        networks:
            - net

volumes:
    data-prod:

networks:
    net:
        driver: bridge

Next, I have run this file. I have no problem with creating a connection between the backend-container and database-container. I create access using service name, like this:

'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'  # access using service name 'database'

The problem was: firstly i could not connect the frontend-container with backend container.

My frontend is a very simple application. It consists with 2 files: index.html and index.js. I am using AngularJS, and index.js file has path for requests:

const apiPath = 'http://localhost:8082/api/v1';

8082 because Tomcat-server on backend start on port 8082.

But inside the container frontend will send a request to its internal localhost:8082. And therefore, the data from the backend is not pulled up and I see only my html-layout, and i also see errors in the browser-console:

Then i tried to open the port of backend-server. I have added this 2 lines to docker-compose:

ports:
    - 8082:8082

and now backend-service look like this:

# .....

backend:
    image: my_back_image

    # Why this help to me???
    ports:
        - 8082:8082

    environment:
        - 'DATASOURCE_URL=jdbc:postgresql://database:5432/converter_prod'
        - 'DATASOURCE_USER=admin1'
        - 'DATASOURCE_PSWD=123'
    depends_on:
        - database
    networks:
        - net

# .....

then i start docker-compose file again.
Now i go to browser, and again open http://localhost:8099/

and now everything is OK, application is working!

I don't understand: why opening the server port (8082) is helped me? If I understand correctly, at this moment the scheme of my containers like this:

Port 8099:80 is open on the frontend. Therefore, when I type localhost:8099 in the browser on the local computer, i go inside the container with frontend. Inside frontend-container, my angular-application is running on the nginx server. It sends a request to localhost:8082 but that is localhost inside this container!

And in the backend container, port 8082:8082 is open. But it is open for access from the host-computer, not from the front-container!

But for some reason it is work now!

Can you explain me, why if i open 8082:8082 on the backend-container the application begin to work?

P.S.: when i created frontend-image i wrote the Dockerfile:

FROM nginx
WORKDIR /usr/share/nginx/html
COPY html/ .

but i never create any nginx-configuration files, such as nginx.conf, or default.nginx or others. Maybe it would be better to create some kind of nginx configuration file?


问:
Cloudinary cannot work properly in node.js registerUser rest Api?
Here I work on an ecommerce website by using mern stack so I created a rest Api in node.js its work properly when I only add json data such as email,password,name its work but when I want to send an avatar means image its throw an error but when I comment out all code that setup cloudinary Its work other wise its throw an error?

Its Usecontroller file where I made different rest Apis

```<code>const catchAsyncError = require("../middleware/catchAsyncError");
const ErrorHandler = require("../utils/errorhandler");
//const ErrorHandler = require("../middleware/error.js");
const User=require("../models/userModel");
const sendToken=require("../utils/Jwttoken");
const sendEmail=require("../utils/sendEmail")
const crypto=require('crypto')
const cloudinary=require("cloudinary");

// Register a User

 exports.registerUser=catchAsyncError(async(req,res,next)=>{

  console.log("BackendR1")
  const myCloud=await cloudinary.v2.uploader.upload(req.body.avatar,{
    folder:"avatars",
    width:150,
    crop:"scale",
  });
  console.log("BackendR2");
  const {name,email,password}=req.body;
  const user=await User.create({
    name,
    email,
    password,
    avatar:{
        public_id:myCloud.public_id,
        url:myCloud.secure_url
    }
  });
  console.log("Backend R3");
 sendToken(user,201,res)
})
</code>```

here is my app.js

```<code>const express=require('express')
const cookieParser=require('cookie-parser')
const errorMiddleware=require("./middleware/error")
const bodyParser=require("body-parser")
const fileupload=require("express-fileupload")

const app=express();
app.use(express.json())
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended:true}));
app.use(fileupload());

//route imports

const product=require('./routes/productRoute')
const user=require('./routes/userRoute')
const order=require('./routes/orderRoutes')

app.use("/api/v1",product);
app.use("/api/v1",user);
app.use("/api/v1",order);
//middleware for error

app.use(errorMiddleware)

module.exports=app;

Here is my Server.js file
const { appendFile } = require('fs')
const app=require('./App')
const cloudinary=require("cloudinary")

const dotenv=require("dotenv")
const connectDatabase=require("./config/database")

// handling uncaught exeption
process.on("uncaughtException",(err)=>{
    console.log(`Error:${err.message}`);
    console.log(`shutting down the server due to uncaught exeption`);
    process.exit(1);
})

//config
dotenv.config({path:"backend/config/config.env"})
connectDatabase()

cloudinary.config({
    cloud_name:process.env.CLOUDINARY_NAME,
    api_key:process.env.CLOUDINARY_API_KEY,
    api_secret:process.env.CLOUDINARY_API_SECRET
})

const server=app.listen(process.env.PORT,()=>{
    console.log(`Server is listining at ${process.env.PORT}`)
})

//unhandled promise rejection
process.on("unhandledRejection",(err)=>{
    console.log(`Error:${err.message}`);
    console.log(`shutting down the server due to unhandled rejection`);

    server.close(()=>{
        process.exit(1);
    })

})
</code>```

Here is the mongodb schema

```<code>const mongoose=require('mongoose');
const validator=require('validator')
const bcrypt=require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto=require('crypto')
const userSchema =new mongoose.Schema({

  name:{
    type:String,
    required:[true,"Please enter your name"],
    maxLength:[30,"name cannot exeed 30 characters"],
    minLength:[3,"Name Should have more then 3 character"],
  },
  email:{
    type:String,
    required:[true,"Please enter your email"],
    unique:true,
    validate:[validator.isEmail,"Please enter a valid email"],

  },
  password:{
    type:String,
    required:[true,"Please enter your password"],
    minLength:[8,"password should be more then 8 character"],
    select:false,
  },
  avatar:{

        public_id:{
            type:String,
            required:true
        },
        url:{
            type:String,
            required:true
        }

  },
  role:{
    type:String,
    default:"user"
  },
  resetPasswordToken:String,
  resetPasswordExpire:Date

})
userSchema.pre("save",async function(next){
  if(!this.isModified("password")){
    next();
  }
  this.password=await bcrypt.hash(this.password,10)
})
//jwt token
userSchema.methods.getJWTToken=function(){

  return jwt.sign({id:this._id},process.env.JWT_SECRET,{
    expiresIn:process.env.JWT_EXPIRE
  })
}

userSchema.methods.comparePassword=async function(enterpassword){
   return await bcrypt.compare(enterpassword,this.password)
}

//Generating Password Reset Token
userSchema.methods.getResetPasswordToken=function(){
  //Generating Token
  const resetToken=crypto.randomBytes(20).toString("hex");
  //Hashing and Adding Reset Password schema to UserSchema
  this.resetPasswordToken=crypto.createHash("sha256").update(resetToken).digest("hex");
  this.resetPasswordExpire=Date.now()*15*60*1000;

}
module.exports=mongoose.model("User",userSchema)
</code>```

Body:
Here I work on an ecommerce website by using mern stack so I created a rest Api in node.js its work properly when I only add json data such as email,password,name its work but when I want to send an avatar means image its throw an error but when I comment out all code that setup cloudinary Its work other wise its throw an error?

Its Usecontroller file where I made different rest Apis

const catchAsyncError = require("../middleware/catchAsyncError");
const ErrorHandler = require("../utils/errorhandler");
//const ErrorHandler = require("../middleware/error.js");
const User=require("../models/userModel");
const sendToken=require("../utils/Jwttoken");
const sendEmail=require("../utils/sendEmail")
const crypto=require('crypto')
const cloudinary=require("cloudinary");

// Register a User

 exports.registerUser=catchAsyncError(async(req,res,next)=>{

  console.log("BackendR1")
  const myCloud=await cloudinary.v2.uploader.upload(req.body.avatar,{
    folder:"avatars",
    width:150,
    crop:"scale",
  });
  console.log("BackendR2");
  const {name,email,password}=req.body;
  const user=await User.create({
    name,
    email,
    password,
    avatar:{
        public_id:myCloud.public_id,
        url:myCloud.secure_url
    }
  });
  console.log("Backend R3");
 sendToken(user,201,res)
})

here is my app.js

const express=require('express')
const cookieParser=require('cookie-parser')
const errorMiddleware=require("./middleware/error")
const bodyParser=require("body-parser")
const fileupload=require("express-fileupload")

const app=express();
app.use(express.json())
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended:true}));
app.use(fileupload());

//route imports

const product=require('./routes/productRoute')
const user=require('./routes/userRoute')
const order=require('./routes/orderRoutes')

app.use("/api/v1",product);
app.use("/api/v1",user);
app.use("/api/v1",order);
//middleware for error

app.use(errorMiddleware)

module.exports=app;

Here is my Server.js file
const { appendFile } = require('fs')
const app=require('./App')
const cloudinary=require("cloudinary")

const dotenv=require("dotenv")
const connectDatabase=require("./config/database")

// handling uncaught exeption
process.on("uncaughtException",(err)=>{
    console.log(`Error:${err.message}`);
    console.log(`shutting down the server due to uncaught exeption`);
    process.exit(1);
})

//config
dotenv.config({path:"backend/config/config.env"})
connectDatabase()

cloudinary.config({
    cloud_name:process.env.CLOUDINARY_NAME,
    api_key:process.env.CLOUDINARY_API_KEY,
    api_secret:process.env.CLOUDINARY_API_SECRET
})

const server=app.listen(process.env.PORT,()=>{
    console.log(`Server is listining at ${process.env.PORT}`)
})

//unhandled promise rejection
process.on("unhandledRejection",(err)=>{
    console.log(`Error:${err.message}`);
    console.log(`shutting down the server due to unhandled rejection`);

    server.close(()=>{
        process.exit(1);
    })

})

Here is the mongodb schema

const mongoose=require('mongoose');
const validator=require('validator')
const bcrypt=require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto=require('crypto')
const userSchema =new mongoose.Schema({

  name:{
    type:String,
    required:[true,"Please enter your name"],
    maxLength:[30,"name cannot exeed 30 characters"],
    minLength:[3,"Name Should have more then 3 character"],
  },
  email:{
    type:String,
    required:[true,"Please enter your email"],
    unique:true,
    validate:[validator.isEmail,"Please enter a valid email"],

  },
  password:{
    type:String,
    required:[true,"Please enter your password"],
    minLength:[8,"password should be more then 8 character"],
    select:false,
  },
  avatar:{

        public_id:{
            type:String,
            required:true
        },
        url:{
            type:String,
            required:true
        }

  },
  role:{
    type:String,
    default:"user"
  },
  resetPasswordToken:String,
  resetPasswordExpire:Date

})
userSchema.pre("save",async function(next){
  if(!this.isModified("password")){
    next();
  }
  this.password=await bcrypt.hash(this.password,10)
})
//jwt token
userSchema.methods.getJWTToken=function(){

  return jwt.sign({id:this._id},process.env.JWT_SECRET,{
    expiresIn:process.env.JWT_EXPIRE
  })
}

userSchema.methods.comparePassword=async function(enterpassword){
   return await bcrypt.compare(enterpassword,this.password)
}

//Generating Password Reset Token
userSchema.methods.getResetPasswordToken=function(){
  //Generating Token
  const resetToken=crypto.randomBytes(20).toString("hex");
  //Hashing and Adding Reset Password schema to UserSchema
  this.resetPasswordToken=crypto.createHash("sha256").update(resetToken).digest("hex");
  this.resetPasswordExpire=Date.now()*15*60*1000;

}
module.exports=mongoose.model("User",userSchema)


问:
Excel VBA ListBox only displaying 1 column, not the 8 added columns
So I have a listbox (CustomerList) that updates based on my ComboBox Value (CustomerName). I was hoping to have it search and display the listed customer information based ont he combobox text, I can get my "Cust ID" to display and populate as expected, but all of my other columns seem to be MIA or hidden perhaps.

```<code>   Private Sub CustomerName_Change()
    Dim i As Long
    Dim sh As Worksheet
        Set sh = ThisWorkbook.Sheets("Customer Database")
    Dim Last_Row As Long
        Last_Row = Worksheets("Customer Database").Cells(Rows.Count, 1).End(xlUp).Row
    Me.CustomerName = Format(StrConv(Me.CustomerName.Text, vbLowerCase))
        With Me.CustomerList
            .Clear
            .AddItem "Cust. ID"
            .List(0, 1) = "Customer Name"
            .List(0, 2) = "Customer Business"
            .List(0, 3) = "Customer Address"
            .List(0, 4) = "Customer Phone"
            .List(0, 5) = "Customer Email"
            .List(0, 6) = "Machine Serial#"
            .List(0, 7) = "Machine Serial#"
            .List(0, 8) = "Machine Serial#"
        End With
    Me.CustomerList.Selected(0) = True
        For i = 2 To Last_Row
        For X = 1 To Len(sh.Cells(i, 1))
        a = Me.CustomerName.TextLength
            If LCase(Mid(sh.Cells(i, 2), X, a)) = Me.CustomerName And Me.CustomerName <> "" Then
        With Me.CustomerList
            .AddItem sh.Cells(i, 3)
            .List(CustomerList.ListCount - 1, 0) = sh.Cells(i, 1)
            .List(CustomerList.ListCount - 1, 1) = sh.Cells(i, 2)
            .List(CustomerList.ListCount - 1, 2) = sh.Cells(i, 3)
            .List(CustomerList.ListCount - 1, 3) = sh.Cells(i, 4)
            .List(CustomerList.ListCount - 1, 4) = sh.Cells(i, 5)
            .List(CustomerList.ListCount - 1, 5) = sh.Cells(i, 6)
            .List(CustomerList.ListCount - 1, 6) = sh.Cells(i, 7)
            .List(CustomerList.ListCount - 1, 7) = sh.Cells(i, 8)
        End With
    End If
    Next X
    Next i
    End Sub
</code>```

Have tried declaring column widths aswell, which did not do anything. however when selecting the entry from my listbox the expected boxes populate with the correct customer information.

Body:
So I have a listbox (CustomerList) that updates based on my ComboBox Value (CustomerName). I was hoping to have it search and display the listed customer information based ont he combobox text, I can get my "Cust ID" to display and populate as expected, but all of my other columns seem to be MIA or hidden perhaps.

   Private Sub CustomerName_Change()
    Dim i As Long
    Dim sh As Worksheet
        Set sh = ThisWorkbook.Sheets("Customer Database")
    Dim Last_Row As Long
        Last_Row = Worksheets("Customer Database").Cells(Rows.Count, 1).End(xlUp).Row
    Me.CustomerName = Format(StrConv(Me.CustomerName.Text, vbLowerCase))
        With Me.CustomerList
            .Clear
            .AddItem "Cust. ID"
            .List(0, 1) = "Customer Name"
            .List(0, 2) = "Customer Business"
            .List(0, 3) = "Customer Address"
            .List(0, 4) = "Customer Phone"
            .List(0, 5) = "Customer Email"
            .List(0, 6) = "Machine Serial#"
            .List(0, 7) = "Machine Serial#"
            .List(0, 8) = "Machine Serial#"
        End With
    Me.CustomerList.Selected(0) = True
        For i = 2 To Last_Row
        For X = 1 To Len(sh.Cells(i, 1))
        a = Me.CustomerName.TextLength
            If LCase(Mid(sh.Cells(i, 2), X, a)) = Me.CustomerName And Me.CustomerName <> "" Then
        With Me.CustomerList
            .AddItem sh.Cells(i, 3)
            .List(CustomerList.ListCount - 1, 0) = sh.Cells(i, 1)
            .List(CustomerList.ListCount - 1, 1) = sh.Cells(i, 2)
            .List(CustomerList.ListCount - 1, 2) = sh.Cells(i, 3)
            .List(CustomerList.ListCount - 1, 3) = sh.Cells(i, 4)
            .List(CustomerList.ListCount - 1, 4) = sh.Cells(i, 5)
            .List(CustomerList.ListCount - 1, 5) = sh.Cells(i, 6)
            .List(CustomerList.ListCount - 1, 6) = sh.Cells(i, 7)
            .List(CustomerList.ListCount - 1, 7) = sh.Cells(i, 8)
        End With
    End If
    Next X
    Next i
    End Sub

Have tried declaring column widths aswell, which did not do anything. however when selecting the entry from my listbox the expected boxes populate with the correct customer information.


问:
Vitest mocks function available in template but not in script
I have mocked function in my global config

```<code>config.global.mocks.route = (name) => route(name, undefined, undefined, Ziggy);
</code>```

If I access route() inside the <template> everything works as expected but if I try to access rotue() inside method

```<code>const submit = () => {
    form.post(route('login'), {
        onFinish: () => form.reset('password'),
    });
};
</code>```

I get an error that ReferenceError: route is not defined

Any ideas why?

Body:
I have mocked function in my global config

config.global.mocks.route = (name) => route(name, undefined, undefined, Ziggy);

If I access route() inside the <template> everything works as expected but if I try to access rotue() inside method

const submit = () => {
    form.post(route('login'), {
        onFinish: () => form.reset('password'),
    });
};

I get an error that ReferenceError: route is not defined

Any ideas why?


问:
React native component state not clearing/ umounting
I am using a the same component (BottomSheet) on two different screens in my react navigation stack.

When I go from one page to another, it keeps the component state. How can I refresh the component when I browse to another screen?

```<code>const HomeScreen = () => {
...

  const showSheet = data.reminderVehicles.length !== 0 ? true : false;

  return (
    <BottomSheet
      firstSnapshot={160}
      secondSnapshot={90}
      renderContent={renderSheetContent()}
      tapToOpenEnabled
      headerClose={true}
      hide={showSheet}
    >
.....
    </BottomSheet>
  );
};

export default HomeScreen;

export const MyVehicleScreen = ({ navigation }) => {

  return (
...
      <BottomSheet
        firstSnapshot={160}
        secondSnapshot={90}
        renderContent={renderSheetContent()}
        tapToOpenEnabled
        hide={false}
      >

      </BottomSheet>
    </RACPageStructure>
  );
};
</code>```

BottomSheet component:

```<code>const BottomSheet = ({
    children,
    firstSnapshot,
    secondSnapshot,
    renderHeader,
    renderContent,
    backgroundColor,
    tapToOpenEnabled,
    headerClose,
    hide,
}) => {
  ...

    return (
        <WrapperComponent onPress={toggleOpen}>
            <Animated.View style={childrenStyle}>{children}</Animated.View>
            {!hide && (
                <PanGestureHandler onGestureEvent={handleSwipe}>
                    ....
                    </Animated.View>
                </PanGestureHandler>
            )}
        </WrapperComponent>
    );
};
</code>```

Navigation stack:

```<code>return (
    <TabStack.Navigator
      initialRouteName={initialRouteName}
      tabBarOptions={{
        ...
      }}
    >
      <TabStack.Screen
        name={AppRoutes.Home.Name}
        ...
      </TabStack.Screen>
      <TabStack.Screen
        name={AppRoutes.MyVehicle.Name}
        ...
      </TabStack.Screen>
</code>```

Body:
I am using a the same component (BottomSheet) on two different screens in my react navigation stack.

When I go from one page to another, it keeps the component state. How can I refresh the component when I browse to another screen?

const HomeScreen = () => {
...

  const showSheet = data.reminderVehicles.length !== 0 ? true : false;

  return (
    <BottomSheet
      firstSnapshot={160}
      secondSnapshot={90}
      renderContent={renderSheetContent()}
      tapToOpenEnabled
      headerClose={true}
      hide={showSheet}
    >
.....
    </BottomSheet>
  );
};

export default HomeScreen;

export const MyVehicleScreen = ({ navigation }) => {

  return (
...
      <BottomSheet
        firstSnapshot={160}
        secondSnapshot={90}
        renderContent={renderSheetContent()}
        tapToOpenEnabled
        hide={false}
      >

      </BottomSheet>
    </RACPageStructure>
  );
};

BottomSheet component:

const BottomSheet = ({
    children,
    firstSnapshot,
    secondSnapshot,
    renderHeader,
    renderContent,
    backgroundColor,
    tapToOpenEnabled,
    headerClose,
    hide,
}) => {
  ...

    return (
        <WrapperComponent onPress={toggleOpen}>
            <Animated.View style={childrenStyle}>{children}</Animated.View>
            {!hide && (
                <PanGestureHandler onGestureEvent={handleSwipe}>
                    ....
                    </Animated.View>
                </PanGestureHandler>
            )}
        </WrapperComponent>
    );
};

Navigation stack:

return (
    <TabStack.Navigator
      initialRouteName={initialRouteName}
      tabBarOptions={{
        ...
      }}
    >
      <TabStack.Screen
        name={AppRoutes.Home.Name}
        ...
      </TabStack.Screen>
      <TabStack.Screen
        name={AppRoutes.MyVehicle.Name}
        ...
      </TabStack.Screen>


问:
broken header on load sitemap.xml for google search
sitemap.xml not work in my host:

```<code><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://tcg-wallet.ga/</loc>
        <lastmod>2022-12-13T17:12:22+00:00</lastmod>
    </url>
</urlset>
</code>```

located in public, and loaded via: https://tcg-wallet.ga/sitemap.xml

in network i see this:

but when i try to get it working in google search i get this:

i have test it with: https://www.xml-sitemaps.com/ and get this:

i have try handle the content type with .htaccess but is not enough to solve the problem:

```<code><IfModule mod_expires.c>
    AddType application/xml                   xml

</IfModule>
</code>```

I can't find that it is misconfigured.***

Body:
sitemap.xml not work in my host:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://tcg-wallet.ga/</loc>
        <lastmod>2022-12-13T17:12:22+00:00</lastmod>
    </url>
</urlset>

located in public, and loaded via: https://tcg-wallet.ga/sitemap.xml

in network i see this:

but when i try to get it working in google search i get this:

i have test it with: https://www.xml-sitemaps.com/ and get this:

i have try handle the content type with .htaccess but is not enough to solve the problem:

<IfModule mod_expires.c>
    AddType application/xml                   xml

</IfModule>

I can't find that it is misconfigured.***


问:
AWS Lambda Function Shell Command not Found
I have a lambda function as part of a custom deployment stack. It calls /opt/awscli/aws s3 s3//<bucket name> /tmp/tmpfolder/

But it returns with a error 127. Presumably, because it can't find /opt/awscli/aws.

This is the code that errors:

```<code>def aws_command(*args):
    aws="/opt/awscli/aws" # from AwsCliLayer
    logger.info("| aws %s" % ' '.join(args))
    subprocess.check_call([aws] + list(args))

</code>```

This is the stacktrace:

```<code>[ERROR] 2022-12-13T06:08:25.547Z    7a8c5bee-a4ec-4ef0-aa53-6ebe2496f89d    Command '['/opt/awscli/aws', 's3', 'cp', 's3://<bucket_name>/<80cd38...rest_of_zip>.zip', '/tmp/tmpblg17gcs/006ca603-6934-431e-9a96-0bd41b25d465']' returned non-zero exit status 127.
Traceback (most recent call last):
  File "/var/task/index.py", line 103, in handler
    s3_deploy(s3_source_zips, s3_dest, user_metadata, system_metadata, prune)
  File "/var/task/index.py", line 130, in s3_deploy
    aws_command("s3", "cp", s3_source_zip, archive)
  File "/var/task/index.py", line 188, in aws_command
    subprocess.check_call([aws] + list(args))
  File "/var/lang/lib/python3.9/subprocess.py", line 373, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/opt/awscli/aws', 's3', 'cp', 's3://cdk-hnb659fds-assets-403230261384-us-west-2/80cd38c81cb1261c29a32510bb6fafd2cfbe110c40d6ab17cb9e78fc2b78202b.zip', '/tmp/tmpblg17gcs/006ca603-6934-431e-9a96-0bd41b25d465']' returned non-zero exit status 127.
</code>```

Does anyone have an idea how to make sure /opt/awscli/aws it where it should be found by lambda function? Is there a way to manually install onto the ec2 instance?

Body:
I have a lambda function as part of a custom deployment stack. It calls /opt/awscli/aws s3 s3//<bucket name> /tmp/tmpfolder/

But it returns with a error 127. Presumably, because it can't find /opt/awscli/aws.

This is the code that errors:

def aws_command(*args):
    aws="/opt/awscli/aws" # from AwsCliLayer
    logger.info("| aws %s" % ' '.join(args))
    subprocess.check_call([aws] + list(args))

This is the stacktrace:

[ERROR] 2022-12-13T06:08:25.547Z    7a8c5bee-a4ec-4ef0-aa53-6ebe2496f89d    Command '['/opt/awscli/aws', 's3', 'cp', 's3://<bucket_name>/<80cd38...rest_of_zip>.zip', '/tmp/tmpblg17gcs/006ca603-6934-431e-9a96-0bd41b25d465']' returned non-zero exit status 127.
Traceback (most recent call last):
  File "/var/task/index.py", line 103, in handler
    s3_deploy(s3_source_zips, s3_dest, user_metadata, system_metadata, prune)
  File "/var/task/index.py", line 130, in s3_deploy
    aws_command("s3", "cp", s3_source_zip, archive)
  File "/var/task/index.py", line 188, in aws_command
    subprocess.check_call([aws] + list(args))
  File "/var/lang/lib/python3.9/subprocess.py", line 373, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/opt/awscli/aws', 's3', 'cp', 's3://cdk-hnb659fds-assets-403230261384-us-west-2/80cd38c81cb1261c29a32510bb6fafd2cfbe110c40d6ab17cb9e78fc2b78202b.zip', '/tmp/tmpblg17gcs/006ca603-6934-431e-9a96-0bd41b25d465']' returned non-zero exit status 127.

Does anyone have an idea how to make sure /opt/awscli/aws it where it should be found by lambda function? Is there a way to manually install onto the ec2 instance?


问:
Receive data from esp32 and show it on an app(Android Studio)
I am trying to create an android app using Android Studio in order to receive some data from an ESP32 in order to display those data on an app build using Android Studio.

I have came across many but couldn't successfully implement the idea.

Please help. I will be highly obliged.

An esp32 code and Android Studio code.


问:
Travel Rule Protocol: how to decode LNURL with bech32
Issue: bech32 algo only supports strings less than 90 characters. But LNURL can be more than 90 characters: https://github.com/lnurl/luds/blob/luds/01.md

Question: How to do the encoding / decoding? Does anyone have any code examples?


问:
Walker 'ID' number in emcee? (Python)
I am using the Emcee python package to fit some models to data. The models are created using a separate piece of software.

For each step in the MCMC chain, each walker generates a new input file to the software, and then creates a 'fresh' copy of the software in a new directory which can be run. The likelihood is computed from the outputs.

Is it possible to extract walker 'id' numbers for each step, so that I can provide unique names to the software directories when they are copied over?

Title: Walker 'ID' number in emcee? (Python)


问:
How can I define this OR type on Typescript to avoid that errors?
I have problems with types...There are some errors using this OR typing. I need to give to elements prop a different type depending of type prop, how I could do that? Thanks.

Code:

```<code>      interface LayoutProps {
        type: LayoutPropsType;
        elements: OneElementLayoutProps | TwoElementsLayoutProps;
      }
      interface OneElementLayoutProps {
        component: React.ReactElement;
      }
      interface TwoElementsLayoutProps {
        leftcomponent: React.ReactElement;
        rightcomponent: React.ReactElement;
      }
      ...
      {layout.type === LayoutPropsType.one && (
        <OneElementLayout
          component={layout.elements.component} // Error. Don't exists on TwoElementsLayoutProps
        ></OneElementLayout>
      )}
      {layout.type === LayoutPropsType.two && (
        <TwoElementsLayout
          leftComponent={layout.elements.leftComponent} // Error. Don't exists on OneElementLayoutProps
          rightComponent={layout.elements.rightComponent} // Error. Don't exists on OneElementLayoutProps
        ></TwoElementsLayout>
      )}
      ...
</code>```

Body:
I have problems with types...There are some errors using this OR typing. I need to give to elements prop a different type depending of type prop, how I could do that? Thanks.

Code:

      interface LayoutProps {
        type: LayoutPropsType;
        elements: OneElementLayoutProps | TwoElementsLayoutProps;
      }
      interface OneElementLayoutProps {
        component: React.ReactElement;
      }
      interface TwoElementsLayoutProps {
        leftcomponent: React.ReactElement;
        rightcomponent: React.ReactElement;
      }
      ...
      {layout.type === LayoutPropsType.one && (
        <OneElementLayout
          component={layout.elements.component} // Error. Don't exists on TwoElementsLayoutProps
        ></OneElementLayout>
      )}
      {layout.type === LayoutPropsType.two && (
        <TwoElementsLayout
          leftComponent={layout.elements.leftComponent} // Error. Don't exists on OneElementLayoutProps
          rightComponent={layout.elements.rightComponent} // Error. Don't exists on OneElementLayoutProps
        ></TwoElementsLayout>
      )}
      ...


问:
if else statement to check and configure switches. if the config is there, do nothing. if it is not there, implement it
i want to run a script that checks for configs, if the config is true, the script should do nothing, if the config is not available, the script should configure it. the script should then print a csv appending the configs that were carried out to the csv.

however, when i ran the script below, it did not configure the ntp sever, but cos it is configured, but it reconfigured the ntp peer and the timezone which were there already.

```<code>from netmiko import ConnectHandler
from getpass import getpass
import time
import os

cisco1 = {
    "device_type": "cisco_ios",
    "host": "10.0.0.0.",
    "username": "adm",
    "password": getpass(),
    "ssh_config_file": "~/.ssh/ssh_config",
}

with ConnectHandler(**cisco1) as net_connect:
    output = net_connect.send_command('sh ntp ass')
    outputd = net_connect.send_command('sh clock det')
    print(output)
    print(outputd)
    net_connect.enable()
    net_connect.config_mode()
    #print("Connected Successfully")

    P = '192.168.1.1'
    S = '192.168.1.2'
    EST = 'clock timezone est -5'
    EDT = 'clock summer-time edt recurring'

    if output == P:
        print ('Primary NTP is present')
    elif output != P:
        output1 = net_connect.send_config_set('ntp server 192.168.1.1') # where ntp server  is absent, implement the config.
        print(output, output1)
    if output == S:
        print('Secondary NTP is present')
    elif output != S:
        output2 = net_connect.send_config_set('ntp peer 192.168.1.2')
        print(output, output2)
    if outputd == EST:
        print('EST time correct')
    elif outputd != EST:
        output3 = net_connect.send_config_set('clock timezone est -5')
        print(outputd, output3)

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

Body:
i want to run a script that checks for configs, if the config is true, the script should do nothing, if the config is not available, the script should configure it. the script should then print a csv appending the configs that were carried out to the csv.

however, when i ran the script below, it did not configure the ntp sever, but cos it is configured, but it reconfigured the ntp peer and the timezone which were there already.

from netmiko import ConnectHandler
from getpass import getpass
import time
import os

cisco1 = {
    "device_type": "cisco_ios",
    "host": "10.0.0.0.",
    "username": "adm",
    "password": getpass(),
    "ssh_config_file": "~/.ssh/ssh_config",
}

with ConnectHandler(**cisco1) as net_connect:
    output = net_connect.send_command('sh ntp ass')
    outputd = net_connect.send_command('sh clock det')
    print(output)
    print(outputd)
    net_connect.enable()
    net_connect.config_mode()
    #print("Connected Successfully")

    P = '192.168.1.1'
    S = '192.168.1.2'
    EST = 'clock timezone est -5'
    EDT = 'clock summer-time edt recurring'

    if output == P:
        print ('Primary NTP is present')
    elif output != P:
        output1 = net_connect.send_config_set('ntp server 192.168.1.1') # where ntp server  is absent, implement the config.
        print(output, output1)
    if output == S:
        print('Secondary NTP is present')
    elif output != S:
        output2 = net_connect.send_config_set('ntp peer 192.168.1.2')
        print(output, output2)
    if outputd == EST:
        print('EST time correct')
    elif outputd != EST:
        output3 = net_connect.send_config_set('clock timezone est -5')
        print(outputd, output3)


问:
Error: Error trying to display an error. with PyMNE
I have a huge problems after updating PyMNE to v0.2.0.
It shows very strange behavior, especially interacting with other packages

It can give this kind of error, or go to eternal installation, or some its functions do not work.

This error happens after:

```<code>using Makie
using TopoPlots
using PyMNE
</code>```

I tryed to do it in REPL, but it crashes and error message disappears immediately.
So I even do not understand what is the problem.

Do you have any ideas what to do?

Body:
I have a huge problems after updating PyMNE to v0.2.0.
It shows very strange behavior, especially interacting with other packages

It can give this kind of error, or go to eternal installation, or some its functions do not work.

This error happens after:

using Makie
using TopoPlots
using PyMNE

I tryed to do it in REPL, but it crashes and error message disappears immediately.
So I even do not understand what is the problem.

Do you have any ideas what to do?


问:
Chrome Crux API - depending when API request is run no data is populated for URLs
I've run my code below in the morning (between 8AM EST - 11AM EST) and no data populates for my urls, however in the evening (at no specific time) data populates.

I'm using the Crux API docs here, specifically looking at daily-updates:
https://developer.chrome.com/docs/crux/api/#daily-updates

Which states:

Data is updated daily around 04:00 UTC. There is no service level
agreement for update times; it is run on a best-effort basis every
day.

More importantly it also states:

Data will not differ within the same day after it has been updated
around 04:00 UTC, repeated calls will yield the same results.

Which I feel means should have data always populating for these urls if they had populated for the previous day!

My code:

```<code>import requests
import json

x = {"formFactor":"TABLET",
"metrics":["largest_contentful_paint", "experimental_time_to_first_byte",
           "first_contentful_paint", "cumulative_layout_shift",
          "first_input_delay", "experimental_interaction_to_next_paint"],
"url":"https://www.happy-tests.com/id",
    }

url = "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key={key}"

headers = {"Content-Type": "application/json",
          "Accept": "application/json"}

response = requests.post(url, json=x, headers=headers)

response_json = response.json()
print(response_json)
</code>```

'error': {'code': 404, 'message': 'chrome ux report data not found',
'status': 'NOT_FOUND'}}

Body:
I've run my code below in the morning (between 8AM EST - 11AM EST) and no data populates for my urls, however in the evening (at no specific time) data populates.

I'm using the Crux API docs here, specifically looking at daily-updates:
https://developer.chrome.com/docs/crux/api/#daily-updates

Which states:

Data is updated daily around 04:00 UTC. There is no service level
agreement for update times; it is run on a best-effort basis every
day.

More importantly it also states:

Data will not differ within the same day after it has been updated
around 04:00 UTC, repeated calls will yield the same results.

Which I feel means should have data always populating for these urls if they had populated for the previous day!

My code:

import requests
import json

x = {"formFactor":"TABLET",
"metrics":["largest_contentful_paint", "experimental_time_to_first_byte",
           "first_contentful_paint", "cumulative_layout_shift",
          "first_input_delay", "experimental_interaction_to_next_paint"],
"url":"https://www.happy-tests.com/id",
    }

url = "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key={key}"

headers = {"Content-Type": "application/json",
          "Accept": "application/json"}

response = requests.post(url, json=x, headers=headers)

response_json = response.json()
print(response_json)

'error': {'code': 404, 'message': 'chrome ux report data not found',
'status': 'NOT_FOUND'}}


问:
VSCode doesn't recognize ConfluentKafkaLibrary to use in Robot Framework
I need to do a test automation in Robot Framework using Kafka topics. I'm trying to use the ConfluentKafkaLibrary library, but VSCode doesn't recognize it.

I already installed the commands:

```<code>pip install robotframework-confluentkafkalibrary
pip install confluent-kafka
</code>```

Still, it keeps giving the error:

Unresolved library: ConfluentKafkaLibrary. Error generating libspec: Importing library 'ConfluentKafkaLibrary' failed: ModuleNotFoundError: No module named '_bz2' Consider adding the needed paths to the "robot.pythonpath" setting and calling the "Robot Framework: Clear caches and restart" action.

Does anyone know how to solve this problem?

IMAGE - error message

I already tried to reinstall all libraries.

I already tried to configure the robot.pythonpath.

I've restarted VSCode several times, after each step.

Body:
I need to do a test automation in Robot Framework using Kafka topics. I'm trying to use the ConfluentKafkaLibrary library, but VSCode doesn't recognize it.

I already installed the commands:

pip install robotframework-confluentkafkalibrary
pip install confluent-kafka

Still, it keeps giving the error:

Unresolved library: ConfluentKafkaLibrary. Error generating libspec: Importing library 'ConfluentKafkaLibrary' failed: ModuleNotFoundError: No module named '_bz2' Consider adding the needed paths to the "robot.pythonpath" setting and calling the "Robot Framework: Clear caches and restart" action.

Does anyone know how to solve this problem?

IMAGE - error message

I already tried to reinstall all libraries.

I already tried to configure the robot.pythonpath.

I've restarted VSCode several times, after each step.


问:
Can you add a NPopover to a disabled NButton?
I am new to naive ui and am trying to add a popover to a disabled button. Is this possible? When I add the popover, it won't show up when the button is disabled. Is there a special trick to get it to show?

Here's the code I have:

```<code>NPopover(trigger="hover" placement="top")
        template(#trigger="")
          NButton(ref="resumeButton" type="primary" icon-placement="right" size="small" v-if="isLoadingComplete && buttonState === 'resume'" @click="resumeMetricsLoading" :disabled="isLoadingComplete" color="#d3d3d3")
            NIcon(:size="iconSize")
              PlayArrowSharp
        | All data has loaded
</code>```

Body:
I am new to naive ui and am trying to add a popover to a disabled button. Is this possible? When I add the popover, it won't show up when the button is disabled. Is there a special trick to get it to show?

Here's the code I have:

NPopover(trigger="hover" placement="top")
        template(#trigger="")
          NButton(ref="resumeButton" type="primary" icon-placement="right" size="small" v-if="isLoadingComplete && buttonState === 'resume'" @click="resumeMetricsLoading" :disabled="isLoadingComplete" color="#d3d3d3")
            NIcon(:size="iconSize")
              PlayArrowSharp
        | All data has loaded


问:
Pygame ValueError: subsurface rectangle outside surface area
I am currently working on a game on Pygame in Python. It is a player vs player battle game. When the program is run the value error subsurface rectangle outside surface area is shown. I searched about the error but could not understand about it as I am new to Pygame.

My program-

```<code>import pygame
from Players import Characters

pygame.init()

#Game window
swidth = 1000
sheight= 600
s=pygame.display.set_mode((swidth, sheight))
pygame.display.set_caption("Brawler")

#Framerate
clock = pygame.time.Clock()
FPS = 60

#Game variables
count=3
last_count_update=pygame.time.get_ticks()
score = [0, 0]#player scores. [P1, P2]
round_over = False
round_cooldown = 2000

#Player variables
Knight_size = 278
Knight_scale = 4
Knight_offset = [72, 56]
Knight_data = [Knight_size, Knight_scale, Knight_offset]

Assassin_size = 288
Assassin_scale = 3
Assassin_offset = [112, 107]
Assassin_data =[ Assassin_size, Assassin_scale, Assassin_offset]

#load background image
bg_image = pygame.image.load("G1/Assets/Bg.png").convert_alpha()

#load spritesheets
Knight_sheet = pygame.image.load("G1/Assets/Knight/Sprites.png").convert_alpha()
Assassin_sheet = pygame.image.load("G1/Assets/Assassin/Sprites.png").convert_alpha()

#load vicory image
victory_img = pygame.image.load("G1/Assets/victory.png").convert_alpha()

#define number of steps in each animation
Knight_steps=[8, 8, 20, 8, 11, 19, 10, 6, 13]
Assassin_steps=[8, 8, 6, 6, 8, 18, 7, 6, 19]

#Font
count_font = pygame.font.Font("G1/assets/fonts/turok.ttf", 80)
score_font = pygame.font.Font("G1/assets/fonts/turok.ttf", 30)

#Text
def draw_text(text, font, text_col, x, y):
  img = font.render(text, True, text_col)
  s.blit(img, (x, y))

#Background
def draw_bg():
  scaled_bg = pygame.transform.scale(bg_image, (swidth, sheight))
  s.blit(scaled_bg, (0, 0))

#Health bars
red=(255, 0, 0)
yellow=(255, 255, 0)
white=(255, 255, 255)
def draw_health_bar(health, x, y):
  ratio = health / 100
  pygame.draw.rect(s, white, (x - 2, y - 2, 404, 34))
  pygame.draw.rect(s, red, (x, y, 400, 30))
  pygame.draw.rect(s, yellow, (x, y, 400 * ratio, 30))

#Player avatars
Knight=Characters(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
Assassin=Characters(2, 700, 310, True, Assassin_data, Assassin_sheet, Assassin_steps)

#game loop
run = True
while run:

  clock.tick(FPS)

  #Display background
  draw_bg()

  #Display health bar
  draw_health_bar(Knight.health, 20, 20)
  draw_health_bar(Assassin.health, 580, 20)
  draw_text("P1: " + str(score[0]), score_font, red, 20, 60)
  draw_text("P2: " + str(score[1]), score_font, red, 580, 60)

  #countdown
  if intro_count <= 0:
    #Move fighters
    Knight.move(swidth, sheight, s, Assassin, round_over)
    Assassin.move(swidth, sheight, s, Knight, round_over)
  else:

    #Display count timer
    draw_text(str(intro_count), count_font, red, swidth/2, sheight/3)

    #update count timer
    if (pygame.time.get_ticks()-last_count_update)>= 1000:
      intro_count -= 1
      last_count_update = pygame.time.get_ticks()

  #Update fighters
  Knight.update()
  Assassin.update()

  #Display fighters
  Knight.draw(s)
  Assassin.draw(s)

  #check for player defeat
  if round_over == False:
    if Knight.alive == False:
      score[1] += 1
      round_over = True
      round_over_time = pygame.time.get_ticks()
    elif Assassin.alive == False:
      score[0] += 1
      round_over = True
      round_over_time = pygame.time.get_ticks()
  else:
    #display victory image
    s.blit(victory_img, (360, 150))
    if pygame.time.get_ticks()-round_over_time>round_cooldown:
      round_over = False
      intro_count = 3
      Knight= Knight(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
      Assassin= Assassin(2, 700, 310, True, Assassin_data, Assassin_sheet, Assassin_steps)

  #event handler
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run = False

  #update display
  pygame.display.update()

#exit pygame
pygame.quit()`
</code>```

My Module-

```<code>import pygame

class Characters():
  def __init__(self, player, x, y, flip, data, sheet, steps):
    self.player = player
    self.size = data[0]
    self.image_scale = data[1]
    self.offset = data[2]
    self.flip = flip
    self.animation_list = self.load_images(sheet, steps)
    self.action = 0#0:idle #1:run #2:jump #3:attack1 #4: attack2 #5:hit #6:death
    self.frame_index = 0
    self.image = self.animation_list[self.action][self.frame_index]
    self.update_time = pygame.time.get_ticks()
    self.rect = pygame.Rect((x, y, 80, 180))
    self.vel_y = 0
    self.running = False
    self.jump = False
    self.attacking = False
    self.attack_type = 0
    self.attack_cooldown = 0
    self.hit = False
    self.health = 100
    self.alive = True

  def load_images(self, sheet, steps):
    #extract images from spritesheet
    animation_list = []
    for y, animation in enumerate(steps):
      temp_img_list = []
      for x in range(animation):
        temp_img = sheet.subsurface(x * self.size, y * self.size, self.size, self.size)
        temp_img_list.append(pygame.transform.scale(temp_img, (self.size * self.image_scale, self.size * self.image_scale)))
      animation_list.append(temp_img_list)
    return animation_list

  def move(self, screen_width, screen_height, surface, target, round_over):
    SPEED = 10
    GRAVITY = 2
    dx = 0
    dy = 0
    self.running = False
    self.attack_type = 0

    #get keypresses
    key = pygame.key.get_pressed()

    #can only perform other actions if not currently attacking
    if self.attacking == False and self.alive == True and round_over == False:
      #check player 1 controls
      if self.player == 1:
        #movement
        if key[pygame.K_a]:
          dx = -SPEED
          self.running = True
        if key[pygame.K_d]:
          dx = SPEED
          self.running = True
        #jump
        if key[pygame.K_w] and self.jump == False:
          self.vel_y = -30
          self.jump = True
        #attack
        if key[pygame.K_r] or key[pygame.K_t]:
          self.attack(target)
          #determine which attack type was used
          if key[pygame.K_r]:
            self.attack_type = 1
          if key[pygame.K_t]:
            self.attack_type = 2

      #check player 2 controls
      if self.player == 2:
        #movement
        if key[pygame.K_LEFT]:
          dx = -SPEED
          self.running = True
        if key[pygame.K_RIGHT]:
          dx = SPEED
          self.running = True
        #jump
        if key[pygame.K_UP] and self.jump == False:
          self.vel_y = -30
          self.jump = True
        #attack
        if key[pygame.K_KP1] or key[pygame.K_KP2]:
          self.attack(target)
          #determine which attack type was used
          if key[pygame.K_KP1]:
            self.attack_type = 1
          if key[pygame.K_KP2]:
            self.attack_type = 2

    #apply gravity
    self.vel_y += GRAVITY
    dy += self.vel_y

    #ensure player stays on screen
    if self.rect.left + dx < 0:
      dx = -self.rect.left
    if self.rect.right + dx > screen_width:
      dx = screen_width - self.rect.right
    if self.rect.bottom + dy > screen_height - 220:
      self.vel_y = 0
      self.jump = False
      dy = screen_height - 220 - self.rect.bottom

    #ensure players face each other
    if target.rect.centerx > self.rect.centerx:
      self.flip = False
    else:
      self.flip = True

    #apply attack cooldown
    if self.attack_cooldown > 0:
      self.attack_cooldown -= 1

    #update player position
    self.rect.x += dx
    self.rect.y += dy

  #handle animation updates
  def update(self):
    #check what action the player is performing
    if self.health <= 0:
      self.health = 0
      self.alive = False
      self.update_action(6)#6:death
    elif self.hit == True:
      self.update_action(5)#5:hit
    elif self.attacking == True:
      if self.attack_type == 1:
        self.update_action(3)#3:attack1
      elif self.attack_type == 2:
        self.update_action(4)#4:attack2
    elif self.jump == True:
      self.update_action(2)#2:jump
    elif self.running == True:
      self.update_action(1)#1:run
    else:
      self.update_action(0)#0:idle

    animation_cooldown = 50
    #update image
    self.image = self.animation_list[self.action][self.frame_index]
    #check if enough time has passed since the last update
    if pygame.time.get_ticks() - self.update_time > animation_cooldown:
      self.frame_index += 1
      self.update_time = pygame.time.get_ticks()
    #check if the animation has finished
    if self.frame_index >= len(self.animation_list[self.action]):
      #if the player is dead then end the animation
      if self.alive == False:
        self.frame_index = len(self.animation_list[self.action]) - 1
      else:
        self.frame_index = 0
        #check if an attack was executed
        if self.action == 3 or self.action == 4:
          self.attacking = False
          self.attack_cooldown = 20
        #check if damage was taken
        if self.action == 5:
          self.hit = False
          #if the player was in the middle of an attack, then the attack is stopped
          self.attacking = False
          self.attack_cooldown = 20

  def attack(self, target):
    if self.attack_cooldown == 0:
      #execute attack
      self.attacking = True
      self.attack_sound.play()
      attacking_rect = pygame.Rect(self.rect.centerx - (2 * self.rect.width * self.flip), self.rect.y, 2 * self.rect.width, self.rect.height)
      if attacking_rect.colliderect(target.rect):
        target.health -= 10
        target.hit = True

  def update_action(self, new_action):
    #check if the new action is different to the previous one
    if new_action != self.action:
      self.action = new_action

      #update the animation settings
      self.frame_index = 0
      self.update_time = pygame.time.get_ticks()

  def draw(self, surface):
    img = pygame.transform.flip(self.image, self.flip, False)
    surface.blit(img, (self.rect.x - (self.offset[0] * self.image_scale), self.rect.y - (self.offset[1] * self.image_scale)))
</code>```

The error occurred-

```<code>File "c:\Users\User\Desktop\G1\Battle game V1.py", line 73, in <module>
    Knight=Characters(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
  File "c:\Users\User\Desktop\G1\Players.py", line 10, in __init__
    self.animation_list = self.load_images(sheet, steps)
  File "c:\Users\User\Desktop\G1\Players.py", line 33, in load_images
    temp_img = sheet.subsurface(x * self.size, y * self.size, self.size, self.size)
ValueError: subsurface rectangle outside surface area
</code>```

Body:
I am currently working on a game on Pygame in Python. It is a player vs player battle game. When the program is run the value error subsurface rectangle outside surface area is shown. I searched about the error but could not understand about it as I am new to Pygame.

My program-

import pygame
from Players import Characters

pygame.init()

#Game window
swidth = 1000
sheight= 600
s=pygame.display.set_mode((swidth, sheight))
pygame.display.set_caption("Brawler")

#Framerate
clock = pygame.time.Clock()
FPS = 60

#Game variables
count=3
last_count_update=pygame.time.get_ticks()
score = [0, 0]#player scores. [P1, P2]
round_over = False
round_cooldown = 2000

#Player variables
Knight_size = 278
Knight_scale = 4
Knight_offset = [72, 56]
Knight_data = [Knight_size, Knight_scale, Knight_offset]

Assassin_size = 288
Assassin_scale = 3
Assassin_offset = [112, 107]
Assassin_data =[ Assassin_size, Assassin_scale, Assassin_offset]

#load background image
bg_image = pygame.image.load("G1/Assets/Bg.png").convert_alpha()

#load spritesheets
Knight_sheet = pygame.image.load("G1/Assets/Knight/Sprites.png").convert_alpha()
Assassin_sheet = pygame.image.load("G1/Assets/Assassin/Sprites.png").convert_alpha()

#load vicory image
victory_img = pygame.image.load("G1/Assets/victory.png").convert_alpha()

#define number of steps in each animation
Knight_steps=[8, 8, 20, 8, 11, 19, 10, 6, 13]
Assassin_steps=[8, 8, 6, 6, 8, 18, 7, 6, 19]

#Font
count_font = pygame.font.Font("G1/assets/fonts/turok.ttf", 80)
score_font = pygame.font.Font("G1/assets/fonts/turok.ttf", 30)

#Text
def draw_text(text, font, text_col, x, y):
  img = font.render(text, True, text_col)
  s.blit(img, (x, y))

#Background
def draw_bg():
  scaled_bg = pygame.transform.scale(bg_image, (swidth, sheight))
  s.blit(scaled_bg, (0, 0))

#Health bars
red=(255, 0, 0)
yellow=(255, 255, 0)
white=(255, 255, 255)
def draw_health_bar(health, x, y):
  ratio = health / 100
  pygame.draw.rect(s, white, (x - 2, y - 2, 404, 34))
  pygame.draw.rect(s, red, (x, y, 400, 30))
  pygame.draw.rect(s, yellow, (x, y, 400 * ratio, 30))

#Player avatars
Knight=Characters(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
Assassin=Characters(2, 700, 310, True, Assassin_data, Assassin_sheet, Assassin_steps)

#game loop
run = True
while run:

  clock.tick(FPS)

  #Display background
  draw_bg()

  #Display health bar
  draw_health_bar(Knight.health, 20, 20)
  draw_health_bar(Assassin.health, 580, 20)
  draw_text("P1: " + str(score[0]), score_font, red, 20, 60)
  draw_text("P2: " + str(score[1]), score_font, red, 580, 60)

  #countdown
  if intro_count <= 0:
    #Move fighters
    Knight.move(swidth, sheight, s, Assassin, round_over)
    Assassin.move(swidth, sheight, s, Knight, round_over)
  else:

    #Display count timer
    draw_text(str(intro_count), count_font, red, swidth/2, sheight/3)

    #update count timer
    if (pygame.time.get_ticks()-last_count_update)>= 1000:
      intro_count -= 1
      last_count_update = pygame.time.get_ticks()

  #Update fighters
  Knight.update()
  Assassin.update()

  #Display fighters
  Knight.draw(s)
  Assassin.draw(s)

  #check for player defeat
  if round_over == False:
    if Knight.alive == False:
      score[1] += 1
      round_over = True
      round_over_time = pygame.time.get_ticks()
    elif Assassin.alive == False:
      score[0] += 1
      round_over = True
      round_over_time = pygame.time.get_ticks()
  else:
    #display victory image
    s.blit(victory_img, (360, 150))
    if pygame.time.get_ticks()-round_over_time>round_cooldown:
      round_over = False
      intro_count = 3
      Knight= Knight(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
      Assassin= Assassin(2, 700, 310, True, Assassin_data, Assassin_sheet, Assassin_steps)

  #event handler
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run = False

  #update display
  pygame.display.update()

#exit pygame
pygame.quit()`

My Module-

import pygame

class Characters():
  def __init__(self, player, x, y, flip, data, sheet, steps):
    self.player = player
    self.size = data[0]
    self.image_scale = data[1]
    self.offset = data[2]
    self.flip = flip
    self.animation_list = self.load_images(sheet, steps)
    self.action = 0#0:idle #1:run #2:jump #3:attack1 #4: attack2 #5:hit #6:death
    self.frame_index = 0
    self.image = self.animation_list[self.action][self.frame_index]
    self.update_time = pygame.time.get_ticks()
    self.rect = pygame.Rect((x, y, 80, 180))
    self.vel_y = 0
    self.running = False
    self.jump = False
    self.attacking = False
    self.attack_type = 0
    self.attack_cooldown = 0
    self.hit = False
    self.health = 100
    self.alive = True

  def load_images(self, sheet, steps):
    #extract images from spritesheet
    animation_list = []
    for y, animation in enumerate(steps):
      temp_img_list = []
      for x in range(animation):
        temp_img = sheet.subsurface(x * self.size, y * self.size, self.size, self.size)
        temp_img_list.append(pygame.transform.scale(temp_img, (self.size * self.image_scale, self.size * self.image_scale)))
      animation_list.append(temp_img_list)
    return animation_list

  def move(self, screen_width, screen_height, surface, target, round_over):
    SPEED = 10
    GRAVITY = 2
    dx = 0
    dy = 0
    self.running = False
    self.attack_type = 0

    #get keypresses
    key = pygame.key.get_pressed()

    #can only perform other actions if not currently attacking
    if self.attacking == False and self.alive == True and round_over == False:
      #check player 1 controls
      if self.player == 1:
        #movement
        if key[pygame.K_a]:
          dx = -SPEED
          self.running = True
        if key[pygame.K_d]:
          dx = SPEED
          self.running = True
        #jump
        if key[pygame.K_w] and self.jump == False:
          self.vel_y = -30
          self.jump = True
        #attack
        if key[pygame.K_r] or key[pygame.K_t]:
          self.attack(target)
          #determine which attack type was used
          if key[pygame.K_r]:
            self.attack_type = 1
          if key[pygame.K_t]:
            self.attack_type = 2

      #check player 2 controls
      if self.player == 2:
        #movement
        if key[pygame.K_LEFT]:
          dx = -SPEED
          self.running = True
        if key[pygame.K_RIGHT]:
          dx = SPEED
          self.running = True
        #jump
        if key[pygame.K_UP] and self.jump == False:
          self.vel_y = -30
          self.jump = True
        #attack
        if key[pygame.K_KP1] or key[pygame.K_KP2]:
          self.attack(target)
          #determine which attack type was used
          if key[pygame.K_KP1]:
            self.attack_type = 1
          if key[pygame.K_KP2]:
            self.attack_type = 2

    #apply gravity
    self.vel_y += GRAVITY
    dy += self.vel_y

    #ensure player stays on screen
    if self.rect.left + dx < 0:
      dx = -self.rect.left
    if self.rect.right + dx > screen_width:
      dx = screen_width - self.rect.right
    if self.rect.bottom + dy > screen_height - 220:
      self.vel_y = 0
      self.jump = False
      dy = screen_height - 220 - self.rect.bottom

    #ensure players face each other
    if target.rect.centerx > self.rect.centerx:
      self.flip = False
    else:
      self.flip = True

    #apply attack cooldown
    if self.attack_cooldown > 0:
      self.attack_cooldown -= 1

    #update player position
    self.rect.x += dx
    self.rect.y += dy

  #handle animation updates
  def update(self):
    #check what action the player is performing
    if self.health <= 0:
      self.health = 0
      self.alive = False
      self.update_action(6)#6:death
    elif self.hit == True:
      self.update_action(5)#5:hit
    elif self.attacking == True:
      if self.attack_type == 1:
        self.update_action(3)#3:attack1
      elif self.attack_type == 2:
        self.update_action(4)#4:attack2
    elif self.jump == True:
      self.update_action(2)#2:jump
    elif self.running == True:
      self.update_action(1)#1:run
    else:
      self.update_action(0)#0:idle

    animation_cooldown = 50
    #update image
    self.image = self.animation_list[self.action][self.frame_index]
    #check if enough time has passed since the last update
    if pygame.time.get_ticks() - self.update_time > animation_cooldown:
      self.frame_index += 1
      self.update_time = pygame.time.get_ticks()
    #check if the animation has finished
    if self.frame_index >= len(self.animation_list[self.action]):
      #if the player is dead then end the animation
      if self.alive == False:
        self.frame_index = len(self.animation_list[self.action]) - 1
      else:
        self.frame_index = 0
        #check if an attack was executed
        if self.action == 3 or self.action == 4:
          self.attacking = False
          self.attack_cooldown = 20
        #check if damage was taken
        if self.action == 5:
          self.hit = False
          #if the player was in the middle of an attack, then the attack is stopped
          self.attacking = False
          self.attack_cooldown = 20

  def attack(self, target):
    if self.attack_cooldown == 0:
      #execute attack
      self.attacking = True
      self.attack_sound.play()
      attacking_rect = pygame.Rect(self.rect.centerx - (2 * self.rect.width * self.flip), self.rect.y, 2 * self.rect.width, self.rect.height)
      if attacking_rect.colliderect(target.rect):
        target.health -= 10
        target.hit = True

  def update_action(self, new_action):
    #check if the new action is different to the previous one
    if new_action != self.action:
      self.action = new_action

      #update the animation settings
      self.frame_index = 0
      self.update_time = pygame.time.get_ticks()

  def draw(self, surface):
    img = pygame.transform.flip(self.image, self.flip, False)
    surface.blit(img, (self.rect.x - (self.offset[0] * self.image_scale), self.rect.y - (self.offset[1] * self.image_scale)))

The error occurred-

File "c:\Users\User\Desktop\G1\Battle game V1.py", line 73, in <module>
    Knight=Characters(1, 200, 310, False, Knight_data, Knight_sheet, Knight_steps)
  File "c:\Users\User\Desktop\G1\Players.py", line 10, in __init__
    self.animation_list = self.load_images(sheet, steps)
  File "c:\Users\User\Desktop\G1\Players.py", line 33, in load_images
    temp_img = sheet.subsurface(x * self.size, y * self.size, self.size, self.size)
ValueError: subsurface rectangle outside surface area


问:
GraphQL server response is very slow with a large number of types and interfaces
Env Details :

```<code>"@neo4j/graphql": "^3.12.0",
"@neo4j/introspector": "^1.0.2",
"apollo-server": "^3.11.1",
"dotenv": "^16.0.3",
"graphql": "^16.6.0",
"neo4j-driver": "^4.4.3"
 OS : Windows10
</code>```

We have 201 type definitions and 105 interface definitions in graphql file.
neo4j graphql generates SDL file of size around 26 MB ( around 8002 type def in SDL )

Problem is , a simple query takes around 10-15 minutes to get the response  and sometimes we don't even get the response.
Below is code snippet to start server

```<code>const server = new ApolloServer({
  schema: schema,
  introspection: true,
  playground: true,
});
</code>```

However, if we work with a smaller number(~20-25) of type definitions then it works as expected.

Is there any size limit or restriction on the number of type definitions in graphql?

Body:
Env Details :

"@neo4j/graphql": "^3.12.0",
"@neo4j/introspector": "^1.0.2",
"apollo-server": "^3.11.1",
"dotenv": "^16.0.3",
"graphql": "^16.6.0",
"neo4j-driver": "^4.4.3"
 OS : Windows10

We have 201 type definitions and 105 interface definitions in graphql file.
neo4j graphql generates SDL file of size around 26 MB ( around 8002 type def in SDL )

Problem is , a simple query takes around 10-15 minutes to get the response  and sometimes we don't even get the response.
Below is code snippet to start server

const server = new ApolloServer({
  schema: schema,
  introspection: true,
  playground: true,
});

However, if we work with a smaller number(~20-25) of type definitions then it works as expected.

Is there any size limit or restriction on the number of type definitions in graphql?


问:
Heuristic Value Function
I am writing the code for sliding puzzle game, and the template that my teacher gave me has an if statement for timeout. the code runs but it gets stuck for the 3 final strings. I figured that what changes everything is the Heuristic value function but I don't know how to make it better so I wont have the timeout problem. Please help.

```<code>public class Main {
    public static void main(String[] args) {
        String[] boards = {"0 1",
                            "1 0",
                            "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40",
                            "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 35 26 27 28 29 30 31 32 33 34 25 36 37 38 39 40",
                           "7 5 4|0 3 2|8 1 6",
                           "7 5 4|0 3 2|8 6 1",
                           "6 4 7|8 5 0|3 2 1",
                           "6 7 5 1|2 10 4 11|9 3 8 0",
                           "1 6 4 15|5 10 0 13|9 11 3 7|12 8 2 14",
                           "1 9 0 12 10 5 6|8 11 2 3 4 13 7",
                           "1 2 3 12 5 6|7 8 9 4 11 17|13 14 15 0 10 16",
                           "29 7 14 9 11 16|23 17 24 22 18 20|5 3 21 13 27 15|6 4 12 1 19 28|26 10 8 25 2 0",
                           "2 3 8 4 14 13 6|16 9 17 0 10 5 7|1 11 15 18 12 19 20",
                           "1 2 23 5 21 14 7 6 16|10 11 3 22 15 35 9 34 0|28 20 13 31 4 33 26 17 8|29 19 12 32 30 24 18 27 25"};
        int successCounter = 0;
        for (String boardString : boards) {
            boolean success = searchOnce(boardString);
            if (success) {
                successCounter++;
            }
        }
        System.out.println("Able to solve " + successCounter + " ot of " + boards.length + " games.");
    }

    private static boolean searchOnce(String boardString) {
        Search search = new Search();
        Thread t = new Thread(() -> search.search(boardString));
        t.start();
        try {
            t.join(60000);
        } catch (InterruptedException ex) {
        }
        boolean succeeded = false;
        if (t.isAlive()) {
            t.stop();
            System.out.println("Timout occurred...");
        } else {
            int status = search.getStatus();
            switch (status) {
                case Search.SOLVED:
                    System.out.println("Solution length: " + search.getResult().size());
                    System.out.println(search.getResult());
                    succeeded = true;
                    break;
                case Search.UNSOLVABLE:
                    System.out.println("Unsolvable game...");
                    break;
                case Search.OUT_OF_MEMORY:
                    System.out.println("Out of memory while searching...");
                    break;
            }
        }
        System.out.println("Number of expanded nodes: " + search.getExpandedNodes());
        System.out.println("----------------------------------------------------------------------");
        return succeeded;
    }
}

</code>```

and this is the heuristic value function:

```<code>public int heuristicValue(){
    int distance = 0;
    int rowNum = currentState.getBoard().getRowNum();
    int colNum = currentState.getBoard().getColNum();

    for(int i=0; i<rowNum; i++){
        for(int j=0; j<colNum; j++){
            int piece = currentState.getBoard().getTiles()[i][j].getValue();
            if(piece != 0){
                int goalRow = (piece - 1)/rowNum;
                int goalCol = (piece -1)%colNum;
                distance += Math.abs(i-goalRow) + Math.abs(j-goalCol);
            }
        }
    }
    return distance;
}
</code>```

Title: Heuristic Value Function

Body:
I am writing the code for sliding puzzle game, and the template that my teacher gave me has an if statement for timeout. the code runs but it gets stuck for the 3 final strings. I figured that what changes everything is the Heuristic value function but I don't know how to make it better so I wont have the timeout problem. Please help.

public class Main {
    public static void main(String[] args) {
        String[] boards = {"0 1",
                            "1 0",
                            "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40",
                            "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 35 26 27 28 29 30 31 32 33 34 25 36 37 38 39 40",
                           "7 5 4|0 3 2|8 1 6",
                           "7 5 4|0 3 2|8 6 1",
                           "6 4 7|8 5 0|3 2 1",
                           "6 7 5 1|2 10 4 11|9 3 8 0",
                           "1 6 4 15|5 10 0 13|9 11 3 7|12 8 2 14",
                           "1 9 0 12 10 5 6|8 11 2 3 4 13 7",
                           "1 2 3 12 5 6|7 8 9 4 11 17|13 14 15 0 10 16",
                           "29 7 14 9 11 16|23 17 24 22 18 20|5 3 21 13 27 15|6 4 12 1 19 28|26 10 8 25 2 0",
                           "2 3 8 4 14 13 6|16 9 17 0 10 5 7|1 11 15 18 12 19 20",
                           "1 2 23 5 21 14 7 6 16|10 11 3 22 15 35 9 34 0|28 20 13 31 4 33 26 17 8|29 19 12 32 30 24 18 27 25"};
        int successCounter = 0;
        for (String boardString : boards) {
            boolean success = searchOnce(boardString);
            if (success) {
                successCounter++;
            }
        }
        System.out.println("Able to solve " + successCounter + " ot of " + boards.length + " games.");
    }

    private static boolean searchOnce(String boardString) {
        Search search = new Search();
        Thread t = new Thread(() -> search.search(boardString));
        t.start();
        try {
            t.join(60000);
        } catch (InterruptedException ex) {
        }
        boolean succeeded = false;
        if (t.isAlive()) {
            t.stop();
            System.out.println("Timout occurred...");
        } else {
            int status = search.getStatus();
            switch (status) {
                case Search.SOLVED:
                    System.out.println("Solution length: " + search.getResult().size());
                    System.out.println(search.getResult());
                    succeeded = true;
                    break;
                case Search.UNSOLVABLE:
                    System.out.println("Unsolvable game...");
                    break;
                case Search.OUT_OF_MEMORY:
                    System.out.println("Out of memory while searching...");
                    break;
            }
        }
        System.out.println("Number of expanded nodes: " + search.getExpandedNodes());
        System.out.println("----------------------------------------------------------------------");
        return succeeded;
    }
}

and this is the heuristic value function:

public int heuristicValue(){
    int distance = 0;
    int rowNum = currentState.getBoard().getRowNum();
    int colNum = currentState.getBoard().getColNum();

    for(int i=0; i<rowNum; i++){
        for(int j=0; j<colNum; j++){
            int piece = currentState.getBoard().getTiles()[i][j].getValue();
            if(piece != 0){
                int goalRow = (piece - 1)/rowNum;
                int goalCol = (piece -1)%colNum;
                distance += Math.abs(i-goalRow) + Math.abs(j-goalCol);
            }
        }
    }
    return distance;
}