问:
How to perform count and select in a single query?
So in a blog application I am building, I have two tables:

```<code>// Post model
type Post struct {
   Id      int    `json:"id" gorm:"primaryKey"`
   OwnerId int    `json:"owner_id" // foreign key to User model
   Title   string `json:"title"`
   Body    string `json:"body"`
   Likes   []Like `json:"likes"`
}
</code>```
```<code>// Like model
type Like struct {
   PostId  int `json:"post_id"`  // foreign key to Post model
   LikerId int `json:"liker_id"` // foreign key to User model
}
</code>```

I want to run a query which gets posts made by a user as well as whether the current user liked the post(s) and the total number of likes on each post. I'd like to do all of this in a single query because splitting this into multiple queries will be bad for performance when a user has multiple posts which is most likely the case.

I constructed this query but I get an incorrect syntax error which I totally expected:

```<code>SELECT post.title, post.body, COUNT(likes), lk.liker_id
FROM posts as post
LEFT JOIN likes
ON post.owner_id = "..." AND likes.post_id = post.id
LEFT JOIN likes as lk
ON lk.post_id = post.id AND lk.liker_id = "current_user_id"
</code>```

How could I accomplish this? Thank you!

EDIT: here are the SHOW CREATE TABLE for the posts and likes models:

```<code>mysql> SHOW CREATE TABLE posts;
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| posts | CREATE TABLE `posts` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `owner_id` bigint DEFAULT NULL,
  `title` longtext,
  `body` longtext,
  PRIMARY KEY (`id`),
  KEY `fk_users_posts` (`owner_id`),
  CONSTRAINT `fk_users_posts` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
</code>```
```<code>mysql> SHOW CREATE TABLE likes;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| likes | CREATE TABLE `likes` (
  `post_id` bigint DEFAULT NULL,
  `liker_id` bigint DEFAULT NULL,
  KEY `fk_likes_liker` (`liker_id`),
  KEY `fk_posts_likes` (`post_id`),
  CONSTRAINT `fk_likes_liker` FOREIGN KEY (`liker_id`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_posts_likes` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
</code>```

Body:
So in a blog application I am building, I have two tables:

// Post model
type Post struct {
   Id      int    `json:"id" gorm:"primaryKey"`
   OwnerId int    `json:"owner_id" // foreign key to User model
   Title   string `json:"title"`
   Body    string `json:"body"`
   Likes   []Like `json:"likes"`
}

// Like model
type Like struct {
   PostId  int `json:"post_id"`  // foreign key to Post model
   LikerId int `json:"liker_id"` // foreign key to User model
}

I want to run a query which gets posts made by a user as well as whether the current user liked the post(s) and the total number of likes on each post. I'd like to do all of this in a single query because splitting this into multiple queries will be bad for performance when a user has multiple posts which is most likely the case.

I constructed this query but I get an incorrect syntax error which I totally expected:

SELECT post.title, post.body, COUNT(likes), lk.liker_id
FROM posts as post
LEFT JOIN likes
ON post.owner_id = "..." AND likes.post_id = post.id
LEFT JOIN likes as lk
ON lk.post_id = post.id AND lk.liker_id = "current_user_id"

How could I accomplish this? Thank you!

EDIT: here are the SHOW CREATE TABLE for the posts and likes models:

mysql> SHOW CREATE TABLE posts;
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| posts | CREATE TABLE `posts` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `owner_id` bigint DEFAULT NULL,
  `title` longtext,
  `body` longtext,
  PRIMARY KEY (`id`),
  KEY `fk_users_posts` (`owner_id`),
  CONSTRAINT `fk_users_posts` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW CREATE TABLE likes;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| likes | CREATE TABLE `likes` (
  `post_id` bigint DEFAULT NULL,
  `liker_id` bigint DEFAULT NULL,
  KEY `fk_likes_liker` (`liker_id`),
  KEY `fk_posts_likes` (`post_id`),
  CONSTRAINT `fk_likes_liker` FOREIGN KEY (`liker_id`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_posts_likes` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)


来源: stackexchange

问:
How swap tokens in smart contract with PancakeRouter
I have this code to swap tokens in BSC testnet, but it fails.(https://testnet.bscscan.com/tx/0xe3eaedf680eaba297579984de3d84da78aeb47bdf31a85b4e9ad04b919096aca) What i'm doing wrong?
`

```<code>contract tokenSwap {
    //  address private constant WBNB = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;

    address private constant FGD = 0xB86a03eF847d462E40D853c015260C55Cfac9DAD;
    address private constant FACTORY = 0xB7926C0430Afb07AA7DEfDE6DA862aE0Bde767bc;
    address private constant admin = 0x567A623433D503183Fb383493FdB12A4780e2F60;
    address private constant BUSD = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
    address private constant DAI = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
    address private constant cake = 0xF9f93cF501BFaDB6494589Cb4b4C15dE49E85D0e;
    address private owner;
    address private constant Pancakeswap_V2_ROUTER = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;
    address private constant WETH = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;
    function swap_first( address _tokenOut, uint256 _amountIn, uint256 _amountOutMin) external {

    address _tokenIn = WETH;
    IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);

    IERC20(_tokenIn).approve(Pancakeswap_V2_ROUTER, _amountIn);

    address[] memory path;
    if (_tokenIn == WETH || _tokenOut == WETH) {
      path = new address[](2);
      path[0] = _tokenIn;
      path[1] = _tokenOut;
    } else {
      path = new address[](3);
      path[0] = _tokenIn;
      path[1] = WETH;
      path[2] = _tokenOut;
    }
        IPancakeswapV2Router(Pancakeswap_V2_ROUTER).swapExactTokensForTokens(_amountIn, _amountOutMin, path, address(this), block.timestamp);
    }
</code>```

`

I want swap WBNB to another token

ContentLicense: CC BY-SA 4.0

Body:
I have this code to swap tokens in BSC testnet, but it fails.(https://testnet.bscscan.com/tx/0xe3eaedf680eaba297579984de3d84da78aeb47bdf31a85b4e9ad04b919096aca) What i'm doing wrong?
`

contract tokenSwap {
    //  address private constant WBNB = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;

    address private constant FGD = 0xB86a03eF847d462E40D853c015260C55Cfac9DAD;
    address private constant FACTORY = 0xB7926C0430Afb07AA7DEfDE6DA862aE0Bde767bc;
    address private constant admin = 0x567A623433D503183Fb383493FdB12A4780e2F60;
    address private constant BUSD = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
    address private constant DAI = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
    address private constant cake = 0xF9f93cF501BFaDB6494589Cb4b4C15dE49E85D0e;
    address private owner;
    address private constant Pancakeswap_V2_ROUTER = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3;
    address private constant WETH = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;
    function swap_first( address _tokenOut, uint256 _amountIn, uint256 _amountOutMin) external {

    address _tokenIn = WETH;
    IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);

    IERC20(_tokenIn).approve(Pancakeswap_V2_ROUTER, _amountIn);

    address[] memory path;
    if (_tokenIn == WETH || _tokenOut == WETH) {
      path = new address[](2);
      path[0] = _tokenIn;
      path[1] = _tokenOut;
    } else {
      path = new address[](3);
      path[0] = _tokenIn;
      path[1] = WETH;
      path[2] = _tokenOut;
    }
        IPancakeswapV2Router(Pancakeswap_V2_ROUTER).swapExactTokensForTokens(_amountIn, _amountOutMin, path, address(this), block.timestamp);
    }

`

I want swap WBNB to another token


问:
why can does my code not find the element when it loops?
Everytime i run this bit of code it only manages to run once, once it goes to run the second time i get an error message saying that it cannot find the element from line 19. I've tried using the full xpath and the shorter xpath but nothing seems to work. can anyone help me? this is for a work project of mine. i've change the URL of the survey for privacy :)

```<code>from selenium import webdriver
import time

survey = webdriver.Chrome()

survey.get('https://www.surveygizmo.eu/s3/90221786/&sglocale=en')

feedback = open('/Users/xxxxxxxx/Desktop/ResponseVerbatim.txt', "r")

Response = feedback.readline()

while Response:
    # Enter the text into the survey form
    verbatim = survey.find_element("xpath", '/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea')
    verbatim.send_keys(Response)

    # Click the "Next" button
    submit = survey.find_element("xpath", '//*[@id="sg_NextButton"]')
    submit.click()

    # Wait for the next page to load
    time.sleep(5)

    # Select the satisfaction level
    satisfaction = survey.find_element("xpath", '//*[@id="sgE-90221786-35-77-10397-handle"]')
    satisfaction.click()

    # Click the "Next" button
    submit3 = survey.find_element("xpath", '//*[@id="sg_NextButton"]')
    submit3.click()

    # Read the next line of text from the file
    Response = feedback.readline()

feedback.close()
</code>```

I've made a similar programme before and it had no issue. The programme is meant to open and read the text file and submit the responses from the text file, line by line, until all the lines have been submitted. The issue I'm having is after the first response has been submitted, i get an error message saying "no such element unable to locate element" for line 19.

Ive tried using the long xpath and the short xpath to see if that makes a difference but it doesn't seem to.

```<code>Traceback (most recent call last):
  File "/Users/xxxxxxxx/PycharmProjects/seleniumpython/main.py", line 19, in <module>
    verbatim = survey.find_element("xpath", '/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea')
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 861, in find_element
    return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea"}
  (Session info: chrome=108.0.5359.124)
</code>```

Body:
Everytime i run this bit of code it only manages to run once, once it goes to run the second time i get an error message saying that it cannot find the element from line 19. I've tried using the full xpath and the shorter xpath but nothing seems to work. can anyone help me? this is for a work project of mine. i've change the URL of the survey for privacy :)

from selenium import webdriver
import time

survey = webdriver.Chrome()

survey.get('https://www.surveygizmo.eu/s3/90221786/&sglocale=en')

feedback = open('/Users/xxxxxxxx/Desktop/ResponseVerbatim.txt', "r")

Response = feedback.readline()

while Response:
    # Enter the text into the survey form
    verbatim = survey.find_element("xpath", '/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea')
    verbatim.send_keys(Response)

    # Click the "Next" button
    submit = survey.find_element("xpath", '//*[@id="sg_NextButton"]')
    submit.click()

    # Wait for the next page to load
    time.sleep(5)

    # Select the satisfaction level
    satisfaction = survey.find_element("xpath", '//*[@id="sgE-90221786-35-77-10397-handle"]')
    satisfaction.click()

    # Click the "Next" button
    submit3 = survey.find_element("xpath", '//*[@id="sg_NextButton"]')
    submit3.click()

    # Read the next line of text from the file
    Response = feedback.readline()

feedback.close()

I've made a similar programme before and it had no issue. The programme is meant to open and read the text file and submit the responses from the text file, line by line, until all the lines have been submitted. The issue I'm having is after the first response has been submitted, i get an error message saying "no such element unable to locate element" for line 19.

Ive tried using the long xpath and the short xpath to see if that makes a difference but it doesn't seem to.

Traceback (most recent call last):
  File "/Users/xxxxxxxx/PycharmProjects/seleniumpython/main.py", line 19, in <module>
    verbatim = survey.find_element("xpath", '/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea')
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 861, in find_element
    return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "/Users/xxxxxxx/PycharmProjects/seleniumpython/venv/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/form/div[2]/div[2]/div[2]/div[2]/div[2]/textarea"}
  (Session info: chrome=108.0.5359.124)


问:
Pytorch LSTM Dimensions with Reinforcement Learning
Bit of a noob at posting here, hoping everything is formatted correctly.

I'm a little confused on how to make my states 3d tensors for my LSTM Neural Network in my reinforcement learning problem.  I got the model to sucessfully run with standard dense layers but I want to see how LSTM/GRU layers affect the performance.  I've tried following some advice online and I'm just alternating errors at this point.

I'm trying to make a DRL agent that learns how to trade using various trading indicators. I'm not trying to make money from this or deploy anything, I just thought this would be an interesting project to improve my skills and is an extension of the final project of a class I recently completed.

I'm currently only using 5 features and my mess of a code after trying to solve this error looks like this:

```<code>

s = env.reset() # Comes from typical gym environment
# s looks like [-5.95787098e-04  7.52228298e-01  5.97709036e+01 0.00000000e+00
#  0.00000000e+00] <class 'numpy.ndarray'>
a, pi_a = model.select_action(torch.from_numpy(s).float().to(device))

class PPO_discrete(object):
    def __init__(
    hidden_size=200,
    action_dim,
    state_dim,
    lr=1e-4
    ):
    self.actor = Actor(state_dim, action_dim, hidden_size).to(device)
    self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),
    lr=lr)
# Removed a bunch of stuff not related to the question

    def select_action(self, state):
        '''Stochastic Policy'''
        with torch.no_grad():
            pi = self.actor.pi(state, softmax_dim=0)
            m = Categorical(pi)
            a = m.sample().item()
            pi_a = pi[a].item()
        return a, pi_a

class Actor(nn.Module):
    def __init__(self, state_dim, action_dim, hidden_size):
        super(Actor, self).__init__()
        self.num_layers = 1
        self.hidden_size = hidden_size
        self.l1 = nn.LSTM(state_dim, hidden_size,self.num_layers,batch_first = True)
        self.fc1 = nn.Linear(hidden_size, action_dim)
        self.relu = nn.ReLU()

    def forward(self, state):
        h_0 = Variable(torch.zeros(self.num_layers, state.size(0), self.net_width))
        c_0 = Variable(torch.zeros(self.num_layers, state.size(0), self.net_width))

        output, (hn,cn) = self.l1(state,(h_0,c_0))
        hn = hn.view(-1,self.net_width)
        out = self.relu(hn)
        out = self.fc1(out)
        return out

    def pi(self, state, softmax_dim = 0):
        n = self.forward(state)
        prob = F.softmax(self.l3(n), dim=softmax_dim)
        return prob

</code>```

The error I'm currently getting is:
RuntimeError: For unbatched 2-D input, hx and cx should also be 2-D but got (3-D, 3-D) tensors

After using torch.from_numpy(s). s has type and torch.Size of:
<class 'torch.Tensor'> torch.Size([5])

Any help would be greatly appreciated!  Struggling to wrap my head around LSTM and 3d tensors during reinforcement learning.

Body:
Bit of a noob at posting here, hoping everything is formatted correctly.

I'm a little confused on how to make my states 3d tensors for my LSTM Neural Network in my reinforcement learning problem.  I got the model to sucessfully run with standard dense layers but I want to see how LSTM/GRU layers affect the performance.  I've tried following some advice online and I'm just alternating errors at this point.

I'm trying to make a DRL agent that learns how to trade using various trading indicators. I'm not trying to make money from this or deploy anything, I just thought this would be an interesting project to improve my skills and is an extension of the final project of a class I recently completed.

I'm currently only using 5 features and my mess of a code after trying to solve this error looks like this:

s = env.reset() # Comes from typical gym environment
# s looks like [-5.95787098e-04  7.52228298e-01  5.97709036e+01 0.00000000e+00
#  0.00000000e+00] <class 'numpy.ndarray'>
a, pi_a = model.select_action(torch.from_numpy(s).float().to(device))

class PPO_discrete(object):
    def __init__(
    hidden_size=200,
    action_dim,
    state_dim,
    lr=1e-4
    ):
    self.actor = Actor(state_dim, action_dim, hidden_size).to(device)
    self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),
    lr=lr)
# Removed a bunch of stuff not related to the question

    def select_action(self, state):
        '''Stochastic Policy'''
        with torch.no_grad():
            pi = self.actor.pi(state, softmax_dim=0)
            m = Categorical(pi)
            a = m.sample().item()
            pi_a = pi[a].item()
        return a, pi_a

class Actor(nn.Module):
    def __init__(self, state_dim, action_dim, hidden_size):
        super(Actor, self).__init__()
        self.num_layers = 1
        self.hidden_size = hidden_size
        self.l1 = nn.LSTM(state_dim, hidden_size,self.num_layers,batch_first = True)
        self.fc1 = nn.Linear(hidden_size, action_dim)
        self.relu = nn.ReLU()

    def forward(self, state):
        h_0 = Variable(torch.zeros(self.num_layers, state.size(0), self.net_width))
        c_0 = Variable(torch.zeros(self.num_layers, state.size(0), self.net_width))

        output, (hn,cn) = self.l1(state,(h_0,c_0))
        hn = hn.view(-1,self.net_width)
        out = self.relu(hn)
        out = self.fc1(out)
        return out

    def pi(self, state, softmax_dim = 0):
        n = self.forward(state)
        prob = F.softmax(self.l3(n), dim=softmax_dim)
        return prob

The error I'm currently getting is:
RuntimeError: For unbatched 2-D input, hx and cx should also be 2-D but got (3-D, 3-D) tensors

After using torch.from_numpy(s). s has type and torch.Size of:
<class 'torch.Tensor'> torch.Size([5])

Any help would be greatly appreciated!  Struggling to wrap my head around LSTM and 3d tensors during reinforcement learning.


问:
Moving pdf files to a specific directory
I am using ubuntu.  I have about 500 directories in the current working directory.  I want to transfer any pdf files that exist in these directories to a specific location.  What can I do?

Have been copying from the Caja but this is very time consuming.

I have been using rsync to transfer whole directory trees.


问:
Why can't I see the tag information in the print?
How can I get the data from the following tag:

```<code><a class="sc-bdVaJa ebNrSm" href="/inmueble/venta-apartamento-bogota-puente-largo-2-habitaciones-2-banos-2-garajes/14221-M3963321" target="_blank" data-gtm-productname="Apartamento en Venta, Puente Largo, Bogotá D.C." data-gtm-productsku="14221-M3963321" data-gtm-productprice="457000000" data-gtm-productcategory="venta - Apartamento" data-gtm-city="Bogotá D.C." data-gtm-zone="Noroccidente" data-gtm-neighborhood="PUENTE LARGO" data-gtm-businesstype="venta" data-gtm-propertytype="Apartamento" data-gtm-projectname="Ocasional" data-gtm-position="1"\><h2 class="sc-dxgOiQ BSoGx card-title"\><div\>Apartamento en Venta, Puente Largo, Bogotá D.C.</div\></h2\></a\>
</code>```

i try:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://www.metrocuadrado.com/apartamento/venta/bogota/?search=form'
page = requests.get(url)

soup = BeautifulSoup(page.content, 'lxml')

projects = soup.find('a', class_='sc-bdVaJa ebNrSm')
print(projects.text)
</code>```

but, i get error:
AttributeError: 'NoneType' object has no attribute 'text'

Body:
How can I get the data from the following tag:

<a class="sc-bdVaJa ebNrSm" href="/inmueble/venta-apartamento-bogota-puente-largo-2-habitaciones-2-banos-2-garajes/14221-M3963321" target="_blank" data-gtm-productname="Apartamento en Venta, Puente Largo, Bogotá D.C." data-gtm-productsku="14221-M3963321" data-gtm-productprice="457000000" data-gtm-productcategory="venta - Apartamento" data-gtm-city="Bogotá D.C." data-gtm-zone="Noroccidente" data-gtm-neighborhood="PUENTE LARGO" data-gtm-businesstype="venta" data-gtm-propertytype="Apartamento" data-gtm-projectname="Ocasional" data-gtm-position="1"\>

Apartamento en Venta, Puente Largo, Bogotá D.C.

i try:

import requests
from bs4 import BeautifulSoup

url = 'https://www.metrocuadrado.com/apartamento/venta/bogota/?search=form'
page = requests.get(url)

soup = BeautifulSoup(page.content, 'lxml')

projects = soup.find('a', class_='sc-bdVaJa ebNrSm')
print(projects.text)

but, i get error:
AttributeError: 'NoneType' object has no attribute 'text'


问:
How to resolve javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake exception
I am working on java 7 with TestNG rest assured framework and testing some server calls. Lately faced some exception while running my test. It is ignoring my test and throw below exception javax.net.ssl.SSLHandshakeException:Remote host terminated the handshake.
I have tried to insert server certificate into java charsets, but it did not help at all.
Also provided TLSv1.3,TLSv1.2 to a protocol still not seeing results. What would be the possible causes and how to fix it? Thanks in advance!

Understand the root of the problem and resolve it.


问:
Implement StepListener from thucydides
I am trying to implement StepListener interface from net.thucydides.core.steps where I need to implement the methods:

```<code>@Override
public void testSuiteStarted(Class<?> storyClass) {}
</code>```
```<code>@Override
public void testSuiteFinished() {}
</code>```

How can I send those events in a correct JSON format?

Title: Implement StepListener from thucydides

Body:
I am trying to implement StepListener interface from net.thucydides.core.steps where I need to implement the methods:

@Override
public void testSuiteStarted(Class<?> storyClass) {}

@Override
public void testSuiteFinished() {}

How can I send those events in a correct JSON format?


问:
How can I convert a pandas df from tickdata to ohlcv data?
Hello I am relative new in this space, I want to format my df from tickdata to ohlcv for me it looks good what I'm doing and don't know why I get this error or what can I do to solve this error</p>
```<code>                              symbol  side   size    price  ...                            trdMatchID    grossValue  homeNotional  foreignNotional
timestamp                                                     ...
2022-12-31 00:00:01.436100096  BTCUSDT  Sell  0.001  16620.5  ...  96118c0a-caad-5aae-902d-2c7a2f2b50e8  1.662050e+09         0.001          16.6205
2022-12-31 00:00:01.453900032  BTCUSDT  Sell  0.001  16620.5  ...  1cc6a59b-764a-5aa2-b784-2e3d17df65ca  1.662050e+09         0.001          16.6205
2022-12-31 00:00:01.668999936  BTCUSDT  Sell  0.250  16620.5  ...  a5e005fa-ac11-5cdd-b4b6-1d2d13d0c832  4.155125e+11         0.250        4155.1250
2022-12-31 00:00:02.475899904  BTCUSDT  Sell  0.004  16620.5  ...  0d16dbd7-7569-513a-b52c-4d22c4322c1b  6.648200e+09         0.004          66.4820
2022-12-31 00:00:03.699500032  BTCUSDT  Sell  0.142  16620.5  ...  6fe23531-ecd4-5910-8490-7400acaf0ab5  2.360111e+11         0.142        2360.1110
</code>```
```<code>resample_LTP = df['price'].resample('15Min').ohlc(_method='ohlc')

resample_LTQ = df['size'].resample('15Min').sum()
resample_data = pd.concat([resample_LTP, resample_LTQ], axis=1,)
df = resample_data
</code>```
```<code>MY ERROR:
</code>```
```<code>Traceback (most recent call last):
  File "/Users/anon/PycharmProjects/MachineLearning/test.py", line 14, in <module>
    resample_LTP = df_head['price'].resample('15Min').ohlc(_method='ohlc')
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pandas/core/resample.py", line 1148, in f
    nv.validate_resampler_func(name, args, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pandas/compat/numpy/function.py", line 413, in validate_resampler_func
    raise TypeError("too many arguments passed in")
TypeError: too many arguments passed in
</code>```
```<code>

I thought my venv is broken and installed everything new but it doesn't helped
</code>```

Body:
Hello I am relative new in this space, I want to format my df from tickdata to ohlcv for me it looks good what I'm doing and don't know why I get this error or what can I do to solve this error

                              symbol  side   size    price  ...                            trdMatchID    grossValue  homeNotional  foreignNotional
timestamp                                                     ...
2022-12-31 00:00:01.436100096  BTCUSDT  Sell  0.001  16620.5  ...  96118c0a-caad-5aae-902d-2c7a2f2b50e8  1.662050e+09         0.001          16.6205
2022-12-31 00:00:01.453900032  BTCUSDT  Sell  0.001  16620.5  ...  1cc6a59b-764a-5aa2-b784-2e3d17df65ca  1.662050e+09         0.001          16.6205
2022-12-31 00:00:01.668999936  BTCUSDT  Sell  0.250  16620.5  ...  a5e005fa-ac11-5cdd-b4b6-1d2d13d0c832  4.155125e+11         0.250        4155.1250
2022-12-31 00:00:02.475899904  BTCUSDT  Sell  0.004  16620.5  ...  0d16dbd7-7569-513a-b52c-4d22c4322c1b  6.648200e+09         0.004          66.4820
2022-12-31 00:00:03.699500032  BTCUSDT  Sell  0.142  16620.5  ...  6fe23531-ecd4-5910-8490-7400acaf0ab5  2.360111e+11         0.142        2360.1110

resample_LTP = df['price'].resample('15Min').ohlc(_method='ohlc')

resample_LTQ = df['size'].resample('15Min').sum()
resample_data = pd.concat([resample_LTP, resample_LTQ], axis=1,)
df = resample_data

MY ERROR:

Traceback (most recent call last):
  File "/Users/anon/PycharmProjects/MachineLearning/test.py", line 14, in <module>
    resample_LTP = df_head['price'].resample('15Min').ohlc(_method='ohlc')
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pandas/core/resample.py", line 1148, in f
    nv.validate_resampler_func(name, args, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pandas/compat/numpy/function.py", line 413, in validate_resampler_func
    raise TypeError("too many arguments passed in")
TypeError: too many arguments passed in

I thought my venv is broken and installed everything new but it doesn't helped


问:
Getting a return value in a closure
I am still struggling with this issue across many programs.  I have a closure that I need a value back from but as it is with async, it's not waiting for the value and therefore the calling method is erroring because it has the wrong bool.

Here is an example:

```<code>    func requestNotificationAuthorization() -> Bool {
        var retVal: Bool = false
        let authOptions = UNAuthorizationOptions.init(arrayLiteral: .alert, .badge, .sound)
        self.userNotificationCenter.requestAuthorization(options: authOptions) { (success, error) in
            if let error = error {
                retVal = false
                print(error.localizedDescription)
            } else {
                retVal = true
            }
        }
        return retVal
    }
</code>```

I need to know if the user has in fact authorized notifications but during the initial call, it will always return false or true if I set the value to an initial true.  Now, it will come back with a value at some point but the code that reads it has already been processed.

There has to be a way to do this that I just haven't found yet.  I am not looking for a workaround but an actual solution.  Any help in pointing me in the correct direction would be greatly appreciated.

Title: Getting a return value in a closure

Body:
I am still struggling with this issue across many programs.  I have a closure that I need a value back from but as it is with async, it's not waiting for the value and therefore the calling method is erroring because it has the wrong bool.

Here is an example:

    func requestNotificationAuthorization() -> Bool {
        var retVal: Bool = false
        let authOptions = UNAuthorizationOptions.init(arrayLiteral: .alert, .badge, .sound)
        self.userNotificationCenter.requestAuthorization(options: authOptions) { (success, error) in
            if let error = error {
                retVal = false
                print(error.localizedDescription)
            } else {
                retVal = true
            }
        }
        return retVal
    }

I need to know if the user has in fact authorized notifications but during the initial call, it will always return false or true if I set the value to an initial true.  Now, it will come back with a value at some point but the code that reads it has already been processed.

There has to be a way to do this that I just haven't found yet.  I am not looking for a workaround but an actual solution.  Any help in pointing me in the correct direction would be greatly appreciated.


问:
Coloring an AVL tree into a red-black tree with maximum black nodes
What is an algorithm to color an AVL tree into a red-black tree using a maximal number of black nodes (or minimal number of red nodes)?

I was given this problem for a homework problem (color the nodes of an AVL tree to produce a valid red-black tree), and it gave me a thought: when I tried to write an algorithm for this, I tried to write an algorithm which colored as many of the nodes as possible black (e.g. given a perfect binary search tree, all nodes would be black), while the easiest solution (and the one given in the linked question) seems to give red-black trees with either minimal or near-minimal black depth (e.g. given a perfect binary search tree, layers would alternate between red and black). Coloring the most nodes black seemed to be a much harder problem, and while I have a partial solution written in a Java-like language, it is not correct.

```<code>// Helper to recursively color both children of a node; calls to
// colorAVLChildren do not on their own contribute to recursion
// depth, only the calls which they themselves make to colorAVL.
void colorAVLChildren(Node root) {
    if (root != nil) {
        colorAVL(root.left);
        colorAVL(root.right);
    }
}

void colorAVL(Node root) {
    if (root == nil) {
        return;
    }

    root.color = BLACK;

    // All nil nodes are already black, so regardless of the results
    // of the conditionals, the same effect will overall be had on the
    // coloring of the tree.
    if (root.left != nil) {
        root.left.color = BLACK;
    }
    if (root.right != nil) {
        root.right.color = BLACK;
    }

    if (root.isBalanced()) {
        colorAVLChildren(root.left);
        colorAVLChildren(root.right);
    } else {
        if (root.tallestChild().tallestChild() == nil) {
            root.tallestChild().color = RED;

            return;
        }

        // At least the taller of the tallest child's two children is
        // too tall for the next level of the recursion (i.e., would
        // be taller than other trees at that level, thus violating
        // its invariants); however, it is of the correct black-depth.
        // Therefore, it must be red so that its children are at the
        // correct black-depth, but must not be passed as an argument
        // to colorAVL.
        root.tallestChild().tallestChild().color = RED;

        // This part is incorrect if root.tallestChild().tallestChild() is not balanced
        colorAVLChildren(root.tallestChild().tallestChild());

        // If this tallest child is balanced, treat both of its
        // children the same; otherwise, don't color the shorter of
        // its children at this level of recursion, instead leaving it
        // to the next level to preserve the one-to-one correspondence
        // between tree height and recursion level.
        if (root.tallestChild().isBalanced()) {
            root.tallestChild().shortestChild().color = RED;
            // This part is incorrect if root.tallestChild().shortestChild() is not balanced
            colorAVLChildren(root.tallestChild().shortestChild());
        } else {
            colorAVL(root.tallestChild().shortestChild());
        }

        // The next level in this recursion is the level of the
        // shorter of the two children (as this is the only level
        // which both children are guaranteed to possess); therefore,
        // this shorter child must be colored at the next level of
        // recursion.
        colorAVL(root.shortestChild());
    }
}
</code>```

Body:
What is an algorithm to color an AVL tree into a red-black tree using a maximal number of black nodes (or minimal number of red nodes)?

I was given this problem for a homework problem (color the nodes of an AVL tree to produce a valid red-black tree), and it gave me a thought: when I tried to write an algorithm for this, I tried to write an algorithm which colored as many of the nodes as possible black (e.g. given a perfect binary search tree, all nodes would be black), while the easiest solution (and the one given in the linked question) seems to give red-black trees with either minimal or near-minimal black depth (e.g. given a perfect binary search tree, layers would alternate between red and black). Coloring the most nodes black seemed to be a much harder problem, and while I have a partial solution written in a Java-like language, it is not correct.

// Helper to recursively color both children of a node; calls to
// colorAVLChildren do not on their own contribute to recursion
// depth, only the calls which they themselves make to colorAVL.
void colorAVLChildren(Node root) {
    if (root != nil) {
        colorAVL(root.left);
        colorAVL(root.right);
    }
}

void colorAVL(Node root) {
    if (root == nil) {
        return;
    }

    root.color = BLACK;

    // All nil nodes are already black, so regardless of the results
    // of the conditionals, the same effect will overall be had on the
    // coloring of the tree.
    if (root.left != nil) {
        root.left.color = BLACK;
    }
    if (root.right != nil) {
        root.right.color = BLACK;
    }

    if (root.isBalanced()) {
        colorAVLChildren(root.left);
        colorAVLChildren(root.right);
    } else {
        if (root.tallestChild().tallestChild() == nil) {
            root.tallestChild().color = RED;

            return;
        }

        // At least the taller of the tallest child's two children is
        // too tall for the next level of the recursion (i.e., would
        // be taller than other trees at that level, thus violating
        // its invariants); however, it is of the correct black-depth.
        // Therefore, it must be red so that its children are at the
        // correct black-depth, but must not be passed as an argument
        // to colorAVL.
        root.tallestChild().tallestChild().color = RED;

        // This part is incorrect if root.tallestChild().tallestChild() is not balanced
        colorAVLChildren(root.tallestChild().tallestChild());

        // If this tallest child is balanced, treat both of its
        // children the same; otherwise, don't color the shorter of
        // its children at this level of recursion, instead leaving it
        // to the next level to preserve the one-to-one correspondence
        // between tree height and recursion level.
        if (root.tallestChild().isBalanced()) {
            root.tallestChild().shortestChild().color = RED;
            // This part is incorrect if root.tallestChild().shortestChild() is not balanced
            colorAVLChildren(root.tallestChild().shortestChild());
        } else {
            colorAVL(root.tallestChild().shortestChild());
        }

        // The next level in this recursion is the level of the
        // shorter of the two children (as this is the only level
        // which both children are guaranteed to possess); therefore,
        // this shorter child must be colored at the next level of
        // recursion.
        colorAVL(root.shortestChild());
    }
}


问:
C Pointer assignments - global
The following code:

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

char *msg = "Hello, World!";
char *p;

p = msg;

int main()
{
    puts(msg);
    return EXIT_SUCCESS;
}
</code>```

gives an error :  error C2040: 'p': 'int' differs in levels of indirection from 'char *'

but when we change the pointer assignment p = msg within the main there are no errors?

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

char *msg = "Hello, World!";
char *p;

int main()
{
    p = msg;
    puts(msg);
    return EXIT_SUCCESS;
}
</code>```

Any suggestions     ?

Title: C Pointer assignments - global

Body:
The following code:

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

char *msg = "Hello, World!";
char *p;

p = msg;

int main()
{
    puts(msg);
    return EXIT_SUCCESS;
}

gives an error :  error C2040: 'p': 'int' differs in levels of indirection from 'char *'

but when we change the pointer assignment p = msg within the main there are no errors?

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

char *msg = "Hello, World!";
char *p;

int main()
{
    p = msg;
    puts(msg);
    return EXIT_SUCCESS;
}

Any suggestions     ?


问:
Why can't macros see variables in scope?
I apparently don't understand how scoping works with regards to macros. I'm trying to write a macro using the TT muncher pattern. I think I need to have an initial matching arm which declares a variable, then munching arms which build it as they consume sequences of tokens.

Here's an oversimplified thing that works, following the general pattern:

```<code>macro_rules! simple_muncher {
    (__recursive) => {};
    (__recursive $l : literal $($tail:tt)*) => {
        {
        println!("I see {}", $l);
        simple_muncher!(__recursive $($tail)*);
        }
    };
    ($($tail:tt)*) => {
        {
        println!("Starting off!");
        simple_muncher!(__recursive $($tail)*)
        }
    }
}
</code>```

And here's one that doesn't work, because it doesn't see v as being in scope:

```<code>
macro_rules! scoped_muncher {
    (__recursive) => {};
    (__recursive $l : literal $($tail:tt)*) => {
        {
        v.push(stringify!($l));
        simple_muncher!(__recursive $($tail)*);
        }
    };
    ($($tail:tt)*) => {
        {
        println!("Starting off!");
        let mut v : Vec<&str> = Vec::<&str>::new();
        scoped_muncher!(__recursive  $($tail)*);
        println!("Vector contains: {:?}", v)
        }
    }
}
</code>```

But why doesn't it? For a simple call (scoped_muncher!(1), say) shouldn't it be outputting something like:

```<code>{

        println!("Starting off!");
        let mut v : Vec<&str> = Vec::<&str>::new();
        {
            v.push(stringify!(1));
        }
        println!("Vector contains: {:?}", v)
}
</code>```

which is perfectly legal. Why is the macro saying that there's no v in scope?

What's the rhyme or reason to what macros can or can't see?
Bonus question: even in the working version, it looks like I'll be generating a lot of nested scopes. Is there any way around that? There seem to be unclear rules of when you need the extra {} block within the RHS of a macro arm, and when you don't.

Body:
I apparently don't understand how scoping works with regards to macros. I'm trying to write a macro using the TT muncher pattern. I think I need to have an initial matching arm which declares a variable, then munching arms which build it as they consume sequences of tokens.

Here's an oversimplified thing that works, following the general pattern:

macro_rules! simple_muncher {
    (__recursive) => {};
    (__recursive $l : literal $($tail:tt)*) => {
        {
        println!("I see {}", $l);
        simple_muncher!(__recursive $($tail)*);
        }
    };
    ($($tail:tt)*) => {
        {
        println!("Starting off!");
        simple_muncher!(__recursive $($tail)*)
        }
    }
}

And here's one that doesn't work, because it doesn't see v as being in scope:

macro_rules! scoped_muncher {
    (__recursive) => {};
    (__recursive $l : literal $($tail:tt)*) => {
        {
        v.push(stringify!($l));
        simple_muncher!(__recursive $($tail)*);
        }
    };
    ($($tail:tt)*) => {
        {
        println!("Starting off!");
        let mut v : Vec<&str> = Vec::<&str>::new();
        scoped_muncher!(__recursive  $($tail)*);
        println!("Vector contains: {:?}", v)
        }
    }
}

But why doesn't it? For a simple call (scoped_muncher!(1), say) shouldn't it be outputting something like:

{

        println!("Starting off!");
        let mut v : Vec<&str> = Vec::<&str>::new();
        {
            v.push(stringify!(1));
        }
        println!("Vector contains: {:?}", v)
}

which is perfectly legal. Why is the macro saying that there's no v in scope?

What's the rhyme or reason to what macros can or can't see?
Bonus question: even in the working version, it looks like I'll be generating a lot of nested scopes. Is there any way around that? There seem to be unclear rules of when you need the extra {} block within the RHS of a macro arm, and when you don't.


问:
How can I run graphql subscription locally without network transport?
I am working on implementing graphql in AWS lambda + apigateway in golang. The API gateway is a websocket gateway which works as network layer. Lambda is just golang application to handle graphql query and resolvers.

I am using github.com/graph-gophers/graphql-go as the graphql library and I need to support subscription. I'd like to avoid importing any network layer in my golang code since all of that is handled by api gateway. My lambda should be just a pure graphql application.

The code I have is to load the schema first:

```<code>graphqlSchema = graphql.MustParseSchema(s, &resolver.Resolver{})
h = handler.New(graphqlSchema)
</code>```

In the handler, it works like a wrapper of graphql. It passes query parameters to schema.Exec method call as below:

```<code>
type Handler struct {
    schema *graphql.Schema
}

func New(schema *graphql.Schema) *Handler {
    h := Handler{schema}
    return &h
}

func (h *Handler) Exec(ctx context.Context, operationName string, query string, variables map[string]interface{}) *graphql.Response {
    response := h.schema.Exec(ctx, query, operationName, variables)
    return response
}

</code>```

when I run the code, I got this error from the response of h.schema.Exec:

&{[graphql: graphql-ws protocol header is missing] [] map[]}

it seems it complains about missing graphql-ws protocol. Is there a way to make it work without any protocol/network dependency? I'd like to make it work just like in local memory.

Body:
I am working on implementing graphql in AWS lambda + apigateway in golang. The API gateway is a websocket gateway which works as network layer. Lambda is just golang application to handle graphql query and resolvers.

I am using github.com/graph-gophers/graphql-go as the graphql library and I need to support subscription. I'd like to avoid importing any network layer in my golang code since all of that is handled by api gateway. My lambda should be just a pure graphql application.

The code I have is to load the schema first:

graphqlSchema = graphql.MustParseSchema(s, &resolver.Resolver{})
h = handler.New(graphqlSchema)

In the handler, it works like a wrapper of graphql. It passes query parameters to schema.Exec method call as below:

type Handler struct {
    schema *graphql.Schema
}

func New(schema *graphql.Schema) *Handler {
    h := Handler{schema}
    return &h
}

func (h *Handler) Exec(ctx context.Context, operationName string, query string, variables map[string]interface{}) *graphql.Response {
    response := h.schema.Exec(ctx, query, operationName, variables)
    return response
}

when I run the code, I got this error from the response of h.schema.Exec:

&{[graphql: graphql-ws protocol header is missing] [] map[]}

it seems it complains about missing graphql-ws protocol. Is there a way to make it work without any protocol/network dependency? I'd like to make it work just like in local memory.


问:
Return 1,0 after looking through multiple scenarios if any are true
I need column J to look at multiple different scenarios and return 1,0 if any are true.

In J1 (and continuing down column J)

if B1 is a number and
B2 and B3 are blank and
the sum of G1:G3 is 2 or more
or

if B1 is a number and B2 is a number or if B2 is "-" and B3 is a number

then return 1

However, if in the range of H1:H3 there is a FALSE,
then an additional row must be added to the sum of G1:G3.

If B1 is "-" then J1 is empty

EXAMPLES:

B1 is a number, B3 is also a number, so J1 should read 1

B11 Is a number. B12:B13 are "-". So then we look to the sum of G11:G13. That equals 2, so J11 should read 1.

B23 is a number, and B24:B25 are "-". So then we look to the sum of G23:G25. However H25 is False, so now we look to the sum of G23:G26. If H24 is false too, then we would look to the sum of G23:G27.

One goal is to always add three applicable values from G, looking at H to determine applicable values.

I could split up these formulas into multiple columns if needed.

SAMPLE SHEET

I worked out this formula

=if(B1="-","",if(or(IF(AND(ISNUMBER(B1),SUM(G1:G3)>=2,B2="-",B3="-"),1),if(and(isnumber(B1),or(isnumber(B2),isnumber(B3))),1)),1))

But have no idea how to add the stipulation for column H when a FALSE is present.


问:
How to retrieve only one result with preg_grep or reset numeric keys when there are multiple matches?
I am working on a code that retrieves image links from a wordpress site using the REST API and curl.

My code therefore retrieves the image links provided by the json generated by curl then I retrieve the basename of each link to split them in order to compare each term
with the title of the current wordpress article.

If any of the terms in the title are also found in the name of one or more images, preg_grep displays the results.

The problem is that I would like to retrieve a single result (The first key for example), it doesn't matter which one.

I tried with preg_match but my regex knowledge is limited, do you have any solutions to share?

**
PS: The result of preg_match creates a multi-dimensional array, and I would only want one so I could manage and hope to get a single result in my var_dump.**

**
here's the result:**

```<code>array(1) {
  [1]=>
  string(4) "buzz"
}

array(1) {
  [3]=>
  string(10) "actualites"
}

</code>```

Here is my shortcut code:

`

```<code>$title = get_the_title();
        $regex = array('/[^\p{L}\p{N}\s]/u', '/\s/');
        $repl  = array('', '-');
        $slug = preg_replace($regex, $repl, $title);

        $res_title = explode('-', $slug);

        $path = array(
            'https://ivredevi.fr/wp-json/wp/v2/media?per_page=100&page=1',
        );

        $node_count = count($path);

        $curl_arr = array();
        $master = curl_multi_init();

        for($i = 0; $i < $node_count; $i++)
        {
            $url =$path[$i];
            $curl_arr[$i] = curl_init($url);
            curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($master, $curl_arr[$i]);
        }

        do {
            curl_multi_exec($master,$running);
        } while($running > 0);

        for($i = 0; $i < $node_count; $i++)
        {
            $results = curl_multi_getcontent  ( $curl_arr[$i]  );
            $img = json_decode($results, true);

            $arr_col = array_column($img, 'source_url');

                $new_array = [];
                foreach ($arr_col as $ncol) {
                    $cnt = basename($ncol, '.jpg');
                    $names = explode('-', $cnt);

                    foreach ($res_title as $value) {

                        $pattern = "/$value/i";

                        $results = preg_grep($pattern, $names);

                        $sk = [];

                        if($results){

                            var_dump($results);

                        }
                    }

                }

        }

</code>```

Body:
I am working on a code that retrieves image links from a wordpress site using the REST API and curl.

My code therefore retrieves the image links provided by the json generated by curl then I retrieve the basename of each link to split them in order to compare each term
with the title of the current wordpress article.

If any of the terms in the title are also found in the name of one or more images, preg_grep displays the results.

The problem is that I would like to retrieve a single result (The first key for example), it doesn't matter which one.

I tried with preg_match but my regex knowledge is limited, do you have any solutions to share?

**
PS: The result of preg_match creates a multi-dimensional array, and I would only want one so I could manage and hope to get a single result in my var_dump.**

**
here's the result:**

array(1) {
  [1]=>
  string(4) "buzz"
}

array(1) {
  [3]=>
  string(10) "actualites"
}

Here is my shortcut code:

`

$title = get_the_title();
        $regex = array('/[^\p{L}\p{N}\s]/u', '/\s/');
        $repl  = array('', '-');
        $slug = preg_replace($regex, $repl, $title);

        $res_title = explode('-', $slug);

        $path = array(
            'https://ivredevi.fr/wp-json/wp/v2/media?per_page=100&page=1',
        );

        $node_count = count($path);

        $curl_arr = array();
        $master = curl_multi_init();

        for($i = 0; $i < $node_count; $i++)
        {
            $url =$path[$i];
            $curl_arr[$i] = curl_init($url);
            curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($master, $curl_arr[$i]);
        }

        do {
            curl_multi_exec($master,$running);
        } while($running > 0);

        for($i = 0; $i < $node_count; $i++)
        {
            $results = curl_multi_getcontent  ( $curl_arr[$i]  );
            $img = json_decode($results, true);

            $arr_col = array_column($img, 'source_url');

                $new_array = [];
                foreach ($arr_col as $ncol) {
                    $cnt = basename($ncol, '.jpg');
                    $names = explode('-', $cnt);

                    foreach ($res_title as $value) {

                        $pattern = "/$value/i";

                        $results = preg_grep($pattern, $names);

                        $sk = [];

                        if($results){

                            var_dump($results);

                        }
                    }

                }

        }


问:
Is there a way to check whether MIP is applied by reading a specific offset header in a file without using the MIP SDK?
We are using the MIP(Microsoft Information Protection) SDK to apply labels to files.

However, there are cases where the MIP(Microsoft Information Protection) SDK cannot be used in other specific legacy systems, and it is necessary to check whether the MIP(Microsoft Information Protection) is applied to the file inside the system.

We want to know if there is a way other than the MIP(Microsoft Information Protection) SDK to know if a file has MIP applied or not.

For example, we can predict the file type by reading the start bytes of the file.

.docx, .xlsx, .pptx : 50 4B 03 04

.doc, .xls, .ppt : D0 CF 11 E0 A1 B1 1A E1

.pdf : 25 50 44 46

Thanks.


问:
Groovy script not working in jenkins active choice reactive parameter
I have Jenkins 2.33 running on ubuntu 18.04, the groovy script which executes a shell script located at usr/local/bin and lists the branches of gitlab repo. groovy script collects each line as tags in active choice reactive parameter. But now with ubuntu 22.04 and java 11 , jenkins 2.36 its not working anymore. branches.sh located at usr/local/bin.I want the list generated by shell script to be appended into a list so that branch can be selected to build..
script is as below.</p>
```<code>tags = []
text = "branches.sh https://gitlab.com/xyz/${services}.git".execute().text
text.eachLine { tags.push(it) }
return tags
</code>```

Body:
I have Jenkins 2.33 running on ubuntu 18.04, the groovy script which executes a shell script located at usr/local/bin and lists the branches of gitlab repo. groovy script collects each line as tags in active choice reactive parameter. But now with ubuntu 22.04 and java 11 , jenkins 2.36 its not working anymore. branches.sh located at usr/local/bin.I want the list generated by shell script to be appended into a list so that branch can be selected to build..
script is as below.

tags = []
text = "branches.sh https://gitlab.com/xyz/${services}.git".execute().text
text.eachLine { tags.push(it) }
return tags


问:
Can libzip reliably write in zip archives from buffers/memory (not files)?
I am creating an archive dynamically an need to write some binary data dynamically as file entries.
I am also using the extra_field API to add more metadata.
Unfortunately when I write using source_buffer the data written gets corrupted.

API calls are along the lines of:

```<code>const std::string diff; //this is initialized and passed from a function
zip_t z_; //class member initialized before
const std::string f; // name of the virtual file, passed in the function
// use unique_ptr to manage the lifetime of zip_source_t
std::unique_ptr<zip_source_t, void (*)(zip_source_t*)>  p_zf(
    zip_source_buffer_create((const void*)diff.data(), diff.size(), 0, 0),
    [](zip_source_t* p) { if(p) zip_source_free(p); }
);
if (!p_zf)
    throw exception ...;
// write inside archive and initialize the fields
const zip_int64_t idx = zip_file_add(z_, f.c_str(), p_zf.get(), ZIP_FL_ENC_GUESS);
if(-1 == idx)
    throw exception ...;
// write extra field
if(zip_file_extra_field_set(z_, idx, FS_ZIP_EXTRA_FIELD_ID, 0, (const zip_uint8_t*)&metadata, sizeof(metadata), ZIP_FL_LOCAL))
    throw exception ...;
</code>```

The code above 'works' but then when I read the archive back for the virtual file f I get some garbled values. The metadata (fairly large, 256 bytes) is perfectly stored.

If I replace the zip_source_buffer_create with:

```<code>zip_source_buffer(z_, (const void*)diff.data(), diff.size(), 0)
</code>```

I get the very same garbled data (the size is always as expected, but the content gets polluted).
Only if I write a temporary file and then initialize the zip_source_t via filesystem API (i.e. zip_source_file_create) then all is saved fine:

```<code>std::unique_ptr<zip_source_t, void (*)(zip_source_t*)>  p_zf(
    zip_source_file_create(tmp_filename, 0, -1, 0),
    [](zip_source_t* p) { if(p) zip_source_close(p); }
);
</code>```

Am I doing anything wrong?
Please note that the lifetime of diff is const within the scope of both zip_source_buffer_create, zip_source_buffer and zip_file_add.
Is this a potential bug in libzip?
I'm using version 1.7.3 on Ubuntu 22.04 64 bit.

Body:
I am creating an archive dynamically an need to write some binary data dynamically as file entries.
I am also using the extra_field API to add more metadata.
Unfortunately when I write using source_buffer the data written gets corrupted.

API calls are along the lines of:

const std::string diff; //this is initialized and passed from a function
zip_t z_; //class member initialized before
const std::string f; // name of the virtual file, passed in the function
// use unique_ptr to manage the lifetime of zip_source_t
std::unique_ptr<zip_source_t, void (*)(zip_source_t*)>  p_zf(
    zip_source_buffer_create((const void*)diff.data(), diff.size(), 0, 0),
    [](zip_source_t* p) { if(p) zip_source_free(p); }
);
if (!p_zf)
    throw exception ...;
// write inside archive and initialize the fields
const zip_int64_t idx = zip_file_add(z_, f.c_str(), p_zf.get(), ZIP_FL_ENC_GUESS);
if(-1 == idx)
    throw exception ...;
// write extra field
if(zip_file_extra_field_set(z_, idx, FS_ZIP_EXTRA_FIELD_ID, 0, (const zip_uint8_t*)&metadata, sizeof(metadata), ZIP_FL_LOCAL))
    throw exception ...;

The code above 'works' but then when I read the archive back for the virtual file f I get some garbled values. The metadata (fairly large, 256 bytes) is perfectly stored.

If I replace the zip_source_buffer_create with:

zip_source_buffer(z_, (const void*)diff.data(), diff.size(), 0)

I get the very same garbled data (the size is always as expected, but the content gets polluted).
Only if I write a temporary file and then initialize the zip_source_t via filesystem API (i.e. zip_source_file_create) then all is saved fine:

std::unique_ptr<zip_source_t, void (*)(zip_source_t*)>  p_zf(
    zip_source_file_create(tmp_filename, 0, -1, 0),
    [](zip_source_t* p) { if(p) zip_source_close(p); }
);

Am I doing anything wrong?
Please note that the lifetime of diff is const within the scope of both zip_source_buffer_create, zip_source_buffer and zip_file_add.
Is this a potential bug in libzip?
I'm using version 1.7.3 on Ubuntu 22.04 64 bit.


问:
Cypress run error: Cannot read properties of undefined (reading 'createElement')
I keep hitting the following error:

```<code>  Running:  checkSellerConsoleForError.spec.js                                              (1 of 8)
Cannot read properties of undefined (reading 'createElement')
TypeError: Cannot read properties of undefined (reading 'createElement')
    at y (<embedded>:2877:169748)
    at new j (<embedded>:2877:166556)
    at S.setRunnables (<embedded>:4526:15381)
    at Object.onTestsReceivedAndMaybeRecord (<embedded>:4573:338651)
    at p.<anonymous> (<embedded>:4573:66378)
    at p.emit (node:events:527:28)
    at p.emitUntyped (<embedded>:4298:41416)
    at <embedded>:4298:48933
    at process.processTicksAndRejections (node:internal/process/task_queues:78:11)
</code>```

for a simple test like this:

```<code>describe('Check Seller Platform for console errors', () => {
  it('Should be no console errors for the Seller platform', () => {
    cy.visit('/')
    cy.window()
      .its('console')
      .then((console) => {
        cy.stub(console, 'log').callsFake((...args) => {
          args.forEach.each((arg) => {
            expect(String(arg)).to.not.contain('error')
          })
          console.log.wrappedMethod(...args)
        })
      })
    // eslint-disable-next-line cypress/no-unnecessary-waiting
    cy.wait(2000)
  })
})
</code>```

Cypress 12.2.0

Body:
I keep hitting the following error:

  Running:  checkSellerConsoleForError.spec.js                                              (1 of 8)
Cannot read properties of undefined (reading 'createElement')
TypeError: Cannot read properties of undefined (reading 'createElement')
    at y (<embedded>:2877:169748)
    at new j (<embedded>:2877:166556)
    at S.setRunnables (<embedded>:4526:15381)
    at Object.onTestsReceivedAndMaybeRecord (<embedded>:4573:338651)
    at p.<anonymous> (<embedded>:4573:66378)
    at p.emit (node:events:527:28)
    at p.emitUntyped (<embedded>:4298:41416)
    at <embedded>:4298:48933
    at process.processTicksAndRejections (node:internal/process/task_queues:78:11)

for a simple test like this:

describe('Check Seller Platform for console errors', () => {
  it('Should be no console errors for the Seller platform', () => {
    cy.visit('/')
    cy.window()
      .its('console')
      .then((console) => {
        cy.stub(console, 'log').callsFake((...args) => {
          args.forEach.each((arg) => {
            expect(String(arg)).to.not.contain('error')
          })
          console.log.wrappedMethod(...args)
        })
      })
    // eslint-disable-next-line cypress/no-unnecessary-waiting
    cy.wait(2000)
  })
})

Cypress 12.2.0


问:
McEliece cryptosystem using Reed Solomon
I’m about to make a python coding to construct encode decode using Reed Solomon codes implementation in McEliece cryptosystem.

I’ve tried construct Reed Solomon code but in normal cause, not in McEliece cryptosystem. I’ve found error whenever i tried to construct the generator matrix. anyone know why this was happened? thank you for your help


问:
Save numpy.ndarray as csv or parquet line by line
I have 3 np.ndarrays in following shape with float values inside where 1st column has just one value and other two columns have arrays for each record:

```<code>(7981112,) (7981112, 512) (7981112, 512)
</code>```

I have to save this in dataframe with 3 columns id, rec, dist. I tried writing it to pandas but it's taling lot of time while saving and then running into memory issue.

Approach:

```<code>df = pd.DataFrame([item_id, I, D], index = ['id', 'rec', 'dist']).T
df.to_csv(location, index = False)
</code>```

Can someone tell me what will be the most optimized way of writing such csv or parquet files

Trying to write line by line:

```<code>with open(path, 'w') as local_path:
    for i in range(100):
        output_str = str(item[i]) + ',' + str(res[i]) +','+ str(dist[i]) + '\n'
        local_path.write(output_str)
</code>```

But it's not creating any sep columns it's writing everything into one column.

Probably writing line by line approach will be much faster for me but I'm not able to write in proper format.

Expected Out:

```<code>id    recs           dist
1     [12, 45,..]    [0.8, 0.9,.]
2     [4, 6, ..]     [0.1, 0.2,..]
3     [90, 7, ..]    [0.9, 0.9,..]
.        .            .
</code>```

Body:
I have 3 np.ndarrays in following shape with float values inside where 1st column has just one value and other two columns have arrays for each record:

(7981112,) (7981112, 512) (7981112, 512)

I have to save this in dataframe with 3 columns id, rec, dist. I tried writing it to pandas but it's taling lot of time while saving and then running into memory issue.

Approach:

df = pd.DataFrame([item_id, I, D], index = ['id', 'rec', 'dist']).T
df.to_csv(location, index = False)

Can someone tell me what will be the most optimized way of writing such csv or parquet files

Trying to write line by line:

with open(path, 'w') as local_path:
    for i in range(100):
        output_str = str(item[i]) + ',' + str(res[i]) +','+ str(dist[i]) + '\n'
        local_path.write(output_str)

But it's not creating any sep columns it's writing everything into one column.

Probably writing line by line approach will be much faster for me but I'm not able to write in proper format.

Expected Out:

id    recs           dist
1     [12, 45,..]    [0.8, 0.9,.]
2     [4, 6, ..]     [0.1, 0.2,..]
3     [90, 7, ..]    [0.9, 0.9,..]
.        .            .


问:
Handling print as PDF in selenium webdriver
I am trying to print as pdf by selenium but without the header and footer information. I made this code using Java and AutoIT tool to deal with the print window.

Here's my Java code:

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk-printing");
options.addArguments("--printing.paper_size_default");

ChromeDriver driver = new ChromeDriver(options);

driver.get("http://google.com");
driver.manage().window().maximize();
Thread.sleep(10000);

//get page title tag so I can use later to put name on PDF file
String pageText = driver.findElement(By.tagName("title")).getAttribute("innerHTML");

//saving title text to clipboard so I can get on autoIT executable
StringSelection stringSelection = new StringSelection(pageText);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

//open print window and execute autoIT file
((JavascriptExecutor) driver).executeScript("print()");
Thread.sleep(5000);

Runtime.getRuntime().exec("src/savfiles.exe");
</code>```

Here's my autoIT code (savfiles.exe):

```<code>//getting title text that I copy to clipboard
Global $sLastClip = ClipGet();

//focus on name file
ControlFocus("Salvar Saída de Impressão como", "", "ComboBox1");
Sleep(500);

//past the text on field`
ControlSetText("Salvar Saída de Impressão como", "", "Edit1", $sLastClip);
Sleep(500);

//click on confirm button and save`
ControlClick("Salvar Saída de Impressão como", "", "Button2");
Sleep(500);

//if there's another file with the same name the operational system will ask if you want to replace the file. this line will confirm that yes
ControlClick("Confirmar Salvar como", "", "Button1");
</code>```

I tried to put some prefs as ("isHeaderAndFooter", false) but it seems not working and I looked many documentations as I could and found nothing dealing with it (at least with java).

Body:
I am trying to print as pdf by selenium but without the header and footer information. I made this code using Java and AutoIT tool to deal with the print window.

Here's my Java code:

ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk-printing");
options.addArguments("--printing.paper_size_default");

ChromeDriver driver = new ChromeDriver(options);

driver.get("http://google.com");
driver.manage().window().maximize();
Thread.sleep(10000);

//get page title tag so I can use later to put name on PDF file
String pageText = driver.findElement(By.tagName("title")).getAttribute("innerHTML");

//saving title text to clipboard so I can get on autoIT executable
StringSelection stringSelection = new StringSelection(pageText);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

//open print window and execute autoIT file
((JavascriptExecutor) driver).executeScript("print()");
Thread.sleep(5000);

Runtime.getRuntime().exec("src/savfiles.exe");

Here's my autoIT code (savfiles.exe):

//getting title text that I copy to clipboard
Global $sLastClip = ClipGet();

//focus on name file
ControlFocus("Salvar Saída de Impressão como", "", "ComboBox1");
Sleep(500);

//past the text on field`
ControlSetText("Salvar Saída de Impressão como", "", "Edit1", $sLastClip);
Sleep(500);

//click on confirm button and save`
ControlClick("Salvar Saída de Impressão como", "", "Button2");
Sleep(500);

//if there's another file with the same name the operational system will ask if you want to replace the file. this line will confirm that yes
ControlClick("Confirmar Salvar como", "", "Button1");

I tried to put some prefs as ("isHeaderAndFooter", false) but it seems not working and I looked many documentations as I could and found nothing dealing with it (at least with java).


问:
PHP QR Code outputting .png as a character string
I've built my first WordPress plugin to create a QR Code from a form.

It's just for learning purposes and would not meet standards for commercial release.

However it works perfectly on my local server in WAMP using Twenty Twenty theme.

When i test it on my live site (with a commercial theme) the qr code in .png format is displayed as a atring of characters similar to this.

�PNG  IHDR{{n m<�PLTE���U��~ pHYs���+aIDATH���1�� ��P��H�W�]���� �΂0;>_�n�ζ�X����w����h�

The string is much longer, but i just put a snippet in to show what i mean.

Below is my plugin code and it includes the full untouched phpqrcode library.

```<code><?php
/*
 * Plugin Name: QR Code Generator
 * Plugin URI: https://www.example.com/qr-code-generator
 * Description: A plugin that allows you to easily generate QR codes for use on your website.
 * Version: 1.0
 * Author: Your Name
 * Author URI: https://www.example.com
 * License: GPL2
 */
include_once( plugin_dir_path( __FILE__ ) . 'phpqrcode/qrlib.php' );

function qr_code_shortcode( $atts ) {
    // Extract the attributes
    extract( shortcode_atts( array(
        'text' => '',
    ), $atts ) );

    global $post;

    // Check if the shortcode is present in the post or page
    if ( has_shortcode( $post->post_content, 'qr_code' ) ) {
        // Check if the form has been submitted
        if ( isset( $_POST['qr_code_text'] ) ) {
            $text = sanitize_text_field( $_POST['qr_code_text'] );
            // Generate the QR code
            QRcode::png( $text );
        } else {
            // Display the form
            ob_start();
            echo '<form method="post">';
            echo '<label for="qr_code_text">Enter the text for the QR code:</label><br>';
            echo '<input type="text" name="qr_code_text" id="qr_code_text"><br>';
            echo '<input type="submit" value="Generate QR Code">';
            echo '</form>';
            return ob_get_clean();
        }
    }
}
add_shortcode( 'qr_code', 'qr_code_shortcode' );
</code>```

Any suggestions as to why it would work in one site and not on another ?

I've tried using base64 on the image thinking it was that but to no avail.

Body:
I've built my first WordPress plugin to create a QR Code from a form.

It's just for learning purposes and would not meet standards for commercial release.

However it works perfectly on my local server in WAMP using Twenty Twenty theme.

When i test it on my live site (with a commercial theme) the qr code in .png format is displayed as a atring of characters similar to this.

�PNG  IHDR{{n m<�PLTE���U��~ pHYs���+aIDATH���1�� ��P��H�W�]���� �΂0;>_�n�ζ�X����w����h�

The string is much longer, but i just put a snippet in to show what i mean.

Below is my plugin code and it includes the full untouched phpqrcode library.

<?php
/*
 * Plugin Name: QR Code Generator
 * Plugin URI: https://www.example.com/qr-code-generator
 * Description: A plugin that allows you to easily generate QR codes for use on your website.
 * Version: 1.0
 * Author: Your Name
 * Author URI: https://www.example.com
 * License: GPL2
 */
include_once( plugin_dir_path( __FILE__ ) . 'phpqrcode/qrlib.php' );

function qr_code_shortcode( $atts ) {
    // Extract the attributes
    extract( shortcode_atts( array(
        'text' => '',
    ), $atts ) );

    global $post;

    // Check if the shortcode is present in the post or page
    if ( has_shortcode( $post->post_content, 'qr_code' ) ) {
        // Check if the form has been submitted
        if ( isset( $_POST['qr_code_text'] ) ) {
            $text = sanitize_text_field( $_POST['qr_code_text'] );
            // Generate the QR code
            QRcode::png( $text );
        } else {
            // Display the form
            ob_start();
            echo '<form method="post">';
            echo 'Enter the text for the QR code:
';
            echo '<input type="text" name="qr_code_text" id="qr_code_text">
';
            echo '<input type="submit" value="Generate QR Code">';
            echo '</form>';
            return ob_get_clean();
        }
    }
}
add_shortcode( 'qr_code', 'qr_code_shortcode' );

Any suggestions as to why it would work in one site and not on another ?

I've tried using base64 on the image thinking it was that but to no avail.


问:
Multiple Requests until it's complete?
My first GPT-3 project is to pull some basic JSON from a body of text. Using NodeJS.

In the Playground:

The completion works great. I have to keep pressing the "Submit button" though, to get it to finish.

Take at least 5 times. I guess this is because of the token limitations on each request.

In NodeJS:

Using the same prompt that worked in Playground (which required multiple Submits), would the equivalent way in a programmatic NodeJS environment be to just keep submitting requests? Or like maybe partial requests? Maybe keep stringify-ing the concat'd completion until it is a valid JSON object?

What is a recommended way to make multiple requests and keep track of when a completion is done using OpenAI GPT-3?

Title: Multiple Requests until it's complete?


问:
Can Floyd warshall algorithm print the edges in a negative cycle?
Is there some way to modify this algorithm so it prints all negative cycles, or at least more than one?
I understand you can enumerate all cycles in Johnson’s algorithm but i was wondering if I could do this with Floyd warshall too and then filter by the sum of edge weights for each cycle. If not, are there any alternative algorithms?</p>


问:
Displaying Firestore Array that is displayed in console on page
I currently am working on a Fitness app.  I currently am just trying to have a page where there is a button for "chest" and a button for "legs".  I would like to display on the webpage the array of exercises when the user clicks one of the two buttons.  I currently have the code below that allows me to print to the console the array from my firestore Db, and it works with onClick, but I am having issues with displaying it on the web page outside of the console.  I'm pretty sure my issue is with objects and useState, but I am not 100% sure.  I have tried a few solutions and nothing changed.

```<code>
```
import React, { useState } from 'react'
import './Workoutselector.css'
import { collection, documentId, onSnapshot, query, where, getDoc } from "firebase/firestore"
import { db } from '../Firebase'
import { render } from '@testing-library/react'

export const Workoutselector = () => {

const [exercises2, setExercises2] = useState([]);
//connect to exercises2 collection
const exercises2ColRef = collection(db, 'exercises2');

const getChest = async () => {
  const q = query(exercises2ColRef,
    where(documentId(), '==', 'chest'))

    const unsub = onSnapshot(q, (querySnapshot) => {
      const exercises2 = [];
      querySnapshot.forEach((doc) => {
        exercises2.push(doc.data());
      });
      setExercises2(exercises2);
      console.log(exercises2);

    });
    return () => { unsub(); }
  }

  const getLegs = async () => {
    const q = query(exercises2ColRef,
      where(documentId(), '==', 'legs'))

      const unsub = onSnapshot(q, (querySnapshot) => {
        const exercises2 = [];
        querySnapshot.forEach((doc) => {
          exercises2.push(doc.data());
        });
        setExercises2(exercises2);
        console.log(exercises2)
      });
      return () => {
        unsub(); }
    }

  return (

Choose a Workout
        <button onClick={getChest}>Chest</button>
        <button onClick={getLegs}>Legs</button>

  )
}
`
[enter image description here](https://i.stack.imgur.com/6Hx7J.png)

For the JSX I have tried the following.  However, I receive an error I dont fully understand.  The exercises do display onClick now, but it does look bad and is all as one string (perhaps a separate issue?). Apologies if this is some noob type questions.  I am very new to programming and react, but I am plowing through as best I can.[[enter image description here](https://i.stack.imgur.com/tPOr1.png)](https://i.stack.imgur.com/xZvtY.png)

```

```
return (

Choose a Workout
        <button onClick={getChest}>Chest</button>
        {exercises2.map((exercises2) => {
        return (

Name: {exercises2.name}

)})}
        <button onClick={getLegs}>Legs</button>

  )
}

```

>
</code>```

Body:
I currently am working on a Fitness app.  I currently am just trying to have a page where there is a button for "chest" and a button for "legs".  I would like to display on the webpage the array of exercises when the user clicks one of the two buttons.  I currently have the code below that allows me to print to the console the array from my firestore Db, and it works with onClick, but I am having issues with displaying it on the web page outside of the console.  I'm pretty sure my issue is with objects and useState, but I am not 100% sure.  I have tried a few solutions and nothing changed.

```
import React, { useState } from 'react'
import './Workoutselector.css'
import { collection, documentId, onSnapshot, query, where, getDoc } from "firebase/firestore"
import { db } from '../Firebase'
import { render } from '@testing-library/react'

export const Workoutselector = () => {

const [exercises2, setExercises2] = useState([]);
//connect to exercises2 collection
const exercises2ColRef = collection(db, 'exercises2');

const getChest = async () => {
  const q = query(exercises2ColRef,
    where(documentId(), '==', 'chest'))

    const unsub = onSnapshot(q, (querySnapshot) => {
      const exercises2 = [];
      querySnapshot.forEach((doc) => {
        exercises2.push(doc.data());
      });
      setExercises2(exercises2);
      console.log(exercises2);

    });
    return () => { unsub(); }
  }

  const getLegs = async () => {
    const q = query(exercises2ColRef,
      where(documentId(), '==', 'legs'))

      const unsub = onSnapshot(q, (querySnapshot) => {
        const exercises2 = [];
        querySnapshot.forEach((doc) => {
          exercises2.push(doc.data());
        });
        setExercises2(exercises2);
        console.log(exercises2)
      });
      return () => {
        unsub(); }
    }

  return (
    <div className='selector-div'>Choose a Workout
        <button onClick={getChest}>Chest</button>
        <button onClick={getLegs}>Legs</button>

    </div>
  )
}
`
[enter image description here](https://i.stack.imgur.com/6Hx7J.png)

For the JSX I have tried the following.  However, I receive an error I dont fully understand.  The exercises do display onClick now, but it does look bad and is all as one string (perhaps a separate issue?). Apologies if this is some noob type questions.  I am very new to programming and react, but I am plowing through as best I can.[[enter image description here](https://i.stack.imgur.com/tPOr1.png)](https://i.stack.imgur.com/xZvtY.png)

```

```
return (
    <div className='selector-div'>Choose a Workout
        <button onClick={getChest}>Chest</button>
        {exercises2.map((exercises2) => {
        return ( <div>
        <p>Name: {exercises2.name}</p>
        </div>)})}
        <button onClick={getLegs}>Legs</button>

    </div>
  )
}

```

>


问:
Using Microsoft.Data.Analysis how can I fetch data from database to Dataframe?
I am trying to use Microsoft.Data.Analysis in .net6.
Is it possible to get data from database into Dataframe?</p>


问:
abc.py __instancecheck__ taking an inordinate amount of time for large calculation. Is there a way around it without abandoning python?
I wrote a program for calculating certain polynomials in python and it's reasonably fast, but I ran cProfile on it and the results are disturbing. The specific run takes 296 seconds, which is fine, but the cumulative time spent in abc.py __instancecheck__ is 43 seconds. This is really pointing to writing it in something other than python, especially since there's a calculation I want to run that, with the current code, would take 50 days.

```<code>  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    201/1    0.001    0.000  296.104  296.104 {built-in method builtins.exec}
        1    0.000    0.000  296.104  296.104 double_samuel_schubmult7.py:1(<module>)
        1   85.132   85.132  295.717  295.717 double_samuel_schubmult7.py:205(schubmult)
    72618   34.608    0.000   94.825    0.001 double_samuel_schubmult7.py:247(<listcomp>)
 46620756   19.717    0.000   60.217    0.000 double_samuel_schubmult7.py:171(elem_sym_func)
        1    0.002    0.002   54.962   54.962 parallel.py:1000(__call__)
        1    0.584    0.584   54.886   54.886 parallel.py:960(retrieve)
    12039    0.013    0.000   54.181    0.005 pool.py:767(get)
    12039    0.008    0.000   54.160    0.004 pool.py:764(wait)
    12054    0.018    0.000   54.156    0.004 threading.py:589(wait)
      768    0.010    0.000   54.119    0.070 threading.py:288(wait)
     3126   54.105    0.017   54.105    0.017 {method 'acquire' of '_thread.lock' objects}
 58143528    7.986    0.000   43.820    0.000 abc.py:117(__instancecheck__)
 58143528   12.915    0.000   35.834    0.000 {built-in method _abc._abc_instancecheck}
 8188300/3054264   30.769    0.000   30.769    0.000 double_samuel_schubmult7.py:148(elem_sym_poly)
58143557/58143542    7.913    0.000   22.918    0.000 abc.py:121(__subclasscheck__)
58143557/58143542   15.006    0.000   15.006    0.000 {built-in method _abc._abc_subclasscheck}
</code>```

The threading portion is for a small part of the code at the end that is unproblematic, most of the code is single-threaded.

Does this 43 seconds of abc __instancecheck__ time spent really mean that if I write it in, say, C, it will be at least 43 seconds faster? Is there a way to suppress it?

I should note that for polynomial calculations I'm using symengine, which could be where this is happening, or numpy. Below is the main function (schubmult).

```<code>from symengine import *
import numpy as np

..200 lines of omitted code..

def schubmult(perm_dict,v):
    vn1 = inverse(v)
    th = theta(vn1)
    if th[0]==0:
        return perm_dict
    mu = permtrim(uncode(th))
    vmu = permtrim(mulperm(list(v),mu))
    inv_vmu = inv(vmu)
    inv_mu = inv(mu)
    ret_dict = {}
    vpaths = [([(vmu,0)],1)]
    while th[-1] == 0:
        th.pop()
    for i in range(len(th)):
        k = i+1
        vpaths2 = []
        for path,s in vpaths:
            last_perm = path[-1][0]
            newperms = kdown_perms(last_perm,th[i],k)
            for new_perm,s2,vdiff in newperms:
                new_perm2 = permtrim(new_perm)
                if i == len(th)-1 and (len(new_perm2) != 2 or new_perm2[0]!=1):
                    continue
                path2 = [*path,(new_perm2,vdiff)]
                vpaths2 += [(path2,s*s2)]
        vpaths = vpaths2
    arr0 = [0 for vpath in vpaths]
    for u,val in perm_dict.items():
        inv_u = inv(u)
        vpathsums = {u: val*np.array([vpath[1] for vpath in vpaths])}
        for index in range(len(th)):
            newpathsums = {}
            for up, arr in vpathsums.items():
                inv_up = inv(up)
                newperms = elem_sym_perms(up,min(th[index],(inv_mu-(inv_up-inv_u))-inv_vmu),th[index])
                for up2, udiff in newperms:
                    newpathsums[up2] = newpathsums.get(up2,np.array(arr0))+arr*[elem_sym_func(th[index],index+1,up,up2,vpaths[i][0][index][0],vpaths[i][0][index+1][0],udiff,vpaths[i][0][index+1][1],var2,var3) for i in range(len(vpaths))]
            vpathsums = newpathsums
        if len(vpaths)<300:
            ret_dict = add_perm_dict({ep: np.sum(arr) for ep,arr in vpathsums.items()},ret_dict)
        else:
            ret_dict = add_perm_dict(dict(Parallel(n_jobs=-1,require='sharedmem')(delayed(pairsum)(ep,arr) for ep,arr in vpathsums.items())),ret_dict)
    return ret_dict
</code>```

Body:
I wrote a program for calculating certain polynomials in python and it's reasonably fast, but I ran cProfile on it and the results are disturbing. The specific run takes 296 seconds, which is fine, but the cumulative time spent in abc.py __instancecheck__ is 43 seconds. This is really pointing to writing it in something other than python, especially since there's a calculation I want to run that, with the current code, would take 50 days.

  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    201/1    0.001    0.000  296.104  296.104 {built-in method builtins.exec}
        1    0.000    0.000  296.104  296.104 double_samuel_schubmult7.py:1(<module>)
        1   85.132   85.132  295.717  295.717 double_samuel_schubmult7.py:205(schubmult)
    72618   34.608    0.000   94.825    0.001 double_samuel_schubmult7.py:247(<listcomp>)
 46620756   19.717    0.000   60.217    0.000 double_samuel_schubmult7.py:171(elem_sym_func)
        1    0.002    0.002   54.962   54.962 parallel.py:1000(__call__)
        1    0.584    0.584   54.886   54.886 parallel.py:960(retrieve)
    12039    0.013    0.000   54.181    0.005 pool.py:767(get)
    12039    0.008    0.000   54.160    0.004 pool.py:764(wait)
    12054    0.018    0.000   54.156    0.004 threading.py:589(wait)
      768    0.010    0.000   54.119    0.070 threading.py:288(wait)
     3126   54.105    0.017   54.105    0.017 {method 'acquire' of '_thread.lock' objects}
 58143528    7.986    0.000   43.820    0.000 abc.py:117(__instancecheck__)
 58143528   12.915    0.000   35.834    0.000 {built-in method _abc._abc_instancecheck}
 8188300/3054264   30.769    0.000   30.769    0.000 double_samuel_schubmult7.py:148(elem_sym_poly)
58143557/58143542    7.913    0.000   22.918    0.000 abc.py:121(__subclasscheck__)
58143557/58143542   15.006    0.000   15.006    0.000 {built-in method _abc._abc_subclasscheck}

The threading portion is for a small part of the code at the end that is unproblematic, most of the code is single-threaded.

Does this 43 seconds of abc __instancecheck__ time spent really mean that if I write it in, say, C, it will be at least 43 seconds faster? Is there a way to suppress it?

I should note that for polynomial calculations I'm using symengine, which could be where this is happening, or numpy. Below is the main function (schubmult).

from symengine import *
import numpy as np

..200 lines of omitted code..

def schubmult(perm_dict,v):
    vn1 = inverse(v)
    th = theta(vn1)
    if th[0]==0:
        return perm_dict
    mu = permtrim(uncode(th))
    vmu = permtrim(mulperm(list(v),mu))
    inv_vmu = inv(vmu)
    inv_mu = inv(mu)
    ret_dict = {}
    vpaths = [([(vmu,0)],1)]
    while th[-1] == 0:
        th.pop()
    for i in range(len(th)):
        k = i+1
        vpaths2 = []
        for path,s in vpaths:
            last_perm = path[-1][0]
            newperms = kdown_perms(last_perm,th[i],k)
            for new_perm,s2,vdiff in newperms:
                new_perm2 = permtrim(new_perm)
                if i == len(th)-1 and (len(new_perm2) != 2 or new_perm2[0]!=1):
                    continue
                path2 = [*path,(new_perm2,vdiff)]
                vpaths2 += [(path2,s*s2)]
        vpaths = vpaths2
    arr0 = [0 for vpath in vpaths]
    for u,val in perm_dict.items():
        inv_u = inv(u)
        vpathsums = {u: val*np.array([vpath[1] for vpath in vpaths])}
        for index in range(len(th)):
            newpathsums = {}
            for up, arr in vpathsums.items():
                inv_up = inv(up)
                newperms = elem_sym_perms(up,min(th[index],(inv_mu-(inv_up-inv_u))-inv_vmu),th[index])
                for up2, udiff in newperms:
                    newpathsums[up2] = newpathsums.get(up2,np.array(arr0))+arr*[elem_sym_func(th[index],index+1,up,up2,vpaths[i][0][index][0],vpaths[i][0][index+1][0],udiff,vpaths[i][0][index+1][1],var2,var3) for i in range(len(vpaths))]
            vpathsums = newpathsums
        if len(vpaths)<300:
            ret_dict = add_perm_dict({ep: np.sum(arr) for ep,arr in vpathsums.items()},ret_dict)
        else:
            ret_dict = add_perm_dict(dict(Parallel(n_jobs=-1,require='sharedmem')(delayed(pairsum)(ep,arr) for ep,arr in vpathsums.items())),ret_dict)
    return ret_dict


问:
AWS JavaScript resolver, Unable to convert
Trying JS resolver for the first time, Getting the Unable to convert error,

// Query-listItems-request.js

```<code>import { util } from '@aws-appsync/utils';

export function request(ctx) {
  const { args: { userId } } = ctx;

  return {
    operation: 'Query',
    query: {
      expression: '#id = :id',
      expressionValues: util.dynamodb.toMapValues({ ':id': `${userId}` }),
      expressionNames: { '#id': 'id' },
    },
  };
}

export function response(ctx) {
  return ctx.result;
}

</code>```

AWS Sam tempalte:

```<code>  AppGraphqlApiQueryListBalanceLogsResolver:
    Type: AWS::AppSync::Resolver
    Properties:
      TypeName: Query
      DataSourceName: !GetAtt AppGraphqlApiToListItemDataSource.Name
      RequestMappingTemplateS3Location: Query-listItems-request.js
      ResponseMappingTemplateS3Location: AppGraphqlApi/response.vtl
      ApiId: !Ref AppGraphqlApi
      FieldName: listItems
    DependsOn: AppGraphqlBOApiSchema
</code>```

Body:
Trying JS resolver for the first time, Getting the Unable to convert error,

// Query-listItems-request.js

import { util } from '@aws-appsync/utils';

export function request(ctx) {
  const { args: { userId } } = ctx;

  return {
    operation: 'Query',
    query: {
      expression: '#id = :id',
      expressionValues: util.dynamodb.toMapValues({ ':id': `${userId}` }),
      expressionNames: { '#id': 'id' },
    },
  };
}

export function response(ctx) {
  return ctx.result;
}

AWS Sam tempalte:

  AppGraphqlApiQueryListBalanceLogsResolver:
    Type: AWS::AppSync::Resolver
    Properties:
      TypeName: Query
      DataSourceName: !GetAtt AppGraphqlApiToListItemDataSource.Name
      RequestMappingTemplateS3Location: Query-listItems-request.js
      ResponseMappingTemplateS3Location: AppGraphqlApi/response.vtl
      ApiId: !Ref AppGraphqlApi
      FieldName: listItems
    DependsOn: AppGraphqlBOApiSchema


问:
java.sql.SQLException: Field 'user_id' doesn't have a default value
This error occurs when my Postmapping method tries to save a quiz.
Here's the controller.
`

```<code>@PostMapping("/quizzes")
public Quiz postQuiz(@Valid @RequestBody Quiz quiz) {
    return quizRepo.save(quiz);
}
</code>```

Now here is the User entity whose association is the Quiz entity (it has 5 fields).

```<code>public class User {
    //other fields/columns

    @OneToMany(targetEntity = Quiz.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private List<Quiz> quizzes;
}
</code>```

Theuser_id` field is the foreign key in the quiz table and not a declared field in the Quiz class/entity.

I was thinking just declaring the relationship will populate the foreign key column, in this case user_id, will just be the primary key of the owning entity but it seems at the the time of saving in the PostMapping method, the user_id is null. I've tried anything I possibly can but to no avail.

Body:
This error occurs when my Postmapping method tries to save a quiz.
Here's the controller.
`

@PostMapping("/quizzes")
public Quiz postQuiz(@Valid @RequestBody Quiz quiz) {
    return quizRepo.save(quiz);
}

Now here is the User entity whose association is the Quiz entity (it has 5 fields).

public class User {
    //other fields/columns

    @OneToMany(targetEntity = Quiz.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private List<Quiz> quizzes;
}

Theuser_id` field is the foreign key in the quiz table and not a declared field in the Quiz class/entity.

I was thinking just declaring the relationship will populate the foreign key column, in this case user_id, will just be the primary key of the owning entity but it seems at the the time of saving in the PostMapping method, the user_id is null. I've tried anything I possibly can but to no avail.