问:
snakemake error Command 'set -euo pipefail; Rscript --vanilla meta.R' returned non-zero exit status 1
I am creating a snakemake workflow to download geodatasets. However, I get the following error

```<code>RuleException: CalledProcessError in file /home/sara/sara/Snakefile, line 8: Command 'set -euo pipefail; Rscript --vanilla /home/sara/sara/.snakemake/scripts/tmps2lv_wlb.meta.R' returned non-zero exit status 1.
File "/home/sara/sara/Snakefile", line 8, in __rule_download
File"/home/sara/mambaforge/envs/snakemake/lib/python3.11/concurrent/futures/thread.py", line 58, in run Shutting down, this might take some time. Exiting because a job execution failed. Look above for error message
</code>```

Here is my snakemake file

```<code>configfile: "config.yml"
rule download:
    output:
        dir= directory("/home/sara/sara/downloads/")
    params:
        sample=config["Samples"]
    script:
        "scripts/meta.R"
</code>```

Here is my config.yml

```<code>env:
            - bioconductor-oligo
            - bioconducor-GEOquery
channels:
            - conda-forge
            - bioconda
Samples:
            - "GSE6955"
            - "GSE67311"
</code>```

Here is the Rscript

```<code>library(GEOquery)
getGEOSuppFiles(snakemakege@params[sample],baseDir = snakemake@output[dir])
</code>```

Body:
I am creating a snakemake workflow to download geodatasets. However, I get the following error

RuleException: CalledProcessError in file /home/sara/sara/Snakefile, line 8: Command 'set -euo pipefail; Rscript --vanilla /home/sara/sara/.snakemake/scripts/tmps2lv_wlb.meta.R' returned non-zero exit status 1.
File "/home/sara/sara/Snakefile", line 8, in __rule_download
File"/home/sara/mambaforge/envs/snakemake/lib/python3.11/concurrent/futures/thread.py", line 58, in run Shutting down, this might take some time. Exiting because a job execution failed. Look above for error message

Here is my snakemake file

configfile: "config.yml"
rule download:
    output:
        dir= directory("/home/sara/sara/downloads/")
    params:
        sample=config["Samples"]
    script:
        "scripts/meta.R"

Here is my config.yml

env:
            - bioconductor-oligo
            - bioconducor-GEOquery
channels:
            - conda-forge
            - bioconda
Samples:
            - "GSE6955"
            - "GSE67311"

Here is the Rscript

library(GEOquery)
getGEOSuppFiles(snakemakege@params[sample],baseDir = snakemake@output[dir])


来源: stackexchange

问:
Copy & Pasted CSS from Chrome and the CSS does not exist
I am currently trying to write a code that scrapes a mileage after logging into a specific website using CSS selector and bs4 in Google Colab (python). I have copied and pasted the CSS of the value that I would like to scrape as follows and wrote a code:

```<code>point = soup.select_one("#commonMypage > section > div.common-mypage__sc-5trtbg-3.JsGLX > div.common-mypage__sc-1m1vyak-0.fJZyji > a:nth-child(2) > strong").get_text()

</code>```

and it results in following error: AttributeError: 'NoneType' object has no attribute 'get_text'

As far as I know, beautifulsoup does not support nth-child and I assume that there should be some modification with the CSS selector. I would like to know how to modify the selector such that it works in common environment.

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to write a code that scrapes a mileage after logging into a specific website using CSS selector and bs4 in Google Colab (python). I have copied and pasted the CSS of the value that I would like to scrape as follows and wrote a code:

point = soup.select_one("#commonMypage > section > div.common-mypage__sc-5trtbg-3.JsGLX > div.common-mypage__sc-1m1vyak-0.fJZyji > a:nth-child(2) > strong").get_text()

and it results in following error: AttributeError: 'NoneType' object has no attribute 'get_text'

As far as I know, beautifulsoup does not support nth-child and I assume that there should be some modification with the CSS selector. I would like to know how to modify the selector such that it works in common environment.


问:
How can i add data to specific row in TableView?
I'm trying to add data to tableview repeatedly. But it doesn't append the data, it just overwrites it. How can i append the data to tableview without deleting old data from the table? Is there any way for me to tell to the program that the row it's trying to write on is not empty?

UserController Class

```<code>package entropy.myproject1;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.util.ResourceBundle;

public class UsersController implements Initializable {

    @FXML
    private TableColumn<User, Integer> colID;

    @FXML
    private TableColumn<User, String> colPassword;

    @FXML
    private TableColumn<User, String> colUsername;

    @FXML
    private TableView<User> table;

    RegisterController registerController = RegisterController.getInstance();
    ObservableList<User> userList = FXCollections.observableArrayList(
        new User(registerController.registeredUser.getId(),registerController.registeredUser.getUsername(),registerController.registeredUser.getPassword())
    );

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        colID.setCellValueFactory(new PropertyValueFactory<User,Integer>("id"));
        colUsername.setCellValueFactory(new PropertyValueFactory<User,String >("username"));
        colPassword.setCellValueFactory(new PropertyValueFactory<User,String>("password"));
        table.setItems(userList);
    }
}

</code>```

Register Controller Class

```<code>package entropy.myproject1;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class RegisterController {
    private Stage stage;
    private Scene scene;
    private static final RegisterController instance = new RegisterController();
    public static RegisterController getInstance(){
        return instance;
    }

    @FXML
    private Button buttonAdd;

    @FXML
    private TextField tfID;

    @FXML
    private TextField tfPassword;

    @FXML
    private TextField tfUsername;
    public User registeredUser = User.getInstance();
    @FXML
    void addOnClick(ActionEvent event){
        registeredUser.setId(Integer.parseInt(tfID.getText()));
        registeredUser.setUsername(tfUsername.getText());
        registeredUser.setPassword(tfPassword.getText());
        System.out.println(registeredUser.toString());
    }
    @FXML
    void showListOnClick(ActionEvent event) throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("userspage.fxml"));
        stage = (Stage)((Node)event.getSource()).getScene().getWindow();
        scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("User List");
        stage.show();
    }
}
</code>```

User Class

```<code>package entropy.myproject1;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

public class User {
    private SimpleIntegerProperty id;
    private SimpleStringProperty username;
    private SimpleStringProperty password;
    private static final User instance = new User();

    public User(Integer id, String username, String password) {
        this.id =new SimpleIntegerProperty(id);
        this.username =new SimpleStringProperty(username);
        this.password = new SimpleStringProperty(password);
    }

    public User() {
    }

    public int getId() {
        return id.get();
    }

    public String getUsername() {
        return username.get();
    }

    public String getPassword() {
        return password.get();
    }

    public void setId(int id) {
        this.id = new SimpleIntegerProperty(id);
    }

    public void setUsername(String username) {
        this.username = new SimpleStringProperty(username);
    }

    public void setPassword(String password) {
        this.password = new SimpleStringProperty(password);
    }
    public static User getInstance(){
        return instance;
    }
    public String toString(){
        return id+" "+username+" "+password;
    }
}

</code>```

Body:
I'm trying to add data to tableview repeatedly. But it doesn't append the data, it just overwrites it. How can i append the data to tableview without deleting old data from the table? Is there any way for me to tell to the program that the row it's trying to write on is not empty?

UserController Class

package entropy.myproject1;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.util.ResourceBundle;

public class UsersController implements Initializable {

    @FXML
    private TableColumn<User, Integer> colID;

    @FXML
    private TableColumn<User, String> colPassword;

    @FXML
    private TableColumn<User, String> colUsername;

    @FXML
    private TableView<User> table;

    RegisterController registerController = RegisterController.getInstance();
    ObservableList<User> userList = FXCollections.observableArrayList(
        new User(registerController.registeredUser.getId(),registerController.registeredUser.getUsername(),registerController.registeredUser.getPassword())
    );

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        colID.setCellValueFactory(new PropertyValueFactory<User,Integer>("id"));
        colUsername.setCellValueFactory(new PropertyValueFactory<User,String >("username"));
        colPassword.setCellValueFactory(new PropertyValueFactory<User,String>("password"));
        table.setItems(userList);
    }
}

Register Controller Class

package entropy.myproject1;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class RegisterController {
    private Stage stage;
    private Scene scene;
    private static final RegisterController instance = new RegisterController();
    public static RegisterController getInstance(){
        return instance;
    }

    @FXML
    private Button buttonAdd;

    @FXML
    private TextField tfID;

    @FXML
    private TextField tfPassword;

    @FXML
    private TextField tfUsername;
    public User registeredUser = User.getInstance();
    @FXML
    void addOnClick(ActionEvent event){
        registeredUser.setId(Integer.parseInt(tfID.getText()));
        registeredUser.setUsername(tfUsername.getText());
        registeredUser.setPassword(tfPassword.getText());
        System.out.println(registeredUser.toString());
    }
    @FXML
    void showListOnClick(ActionEvent event) throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("userspage.fxml"));
        stage = (Stage)((Node)event.getSource()).getScene().getWindow();
        scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("User List");
        stage.show();
    }
}

User Class

package entropy.myproject1;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

public class User {
    private SimpleIntegerProperty id;
    private SimpleStringProperty username;
    private SimpleStringProperty password;
    private static final User instance = new User();

    public User(Integer id, String username, String password) {
        this.id =new SimpleIntegerProperty(id);
        this.username =new SimpleStringProperty(username);
        this.password = new SimpleStringProperty(password);
    }

    public User() {
    }

    public int getId() {
        return id.get();
    }

    public String getUsername() {
        return username.get();
    }

    public String getPassword() {
        return password.get();
    }

    public void setId(int id) {
        this.id = new SimpleIntegerProperty(id);
    }

    public void setUsername(String username) {
        this.username = new SimpleStringProperty(username);
    }

    public void setPassword(String password) {
        this.password = new SimpleStringProperty(password);
    }
    public static User getInstance(){
        return instance;
    }
    public String toString(){
        return id+" "+username+" "+password;
    }
}


问:
Value assignment and debugging in Clojure
I am trying to add a section to a Clojure code. After line no. 99 of the below code:

https://github.com/lspector/Clojush/blob/master/src/clojush/pushgp/breed.clj

I want to add these codes:

```<code>   (if (= num-parents 2)
       (let [initial-other-parents (vec (repeatedly
                                   (+ num-parents 4)     ; selecting parents more than required by 4
                                           (fn []
                                             (loop [re-selections 0
                                                    other (select population argmap)]
                                               (if (and (= other first-parent)
                                                        (< re-selections
                                                           (:self-mate-avoidance-limit argmap)))
                                                 (recur (inc re-selections)
                                                        (select population argmap))
                                                 other)))))

         all-parents (concat (if (nil? first-parent)     ;gathering all created parents
                                   nil
                                   (vector first-parent))
                                 initial-other-parents)

        (defn eclid-dist [u v]                            ;defining a function to calculate distances
          (->> (mapv - u v)
               (mapv #(Math/pow % 2))
               (reduce +)
               Math/sqrt))

        (defn find-largest-dist-pair [vec-map]             ;defining a function to return two vectors (parents) with the largest distance
          (apply max-key second
                 (for [[[k0 v0] & r] (iterate rest vec-map)
                       :while r
                       [k1 v1] r]
                   [[k0 k1] (eclid-dist v0 v1)])))

         final-parents (find-largest-dist-pair (:error all-parents)) ;selecting two parents with the largest distance

        op-fn (:fn (get genetic-operators operator))                     ; extracting the operator

        child (apply op-fn (concat final-parents                         ; creating child
                                   (vector (assoc argmap
                                                  :population population))))]

        )
</code>```

For running the added part line by line, I extracted values before the changes using adding the below code after line 84 of the main code:

```<code> (spit "initial-setting.edn" {:operator-list operator-list
                            :first-parent first-parent
                            :population population
                            :location location
                            :rand-gen rand-gen
                            :argmap argmap})
</code>```

My question is:

what is the best way to assign extracted values by "spit" to variables and execute the added section line by line for debugging?
I am using Calva as IDE and tried to put #break and use lein to run the code and debug it but it did not work. Here is my pervious post on that:
How to set a breakpoint in a Clojure program using Calva?

Body:
I am trying to add a section to a Clojure code. After line no. 99 of the below code:

https://github.com/lspector/Clojush/blob/master/src/clojush/pushgp/breed.clj

I want to add these codes:

   (if (= num-parents 2)
       (let [initial-other-parents (vec (repeatedly
                                   (+ num-parents 4)     ; selecting parents more than required by 4
                                           (fn []
                                             (loop [re-selections 0
                                                    other (select population argmap)]
                                               (if (and (= other first-parent)
                                                        (< re-selections
                                                           (:self-mate-avoidance-limit argmap)))
                                                 (recur (inc re-selections)
                                                        (select population argmap))
                                                 other)))))

         all-parents (concat (if (nil? first-parent)     ;gathering all created parents
                                   nil
                                   (vector first-parent))
                                 initial-other-parents)

        (defn eclid-dist [u v]                            ;defining a function to calculate distances
          (->> (mapv - u v)
               (mapv #(Math/pow % 2))
               (reduce +)
               Math/sqrt))

        (defn find-largest-dist-pair [vec-map]             ;defining a function to return two vectors (parents) with the largest distance
          (apply max-key second
                 (for [[[k0 v0] & r] (iterate rest vec-map)
                       :while r
                       [k1 v1] r]
                   [[k0 k1] (eclid-dist v0 v1)])))

         final-parents (find-largest-dist-pair (:error all-parents)) ;selecting two parents with the largest distance

        op-fn (:fn (get genetic-operators operator))                     ; extracting the operator

        child (apply op-fn (concat final-parents                         ; creating child
                                   (vector (assoc argmap
                                                  :population population))))]

        )

For running the added part line by line, I extracted values before the changes using adding the below code after line 84 of the main code:

 (spit "initial-setting.edn" {:operator-list operator-list
                            :first-parent first-parent
                            :population population
                            :location location
                            :rand-gen rand-gen
                            :argmap argmap})

My question is:

what is the best way to assign extracted values by "spit" to variables and execute the added section line by line for debugging?
I am using Calva as IDE and tried to put #break and use lein to run the code and debug it but it did not work. Here is my pervious post on that:
How to set a breakpoint in a Clojure program using Calva?


问:
socat localhost proxy with 'Connection refused'
I want to play with socat to setup a localhost proxy , which could redirect my request from local proxy I setup to a remote server.
Below are 2 commands I try (by google)

Command 1: works right on localhost

start socat server

```<code>socat -d  TCP6-LISTEN:8080,fork,reuseaddr TCP4:drsol.com:80
</code>```

client connect socat server

```<code>curl -I -6 http://localhost:8080/
HTTP/1.1 200 OK
Date: Sun, 25 Dec 2022 13:06:11 GMT
Server: Apache/2.2.15 (CentOS)
Last-Modified: Tue, 10 Jun 2014 17:35:11 GMT
ETag: "2482ce4-2-4fb7ebff1050b"
Accept-Ranges: bytes
Content-Length: 2
Connection: close
Content-Type: text/html; charset=UTF-8
</code>```

Command 2: 'Connection refused' error on localhost server terminal

setup socat server

```<code>socat TCP6-LISTEN:8000 PROXY:localhost:drsol.com:80,proxyport=8080
</code>```

connect socat server

```<code>curl -v http://localhost:8000/
* STATE: INIT => CONNECT handle 0x55fce853a968; line 1789 (connection #-5000)
* Uses proxy env variable no_proxy == 'localhost,127.0.0.0/8,::1'
* Added connection 0. The cache now contains 1 members
* family0 == v4, family1 == v6
*   Trying 127.0.0.1:8000...
* STATE: CONNECT => CONNECTING handle 0x55fce853a968; line 1850 (connection #0)
* Connected to localhost (127.0.0.1) port 8000 (#0)
* STATE: CONNECTING => PROTOCONNECT handle 0x55fce853a968; line 1982 (connection #0)
* STATE: PROTOCONNECT => DO handle 0x55fce853a968; line 2003 (connection #0)
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.80.0
> Accept: */*
>
* STATE: DO => DID handle 0x55fce853a968; line 2099 (connection #0)
* STATE: DID => PERFORMING handle 0x55fce853a968; line 2218 (connection #0)
* STATE: PERFORMING => DONE handle 0x55fce853a968; line 2417 (connection #0)
* multi_done
* Empty reply from server
* The cache now contains 0 members
* Closing connection 0
* Expire cleared (transfer 0x55fce853a968)
curl: (52) Empty reply from server
</code>```

on the socat server terminal "Connection refused"

```<code>2022/12/25 21:10:42 socat[46697] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused
</code>```

My question is : what was the difference between command 1 and command 2 , and why the connection refused happend on command 2?
(I am new to socat and on my way of learning it)

Body:
I want to play with socat to setup a localhost proxy , which could redirect my request from local proxy I setup to a remote server.
Below are 2 commands I try (by google)

Command 1: works right on localhost

start socat server

socat -d  TCP6-LISTEN:8080,fork,reuseaddr TCP4:drsol.com:80

client connect socat server

curl -I -6 http://localhost:8080/
HTTP/1.1 200 OK
Date: Sun, 25 Dec 2022 13:06:11 GMT
Server: Apache/2.2.15 (CentOS)
Last-Modified: Tue, 10 Jun 2014 17:35:11 GMT
ETag: "2482ce4-2-4fb7ebff1050b"
Accept-Ranges: bytes
Content-Length: 2
Connection: close
Content-Type: text/html; charset=UTF-8

Command 2: 'Connection refused' error on localhost server terminal

setup socat server

socat TCP6-LISTEN:8000 PROXY:localhost:drsol.com:80,proxyport=8080

connect socat server

curl -v http://localhost:8000/
* STATE: INIT => CONNECT handle 0x55fce853a968; line 1789 (connection #-5000)
* Uses proxy env variable no_proxy == 'localhost,127.0.0.0/8,::1'
* Added connection 0. The cache now contains 1 members
* family0 == v4, family1 == v6
*   Trying 127.0.0.1:8000...
* STATE: CONNECT => CONNECTING handle 0x55fce853a968; line 1850 (connection #0)
* Connected to localhost (127.0.0.1) port 8000 (#0)
* STATE: CONNECTING => PROTOCONNECT handle 0x55fce853a968; line 1982 (connection #0)
* STATE: PROTOCONNECT => DO handle 0x55fce853a968; line 2003 (connection #0)
> GET / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.80.0
> Accept: */*
>
* STATE: DO => DID handle 0x55fce853a968; line 2099 (connection #0)
* STATE: DID => PERFORMING handle 0x55fce853a968; line 2218 (connection #0)
* STATE: PERFORMING => DONE handle 0x55fce853a968; line 2417 (connection #0)
* multi_done
* Empty reply from server
* The cache now contains 0 members
* Closing connection 0
* Expire cleared (transfer 0x55fce853a968)
curl: (52) Empty reply from server

on the socat server terminal "Connection refused"

2022/12/25 21:10:42 socat[46697] E connect(5, AF=2 127.0.0.1:8080, 16): Connection refused

My question is : what was the difference between command 1 and command 2 , and why the connection refused happend on command 2?
(I am new to socat and on my way of learning it)


问:
Delete values from second column alongside the values from first column in the same row between two database tables
I am trying to delete the same id between two tables. And deleting a storage file by getting the image file value.
For example procedure:
user_id(table1)->user_id(table2)->avatar->file name-> delete images-> delete all data from same user_id between first table and second table

I have two tables,

```<code>*user* table
| user_id  | Full_name      |
| -------- | -------------- |
| 1        | Steve Jobs     |
| 2        | Bill Gates     |
| 3        | Elon Musk      |

*users_option* table (with both column foreign keys)
|   user_id    | user_option    | user_value           |
| ------------ | -------------- | --------------       |
| 1            | email          | abc@abc.com          |
| 1            | avatar         | 'big.jpg','sml.png'  |
| 1            | username       | stevejobs            |
| 2            | email          | def@def.com          |
| 2            | avatar         | 'big.png','sml.jpeg' |
| 2            | username       | billgates            |
</code>```

I am hardly writing this code with ORM MySQL

```<code>ORM::table($config['db']['pre'].'user')
ORM::table($config['db']['pre'].'user_option')
</code>```

Simply that, I just want completely delete all the data from the same user_id.

I just want completely delete all the data from the same user_id.

Body:
I am trying to delete the same id between two tables. And deleting a storage file by getting the image file value.
For example procedure:
user_id(table1)->user_id(table2)->avatar->file name-> delete images-> delete all data from same user_id between first table and second table

I have two tables,

*user* table
| user_id  | Full_name      |
| -------- | -------------- |
| 1        | Steve Jobs     |
| 2        | Bill Gates     |
| 3        | Elon Musk      |

*users_option* table (with both column foreign keys)
|   user_id    | user_option    | user_value           |
| ------------ | -------------- | --------------       |
| 1            | email          | abc@abc.com          |
| 1            | avatar         | 'big.jpg','sml.png'  |
| 1            | username       | stevejobs            |
| 2            | email          | def@def.com          |
| 2            | avatar         | 'big.png','sml.jpeg' |
| 2            | username       | billgates            |

I am hardly writing this code with ORM MySQL

ORM::table($config['db']['pre'].'user')
ORM::table($config['db']['pre'].'user_option')

Simply that, I just want completely delete all the data from the same user_id.

I just want completely delete all the data from the same user_id.


问:
Limit users from multiple likes on a post using php and mysql
The main problem is every time the users will click the heart button for likes, they can spam the like button and the likes will also increase every time you click the like button.

here's my php code:

`

```<code><?php
    if(isset($_POST['how'])){
        session_start();
        $user_id=$_SESSION['userId'];
        $post_id=$_POST['data'];
        $con = new mysqli("localhost","root","","tattoo_db");
        $sql1="SELECT  `design_id`, `count` FROM `works` WHERE design_id='$user_id' and
        count='$post_id'";
        $res=$con->query($sql1);
        if($res->num_rows == 0){
            $sql2="UPDATE `works` SET `count`=count+1 WHERE design_id='$post_id'";
            if($con->query($sql2)){
                $sql3="INSERT INTO `works`(`design_id`, `count`) VALUES ('$user_id','$post_id)";
                    if($con->query($sql3)){
                        echo "liked";
                    }
            }
        }else if($res->num_rows==1){
            $sql2="UPDATE `works` SET `count`=count-1 WHERE design_id='$post_id'";
            if($con->query($sql2)){
                $sql3="DELETE FROM `works` WHERE design_id='$user_id' and count='$post_id'";
                    if($con->query($sql3)){
                        echo "disliked";
                    }
            }
        }
    }

?>
</code>```

`

and this is my javascript code:

`

```<code>$(document).ready(function(){
        $(".like").click(function(){
            var design_id=$(this).attr("title");
            var i=$(this).children(".like_icon").attr("src");
            if(i=="admin/works/heart.svg"){
                $(this).children(".like_icon").attr("src","admin/works/red-heart.svg");
                $(this).children("span").text("liked");
            }else if(i=="admin/works/red-heart.svg"){
                $(this).children(".like_icon").attr("src","admin/works/heart.svg");
                $(this).children("span").text("unliked");
            }
            $.post("header/get.php",{data:design_id,how:'c'});
        });
    });

</code>```

`

I want to limit the users to one per like to prevent multiple likes from every users when they click the like button.

Body:
The main problem is every time the users will click the heart button for likes, they can spam the like button and the likes will also increase every time you click the like button.

here's my php code:

`

<?php
    if(isset($_POST['how'])){
        session_start();
        $user_id=$_SESSION['userId'];
        $post_id=$_POST['data'];
        $con = new mysqli("localhost","root","","tattoo_db");
        $sql1="SELECT  `design_id`, `count` FROM `works` WHERE design_id='$user_id' and
        count='$post_id'";
        $res=$con->query($sql1);
        if($res->num_rows == 0){
            $sql2="UPDATE `works` SET `count`=count+1 WHERE design_id='$post_id'";
            if($con->query($sql2)){
                $sql3="INSERT INTO `works`(`design_id`, `count`) VALUES ('$user_id','$post_id)";
                    if($con->query($sql3)){
                        echo "liked";
                    }
            }
        }else if($res->num_rows==1){
            $sql2="UPDATE `works` SET `count`=count-1 WHERE design_id='$post_id'";
            if($con->query($sql2)){
                $sql3="DELETE FROM `works` WHERE design_id='$user_id' and count='$post_id'";
                    if($con->query($sql3)){
                        echo "disliked";
                    }
            }
        }
    }

?>

`

and this is my javascript code:

`

$(document).ready(function(){
        $(".like").click(function(){
            var design_id=$(this).attr("title");
            var i=$(this).children(".like_icon").attr("src");
            if(i=="admin/works/heart.svg"){
                $(this).children(".like_icon").attr("src","admin/works/red-heart.svg");
                $(this).children("span").text("liked");
            }else if(i=="admin/works/red-heart.svg"){
                $(this).children(".like_icon").attr("src","admin/works/heart.svg");
                $(this).children("span").text("unliked");
            }
            $.post("header/get.php",{data:design_id,how:'c'});
        });
    });

`

I want to limit the users to one per like to prevent multiple likes from every users when they click the like button.


问:
Github repo directory rename doesn't work in github Desktop
I don't know why the directory renamed from "originalProject" to "originalproject" exists as both names while successfully pushed files look like this:in my local repository
But in my github account the directory seems strange.
in my Github repsitory
Can you help with this?

I tried to make the  files look clean and rename folders to make all lowercase then I commited and pushed using Github desktop but the github repo looks different from actual repo.


问:
Android Studio shape xml file - no transparency in the background
My xml file is as follows :

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topRightRadius="50dp"
        android:topLeftRadius="50dp"
        />
    <solid
        android:color="@color/quantum_grey"
        />
</shape>
</code>```

Please help me :(

I gave the background color, But it was by no means transparent.

Body:
My xml file is as follows :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topRightRadius="50dp"
        android:topLeftRadius="50dp"
        />
    <solid
        android:color="@color/quantum_grey"
        />
</shape>

Please help me :(

I gave the background color, But it was by no means transparent.


问:
Apex chart not changing colors when using candlestick chart
I am using apex charts to develop charts for the stock market and in the backend I use Django. I have a problem with changing the colors of candlesticks. I have multiple stocks with years of data and on some stocks, chart colors are correctly displayed but on most of them, they are displayed incorrectly. I have no idea what is causing this and how to fix this. Any idea?

Chart code:

```<code>    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart">

</div>
<script>

    var options = {
        series: [{
            name: 'OHLC',

            type: 'candlestick',

            data: [
                {% for stock in stocks %}
{
            x: "{{stock.date}}",
            y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"],

        },
        {% endfor %}
        ]
    },

],
    chart: {

        id: 'chart_1',
            group: 'social',

                type: 'candlestick',
                    height: 900

    },

    title: {
        text: '{{ticker}} Stock ',
            align: 'center'
    },

    yaxis: {
        tooltip: {
            enabled: true
        }
    }

};

    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();
</script>
</code>```

With this part of django template:

```<code>    {% for stock in stocks %}
{
            x: "{{stock.date}}",
            y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"],

        },
        {% endfor %}
</code>```

I am looping through a list of data that I have in the backend filtered from the database.

This is how chart looks like with incorrect colors:

Data is displayed correctly but not colors

And this is another stock where data is displayed correctly:

Body:
I am using apex charts to develop charts for the stock market and in the backend I use Django. I have a problem with changing the colors of candlesticks. I have multiple stocks with years of data and on some stocks, chart colors are correctly displayed but on most of them, they are displayed incorrectly. I have no idea what is causing this and how to fix this. Any idea?

Chart code:

With this part of django template:

    {% for stock in stocks %}
{
            x: "{{stock.date}}",
            y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"],

        },
        {% endfor %}

I am looping through a list of data that I have in the backend filtered from the database.

This is how chart looks like with incorrect colors:

Data is displayed correctly but not colors

And this is another stock where data is displayed correctly:


问:
Accessing public static final String constants in EL

Possible Duplicate:

  How to reference constants in EL?

I have a Seam JSF application. I have a Constants.java class which has

```<code>public static final String BLAH_STR = "HA_HA";
</code>```

I have to use BLAH_STR in EL. #{Constants.BLAH_STR} is not working. I have not defined Constants.java as a Seam class. How can I solve it?

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How to reference constants in EL?

I have a Seam JSF application. I have a Constants.java class which has

public static final String BLAH_STR = "HA_HA";

I have to use BLAH_STR in EL. #{Constants.BLAH_STR} is not working. I have not defined Constants.java as a Seam class. How can I solve it?


问:
Convert 1D python list consisting of 2D lists to 3D list for Keras
I wonder how to efficiently convert a python list of (3000,) containing 2D lists of (3, x) with x being a variable length, to a 3D list or numpy array of (3000, 3, x) that can be used as input for Keras LSTM.

What I have: list - (3000,) with each (3,x)

What I need: list - (3000, 3, x)

Thank you!


问:
Queuing deep learning training Jobs on a shared server
We have multiple GPU servers for deep learning training.  We train our code inside Docker containers.

Today every user can log into these machines interactively and run a job.  There is no restriction on job duration, or how many GPUs one can allocate. We haggle over GPUs via a chat channel.

What's the simplest framework for queuing jobs and allocating them to GPUs?  I'm looking for GPU-level granularity, and am fine with multiple user running on the same machine.

The desired workflow is:

Allocate GPU

Create docker container

Run job (and grab requirements on top of vanilla container if necessary).  Can be a bash file?

Finish job / kill job if running too long and close container

Additionally, I'd like an interactive workflow similar to the above, where the time limits are reduced (say, 2 hours max of interactive time?)

I'd like to prevent someone from hogging a machine for a week, so a job should have a finite runtime and be killed afterward.  Also, multiple people shouldn't be able to use the same GPU simultaneously.

I realize I can do this with a cron job that monitors and kills jobs, but am looking for something  more elegant, readymade, and preferably with a nice UI.  I've tried ClearML, but can't figure out how to use it for this purpose.  I know SLURM is used for allocating entire machines. It's unclear to me if it's possible to allocate specific GPUs.


问:
Need reactjs code such that when the docId my url :/<docId> changes, it fetches data from firebase and populates it
Firebase Collection : 'Data'. Within data you have the docIds.
As of now, I wrote this

```<code>const fetchProduct = async ()=> { // <------ async
  const docId = window.location.href.split('/').pop();
  console.log(docId,"Ok")
  if(docId != ""){
    console.log(docId)
    let userDoc = await getDoc(doc(db, 'Notes', docId))
    console.log(userDoc);
    userDoc = userDoc.data().content; // <------ await
    console.log(userDoc);
    userDoc = userDoc.exists; // <------ exists not exists();
  }
}

useEffect(async () => {
  (async () => {
    await fetchProduct()
  })();
}, [window.location.href]); // Only run the effect if the url changes
</code>```

Eg. If url is  url :/hhFQaRx0RaCCGokkFMz
It should fetch data from docId=hhFQaRx0RaCCGokkFMz , which can be then used to populated textBox ith id='MyBox1'
Error:

My full code of this section: error causing part in comment section

```<code>import React from "react"
import { db } from "../firebase-config";
import { useState,useEffect } from "react";

import {
  collection,
  getDoc,
  doc
} from "firebase/firestore";

export default function Navbar(props){

  const [textSearch, settextSearch] = useState('');

  const handleGet = async(e)=>{
    e.preventDefault();

    try {

        const snap = await getDoc(doc(db, 'Notes', textSearch.trim()))
        if (snap.exists()) {
          console.log(snap.data())
          settextSearch(snap.data().content);
          document.getElementById("myBox1").value = snap.data().content;
        }
        else {
          console.log("No such document")
          alert("No such document")
        }
      } catch(error) {
          alert("Error")
          console.log(error)
      }

}
/*
const fetchProduct = async ()=> { // <------ async
  const docId = window.location.href.split('/').pop();
  console.log(docId,"Ok")
  if(docId != ""){
  console.log(docId)
  let userDoc = await getDoc(doc(db, 'Notes', docId))
  console.log(userDoc);
  userDoc = userDoc.data().content; // <------ await
  console.log(userDoc);
  userDoc = userDoc.exists; // <------ exists not exists();
  }
}

useEffect(async () => {
  (async () => {
    await fetchProduct()
  })();
}, [window.location.href]); // Only run the effect if the url changes

*/
  const handleOnChange = (event)=>{
    // console.log("On change");
    settextSearch(event.target.value)
}

    return(
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
        <div className="container-fluid">
        <a className="navbar-brand">{props.title}</a>
        <form className="d-flex">
          <input className="form-control mr-sm-2"  value={textSearch} onChange={handleOnChange} type="search" placeholder="Search" aria-label="Search"/>
          <button className="btn btn-outline-success my-2 my-sm-0" onClick={handleGet} type="submit">Search</button>
        </form>
        </div>
      </nav>
    );
}
</code>```

Title: Need reactjs code such that when the docId my url :<main.com>/<docId> changes, it fetches data from firebase and populates it

Body:
Firebase Collection : 'Data'. Within data you have the docIds.
As of now, I wrote this

const fetchProduct = async ()=> { // <------ async
  const docId = window.location.href.split('/').pop();
  console.log(docId,"Ok")
  if(docId != ""){
    console.log(docId)
    let userDoc = await getDoc(doc(db, 'Notes', docId))
    console.log(userDoc);
    userDoc = userDoc.data().content; // <------ await
    console.log(userDoc);
    userDoc = userDoc.exists; // <------ exists not exists();
  }
}

useEffect(async () => {
  (async () => {
    await fetchProduct()
  })();
}, [window.location.href]); // Only run the effect if the url changes

Eg. If url is  url :/hhFQaRx0RaCCGokkFMz
It should fetch data from docId=hhFQaRx0RaCCGokkFMz , which can be then used to populated textBox ith id='MyBox1'
Error:

My full code of this section: error causing part in comment section

import React from "react"
import { db } from "../firebase-config";
import { useState,useEffect } from "react";

import {
  collection,
  getDoc,
  doc
} from "firebase/firestore";

export default function Navbar(props){

  const [textSearch, settextSearch] = useState('');

  const handleGet = async(e)=>{
    e.preventDefault();

    try {

        const snap = await getDoc(doc(db, 'Notes', textSearch.trim()))
        if (snap.exists()) {
          console.log(snap.data())
          settextSearch(snap.data().content);
          document.getElementById("myBox1").value = snap.data().content;
        }
        else {
          console.log("No such document")
          alert("No such document")
        }
      } catch(error) {
          alert("Error")
          console.log(error)
      }

}
/*
const fetchProduct = async ()=> { // <------ async
  const docId = window.location.href.split('/').pop();
  console.log(docId,"Ok")
  if(docId != ""){
  console.log(docId)
  let userDoc = await getDoc(doc(db, 'Notes', docId))
  console.log(userDoc);
  userDoc = userDoc.data().content; // <------ await
  console.log(userDoc);
  userDoc = userDoc.exists; // <------ exists not exists();
  }
}

useEffect(async () => {
  (async () => {
    await fetchProduct()
  })();
}, [window.location.href]); // Only run the effect if the url changes

*/
  const handleOnChange = (event)=>{
    // console.log("On change");
    settextSearch(event.target.value)
}

    return(

        {props.title}
        <form className="d-flex">
          <input className="form-control mr-sm-2"  value={textSearch} onChange={handleOnChange} type="search" placeholder="Search" aria-label="Search"/>
          <button className="btn btn-outline-success my-2 my-sm-0" onClick={handleGet} type="submit">Search</button>
        </form>

    );
}


问:
Magnific Popup showing same item
Refering to this question , it has a helpful answer but it's partial answer because it only shows three unique popup dialogs - static.

I'm new to jQuery and working in this project. I want this to be dynamic with MySql database. Let's say I have a collection of 20 products stored in a tbl_products and each product has a uniqe id, name and price. When user clicks for more product details, I want to display the Magnific popup dialog that shows the product details, showing the product image(small thumbnail), product name and product price.

This link is inside loop:

">Open with fade-zoom animation

Here is the Code:

```<code><div class="page-content">

        <?php
                $query = "SELECT * FROM tbl_product ORDER BY product_id ASC LIMIT 20";
                        $result = mysqli_query($connect, $query);
                        $ctr = 0;
                if(mysqli_num_rows($result) > 0)
                {
                    $i = 0;
                    $param = 'right';
                    while($row = mysqli_fetch_array($result))
                    {
                        //echo "<h2>" . $row[0] . "</h2>";
                        $data = $row["product_image"];
                        $images = explode(";", $data);
                        if($param=='left'){
                            $param = "right";
                        }
                        else{
                            $param = "left";
                            ?><div class="clear"></div><?php
                        }

                        ?>
                        <a class="popup-with-zoom-anim" href="#small-dialog" data-item="<?php echo $row["product_id"]; ?>">Open with fade-zoom animation</a><br>

                            <div id="small-dialog" class="zoom-anim-dialog mfp-hide">
                            <span class="fa fa-check fa-3x" style="color: black; margin-left:45%;"></span>
                                <h3 style="text-align:center; margin-top:0px;margin-bottom:20px;">Artikulli u shtua në shportë</h3>

                                <div class="table-responsive" style="border: none !important;">
                                            <table style="border: none !important;">
                                                <tr>
                                                    <th width="80%"></th>
                                                    <th width="20%"></th>
                                                </tr>
                                                <tr>
                                                    <td style="font-size:12px;">

                                                        <div class="news-thumbs" style="margin-left:0px; margin-right:20px;">
                                                            <a href="#" class="news-item">
                                                                <div style="line-height: 0.5cm;border: 1px solid #ccc; margin-bottom:5px; width:100%; height:110px; border-radius: 10px;  overflow: hidden; box-shadow: 0 2px 5px 1px rgba(0,0,0,0.1);">
                                                                <amp-img class="responsive-img" src="../../../../../images/images/gallery/preview/<?php echo $images[0]; ?>" width="100" height="100" layout="responsive"></amp-img>
                                                                <h5><?php echo $row[1];?></h5>
                                                                <p style "font-size:11px;">
                                                                    <?php
                                                                        foreach(range(1, $row[10]) as $i)
                                                                        {
                                                                            ?>
                                                                                <span class="fa fa-star checked" style="color: #ffa500;"></span>
                                                                            <?php
                                                                        }
                                                                    ?>
                                                                </p>
                                                                </div>
                                                            </a>
                                                        </div>
                                                    </td>

                                                    <td style="margin-left:-50px; font-size:28px; font-style:bold; line-height:20px;">€<?php echo $row[2];?> <br>
                                                        <p style="font-size:11px; font-style:bold;">TVSH - 8% </p>
                                                        <p style="font-size:10px; line-height:20px;">Dërgesa Falas</p>
                                                        <a href="m-detail-<?php echo $row[0]; ?>.html" style="font-size:11px; line-height:20px;"> Shiko detalet</a>
                                                    </td>
                                                    <td style="font-size:12px;"> </td>
                                                </tr>

                                            </table>
                                        </div>

                                        <hr style="border-top: 0.5px solid #E8E8FF;">
                                    <button type="button" class="btn btn-default popup-modal-dismiss">Vazhdo me blerje</button>
                                    <button type="button" style="float:right;" class="btn btn-primary">Kryje porosinë</button>
                                 <!-- </div>
                                <div class="news-thumbs" style="margin-left:-50px;">
                                    <a href="#" class="news-item">
                                        <div style="line-height: 0.5cm;border: 1px solid #ccc; margin-bottom:5px; width:100%; height:110px; border-radius: 10px;  overflow: hidden; box-shadow: 0 2px 5px 1px rgba(0,0,0,0.1);">
                                        <amp-img class="responsive-img" src="../../../../../images/images/gallery/preview/<?php echo $images[0]; ?>" width="100" height="100" layout="responsive"></amp-img>
                                        <h5><?php echo $row[1];?></h5>
                                        <p><?php echo $row[2];?></p>
                                        </div>
                                    </a>
                                    <hr style="border-top: 0.5px solid #E8E8FF;">
                                </div> -->

                            </div>

                        <a href="m-detail-<?php echo $row[0]; ?>.html">
                            <div class="half-material-box-<?php echo $param; ?>">
                            <span class="fa fa-heart-o fa-2x"style="color: red; aria-hidden="false";></span>
                                <!--<i class="center-text full-bottom huge-icon color-yellow-dark fa fa-bolt"></i>-->
                                <amp-img src="../../../../../images/images/gallery/preview/<?php echo $images[0]; ?>" layout="responsive" width="127" height="130"></amp-img>
                                <p class="center-text small-text half-bottom">

                                    <!--<i class="fa fa-angle-right"></i><?php echo substr_replace($row[1], "...", 60);?>-->
                                </p>
                                <h3 class="small-text lef-text bold" name="hidden_name" style="color:#969696;"><?php echo $row[1]; ?></h3>
                                <h4 class="left-text thick" name="hidden_price" style="color:#f94b2b;">€ <?php echo $row[2]; ?></h4>

                                <?php
                                    foreach(range(1, $row[10]) as $i)
                                    {
                                        //echo $i;
                                        ?>
                                            <span class="fa fa-star checked" style="color: #ffa500;"></span>
                                        <?php
                                    }
                                ?>
                            </div>
                        </a>
                <!--    </form> -->
                        <?php

                    }
                }
        ?>

        <div class="clear"></div>

    </div>
</code>```

jQuery:

```<code>(function ($) {
      $(document).ready(function() {

        $(".popup-with-zoom-anim").each(function() {
            $(this).magnificPopup({

                  type: 'inline',
                 fixedBgPos: true,

                 fixedContentPos: true,
                 overflowY: 'hidden',

                 closeBtnInside: false,
                 preloader: false,

                 midClick: true,
                 removalDelay: 300,
                 mainClass: 'my-mfp-zoom-in'
            });

        });
        $(document).on('click', '.popup-modal-dismiss', function (e) {
                e.preventDefault();
                $.magnificPopup.close();
            });

      });
})(jQuery);
</code>```

It shows the Popup dialog the way I want but the problem is that it shows the same data no matter what product I click!

I can't figure it out weather it has problem with Id or .each instance in jQuery. Any help would be appreciated!

Thank you!

Title: Magnific Popup showing same item

Body:
Refering to this question , it has a helpful answer but it's partial answer because it only shows three unique popup dialogs - static.

I'm new to jQuery and working in this project. I want this to be dynamic with MySql database. Let's say I have a collection of 20 products stored in a tbl_products and each product has a uniqe id, name and price. When user clicks for more product details, I want to display the Magnific popup dialog that shows the product details, showing the product image(small thumbnail), product name and product price.

This link is inside loop:

<a class="popup-with-zoom-anim" href="#small-dialog" data-item="<?php echo $row["product_id"]; ?>">Open with fade-zoom animation

Here is the Code:

        <?php
                $query = "SELECT * FROM tbl_product ORDER BY product_id ASC LIMIT 20";
                        $result = mysqli_query($connect, $query);
                        $ctr = 0;
                if(mysqli_num_rows($result) > 0)
                {
                    $i = 0;
                    $param = 'right';
                    while($row = mysqli_fetch_array($result))
                    {
                        //echo "
" . $row[0] . "
";
                        $data = $row["product_image"];
                        $images = explode(";", $data);
                        if($param=='left'){
                            $param = "right";
                        }
                        else{
                            $param = "left";
                            ?>

<?php
                        }

                        ?>
                        <a class="popup-with-zoom-anim" href="#small-dialog" data-item="<?php echo $row["product_id"]; ?>">Open with fade-zoom animation

Artikulli u shtua në shportë

                                                                <amp-img class="responsive-img" src="../../../../../images/images/gallery/preview/<?php echo $images[0]; ?>" width="100" height="100" layout="responsive"></amp-img>

<?php echo $row[1];?>

                                                                    <?php
                                                                        foreach(range(1, $row[10]) as $i)
                                                                        {
                                                                            ?>

                                                                            <?php
                                                                        }
                                                                    ?>

                                                    €<?php echo $row[2];?>

TVSH - 8%

Dërgesa Falas

                                                        <a href="m-detail-<?php echo $row[0]; ?>.html" style="font-size:11px; line-height:20px;"> Shiko detalet

                                    <button type="button" class="btn btn-default popup-modal-dismiss">Vazhdo me blerje</button>
                                    <button type="button" style="float:right;" class="btn btn-primary">Kryje porosinë</button>

                        <a href="m-detail-<?php echo $row[0]; ?>.html">
                            <div class="half-material-box-<?php echo $param; ?>">

                                <amp-img src="../../../../../images/images/gallery/preview/<?php echo $images[0]; ?>" layout="responsive" width="127" height="130"></amp-img>

<?php echo $row[1]; ?>

€ <?php echo $row[2]; ?>

                                <?php
                                    foreach(range(1, $row[10]) as $i)
                                    {
                                        //echo $i;
                                        ?>

                                        <?php
                                    }
                                ?>

                        <?php

                    }
                }
        ?>

jQuery:

(function ($) {
      $(document).ready(function() {

        $(".popup-with-zoom-anim").each(function() {
            $(this).magnificPopup({

                  type: 'inline',
                 fixedBgPos: true,

                 fixedContentPos: true,
                 overflowY: 'hidden',

                 closeBtnInside: false,
                 preloader: false,

                 midClick: true,
                 removalDelay: 300,
                 mainClass: 'my-mfp-zoom-in'
            });

        });
        $(document).on('click', '.popup-modal-dismiss', function (e) {
                e.preventDefault();
                $.magnificPopup.close();
            });

      });
})(jQuery);

It shows the Popup dialog the way I want but the problem is that it shows the same data no matter what product I click!

I can't figure it out weather it has problem with Id or .each instance in jQuery. Any help would be appreciated!

Thank you!


问:
Wordpress in Beanstalk subdirectory
So I have an interesting problem, and I might need your help to fix it.

I have a NodeJS beanstalk app working pretty well, and hosted on example.com. Now I want to host an external Wordpress application (running on Ligtsail) in the subdirectory of this app (e.g. example.com/wordpress).

I created a .platform/nginx/conf.d/elasticbeanstalk/00_application.conf with the below snippet

```<code>location  /wordpress  {
  proxy_pass  http://{the-wordpress-private-ip}:80/;
  proxy_set_header    Connection          $connection_upgrade;
  proxy_set_header    Upgrade             $http_upgrade;
  proxy_set_header    Host                $host;
  proxy_set_header    X-Real-IP           $remote_addr;
  proxy_set_header    X-Forwarded-For
$proxy_add_x_forwarded_for;
}
</code>```

But I now have the following issues

I have a default nginx page on my site root. Any ideas how I can work around this please?

I have a 404 when I visit example.com/wordpress

Any ideas on how I can resolve this please?

The WordPress app is running on Lightsail; VPC Peering is enabled, so the private IP is reachable from the beanstalk instance.

Title: Wordpress in Beanstalk subdirectory

Body:
So I have an interesting problem, and I might need your help to fix it.

I have a NodeJS beanstalk app working pretty well, and hosted on example.com. Now I want to host an external Wordpress application (running on Ligtsail) in the subdirectory of this app (e.g. example.com/wordpress).

I created a .platform/nginx/conf.d/elasticbeanstalk/00_application.conf with the below snippet

location  /wordpress  {
  proxy_pass  http://{the-wordpress-private-ip}:80/;
  proxy_set_header    Connection          $connection_upgrade;
  proxy_set_header    Upgrade             $http_upgrade;
  proxy_set_header    Host                $host;
  proxy_set_header    X-Real-IP           $remote_addr;
  proxy_set_header    X-Forwarded-For
$proxy_add_x_forwarded_for;
}

But I now have the following issues

I have a default nginx page on my site root. Any ideas how I can work around this please?

I have a 404 when I visit example.com/wordpress

Any ideas on how I can resolve this please?

The WordPress app is running on Lightsail; VPC Peering is enabled, so the private IP is reachable from the beanstalk instance.


问:
How to extend Mysql groupby results to whole integers domain as an axis?
I am making charts for my mysql database. In order to use Bar Chart to display some data as numeric distributions, I have to aggregate a table so it will be like this:

select user_score, count(*) as cnt from t group by user_score order by user_score;

|user_score| cnt |
|         1| 1000|
|         2|  300|
|         5|  500|
|         7|   10|
|       ...|  ...|
```
<p>We assume that the domain of <code>user_score</code> is all integers from 1 to 100. I want the result to be:</p>
<pre class="lang-sql prettyprint-override"><code>|user_score| cnt |
|         1| 1000|
|         2|  300|
|         3|    0|
|         4|    0|
|         5|  500|
|         6|    0|
|         7|   10|
|       ...|  ...|
|       100|    0|
</code>```

this question may also look like:

aggregation result:

|  time | count |
|  1:00 |     10|
|  4:00 |      1|
```
<p>expected result:</p>
<pre class="lang-sql prettyprint-override"><code>|  time | count |
|  1:00 |     10|
|  2:00 |      0|
|  3:00 |      0|
|  4:00 |      1|
|   ... |    ...|
| 24:00 |      0|
</code>```

Any ideas?

Body:
I am making charts for my mysql database. In order to use Bar Chart to display some data as numeric distributions, I have to aggregate a table so it will be like this:

select user_score, count(*) as cnt from t group by user_score order by user_score;

|user_score| cnt |
|         1| 1000|
|         2|  300|
|         5|  500|
|         7|   10|
|       ...|  ...|

We assume that the domain of user_score is all integers from 1 to 100. I want the result to be:

|user_score| cnt |
|         1| 1000|
|         2|  300|
|         3|    0|
|         4|    0|
|         5|  500|
|         6|    0|
|         7|   10|
|       ...|  ...|
|       100|    0|

this question may also look like:

aggregation result:

|  time | count |
|  1:00 |     10|
|  4:00 |      1|

expected result:

|  time | count |
|  1:00 |     10|
|  2:00 |      0|
|  3:00 |      0|
|  4:00 |      1|
|   ... |    ...|
| 24:00 |      0|

Any ideas?


问:
How to use integrate between ast from angular-html-parser and css-select?
I want to parse angularjs html file. I do it using angular-html-parser package who generates AST.

I want to easily travel inside this AST, using queries. To do that I using css-select package (which give me queries to investigate the nodes).

So I made a DOM-like structure, where each node has a type, tagName, attributes, and children property. (what css-select is expected):

```<code>import { parse } from 'angular-html-parser';
import css from 'css-select';

const html = '<div ng-repeat="item in items">{{ item }}</div>';
const ast = parse(html);
console.log(ast);

function convertAstToDomLikeStructure(node) {
  console.log({ node });
  const domNode = {
    type: node.type,
    tagName: node.name,
    attributes: node.attrs,
    children: [],
  };
  if (node.children) {
    node.children.forEach((childNode) => {
      domNode.children.push(convertAstToDomLikeStructure(childNode));
    });
  }
  return domNode;
}

const domLikeStructure = convertAstToDomLikeStructure(ast.rootNodes[0]);
const elements = css('div[ng-repeat]', domLikeStructure);
console.log(elements); // Array of elements with the "ng-repeat" attribute
</code>```

But in the console I got empty array. elements is []

Why?

stackblitz

Body:
I want to parse angularjs html file. I do it using angular-html-parser package who generates AST.

I want to easily travel inside this AST, using queries. To do that I using css-select package (which give me queries to investigate the nodes).

So I made a DOM-like structure, where each node has a type, tagName, attributes, and children property. (what css-select is expected):

import { parse } from 'angular-html-parser';
import css from 'css-select';

const html = '
{{ item }}
';
const ast = parse(html);
console.log(ast);

function convertAstToDomLikeStructure(node) {
  console.log({ node });
  const domNode = {
    type: node.type,
    tagName: node.name,
    attributes: node.attrs,
    children: [],
  };
  if (node.children) {
    node.children.forEach((childNode) => {
      domNode.children.push(convertAstToDomLikeStructure(childNode));
    });
  }
  return domNode;
}

const domLikeStructure = convertAstToDomLikeStructure(ast.rootNodes[0]);
const elements = css('div[ng-repeat]', domLikeStructure);
console.log(elements); // Array of elements with the "ng-repeat" attribute

But in the console I got empty array. elements is []

Why?

stackblitz


问:
Alerts on renko charts for multiple assets
So I have a layout that consists of a Renko chart and some EMAs which I use on multiple assets and change the brick size every time I change the asset in the layout.
The brick sizes of assets aren't saved, and hence need a manual change every time the asset is changed. So I'm confused about how to use alerts for multiple assets using the same Renko layout.

Is it possible to make an indicator/study that changes the Renko brick size when the asset is changed in the layout? The brick calculation is 0.5% of the current price.
By that, we can use alert() in the same indicator to get alerts.

Or is there a better solution?


问:
AdActivity Ad mob load failed
The crash happens every time when AdView.loadAd() is called.

```<code>Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.size()' on a null object reference
       at android.os.Parcel.createExceptionOrNull(Parcel.java:2432)
       at android.os.Parcel.createException(Parcel.java:2410)
       at android.os.Parcel.readException(Parcel.java:2393)
       at android.os.Parcel.readException(Parcel.java:2335)
       at android.view.IWindowManager$Stub$Proxy.getSupportedDisplayHashAlgorithms(IWindowManager.java:6149)
       at android.view.displayhash.DisplayHashManager.getSupportedHashAlgorithms(DisplayHashManager.java:71)
       at com.google.android.gms.ads.eventattestation.internal.l.<init>(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631:2)
       at com.google.android.gms.ads.nonagon.ad.j.e(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631:9)
       at com.google.android.gms.ads.nonagon.ad.g.run(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
       at java.lang.Thread.run(Thread.java:1012)
It has happened only on a single device.
</code>```

happens on the same device

Android 12,  Xiaomi Mi 11 Lite 5G

play services ads version is:

implementation 'com.google.android.gms:play-services-ads:21.3.0'

Title: AdActivity Ad mob load failed

Body:
The crash happens every time when AdView.loadAd() is called.

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.size()' on a null object reference
       at android.os.Parcel.createExceptionOrNull(Parcel.java:2432)
       at android.os.Parcel.createException(Parcel.java:2410)
       at android.os.Parcel.readException(Parcel.java:2393)
       at android.os.Parcel.readException(Parcel.java:2335)
       at android.view.IWindowManager$Stub$Proxy.getSupportedDisplayHashAlgorithms(IWindowManager.java:6149)
       at android.view.displayhash.DisplayHashManager.getSupportedHashAlgorithms(DisplayHashManager.java:71)
       at com.google.android.gms.ads.eventattestation.internal.l.<init>(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631:2)
       at com.google.android.gms.ads.nonagon.ad.j.e(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631:9)
       at com.google.android.gms.ads.nonagon.ad.g.run(:com.google.android.gms.policy_ads_fdr_dynamite@224400003@224400003057.484457631.484457631)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
       at java.lang.Thread.run(Thread.java:1012)
It has happened only on a single device.

happens on the same device

Android 12,  Xiaomi Mi 11 Lite 5G

play services ads version is:

implementation 'com.google.android.gms:play-services-ads:21.3.0'


问:
nginx return directive redirects to another location
My nginx (nginx version: nginx/1.23.3) conf:

```<code>user nginx;
worker_processes auto;

error_log   /var/log/nginx/error.log notice;
pid         /var/run/nginx.pid;

http {
    server {
        listen 80;
        server_name localhost;
        root /home/app/;

        location /test {
            return 200 'from test $uri';
        }

        location ~ /(\d+) {
            return 200 'not from test';
        }

    }
}
</code>```

When i go to the http://localhost/test/ I get from test /test/, its ok,

but when I go to the http://localhost/test/2 server returns not from test /test/2.

According to docs return stops processing and return response to client. But it looks like nginx doesn't stop and goes to another location, why?

And if so, why var $uri doesn't contain only /2 ?

Thanx.

Body:
My nginx (nginx version: nginx/1.23.3) conf:

user nginx;
worker_processes auto;

error_log   /var/log/nginx/error.log notice;
pid         /var/run/nginx.pid;

http {
    server {
        listen 80;
        server_name localhost;
        root /home/app/;

        location /test {
            return 200 'from test $uri';
        }

        location ~ /(\d+) {
            return 200 'not from test';
        }

    }
}

When i go to the http://localhost/test/ I get from test /test/, its ok,

but when I go to the http://localhost/test/2 server returns not from test /test/2.

According to docs return stops processing and return response to client. But it looks like nginx doesn't stop and goes to another location, why?

And if so, why var $uri doesn't contain only /2 ?

Thanx.


问:
Prisma relations: define relations without using "connect" syntax
I use Postgres with Prisma and I want to ask if there is a way to use upsert or create functions and define relations without the connect field.

I have these models:

```<code>model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int // relation scalar field  (used in the `@relation` attribute above)
}
</code>```

and I want to do something like this:

```<code>prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { authorId: 12 })
</code>```

assuming User with ID 12 does exists in the DB I want it to create a new record successfully but it fails because it wants it in this syntax:

```<code>prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { author: { connect: { id: 12}}}})
</code>```

is this achievable somehow?
Thanks.

Body:
I use Postgres with Prisma and I want to ask if there is a way to use upsert or create functions and define relations without the connect field.

I have these models:

model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int // relation scalar field  (used in the `@relation` attribute above)
}

and I want to do something like this:

prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { authorId: 12 })

assuming User with ID 12 does exists in the DB I want it to create a new record successfully but it fails because it wants it in this syntax:

prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { author: { connect: { id: 12}}}})

is this achievable somehow?
Thanks.


问:
Is there an industry standard or W3 recommendation for converting touchpad/fingerpad events to mouseevents? (For javascript use)
Is there an industry standard or W3 recommendation for converting touchpad/fingerpad events to mouseevents? (Ffor javascript use)

Background: I have written my own html-application, running fine on my notebook where I don't have a mouse, but use the touchpad. (I always thought it is called fingerpad.)

The events from the touchpad show up nicely converted to mouse-events in the Firefox javascript event handling.

Now I'm trying to run my web-app on a tablet, and have to handle the touch-events: That mostly works very well, except for the doubleclick or click. (And the not wanted simultaneneously happening page scrolling, but I know how to handle the latter.)

Because physically I can't see any difference between my touchpad and the tablet surface, and before I will change the event handling in my app any further therefore my question, if there is a industry standard or W3 recommendation for converting those touchpad/fingerpad events to those mouseevents that show up in my Firefox javascript event handling.

I simply don't want to reinvent the wheel. (And I have seen many questions here and in other forums around the touch-event handling, that would mostly be solved by such a converting standard.)


问:
Multiple labels while plotting
I am doing a nested plot but my labels are repeating as many times as a loop, although it is out of the loop. In fact, I need three labels which correspond to 6.96K, 0.268K, 0.02025K</p>
```<code>import matplotlib.pyplot as plt
import numpy as np

Freq = np.arange(1, 10, 0.1)

T = 6.96
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='red', linewidth=1.5, markersize=4, label = '6.96K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

T = 0.268
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='orange', linewidth=1.5, markersize=4,label = '0.268K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

T = 0.02025
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='Blue', linewidth=1.5, markersize=4,label = '0.02025K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

plt.show()

</code>```

Title: Multiple labels while plotting

Body:
I am doing a nested plot but my labels are repeating as many times as a loop, although it is out of the loop. In fact, I need three labels which correspond to 6.96K, 0.268K, 0.02025K

import matplotlib.pyplot as plt
import numpy as np

Freq = np.arange(1, 10, 0.1)

T = 6.96
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='red', linewidth=1.5, markersize=4, label = '6.96K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

T = 0.268
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='orange', linewidth=1.5, markersize=4,label = '0.268K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

T = 0.02025
for f in Freq:
        def quanta(f,T):
            return (f*T)
        final = quanta(f,T)
        plt.plot(f, final, 'o', color='Blue', linewidth=1.5, markersize=4,label = '0.02025K')
plt.legend(shadow=True, loc=(0.5, 0.2) )

plt.show()


问:
How to calculate expected value of a Palindrome-Finding game
Given question
So I have this question. I have written a game in R in which there is an 8x8 matrix of letters from to z. You start on any random square, then randomly move to another square and decide if you want to collect the letter on that square. In this way, you collect 5 letters that form a palindrome.

Now, in the above image, the number of turns when starting on a square A is given in a list. How do I calculate the expected value of this square? I have written some code in which, I count the occurrences of values in 10s, 20s, 30s and 40s and multiplying them by 10, 20, 30 and 40 and then summing up to get the expected value. Not sure if this is correct.

```<code># For square A
vals <- c(10, 20, 30, 40)
probs <- c(0.545, 0.363, 0.090, 0)
expected_val_sq_A <- sum(vals*probs)
print(expected_val_sq_A)

# For square B
vals <- c(10, 20, 30, 40)
probs <- c(0.181, 0.363, 0.181, 0.272)
expected_val_sq_b <- sum(vals*probs)
print(expected_val_sq_b)
</code>```

Body:
Given question
So I have this question. I have written a game in R in which there is an 8x8 matrix of letters from to z. You start on any random square, then randomly move to another square and decide if you want to collect the letter on that square. In this way, you collect 5 letters that form a palindrome.

Now, in the above image, the number of turns when starting on a square A is given in a list. How do I calculate the expected value of this square? I have written some code in which, I count the occurrences of values in 10s, 20s, 30s and 40s and multiplying them by 10, 20, 30 and 40 and then summing up to get the expected value. Not sure if this is correct.

# For square A
vals <- c(10, 20, 30, 40)
probs <- c(0.545, 0.363, 0.090, 0)
expected_val_sq_A <- sum(vals*probs)
print(expected_val_sq_A)

# For square B
vals <- c(10, 20, 30, 40)
probs <- c(0.181, 0.363, 0.181, 0.272)
expected_val_sq_b <- sum(vals*probs)
print(expected_val_sq_b)


问:
Is there a way to position an image inside Aspect Ratio component while using Chakra UI
With this simple code below, the image of an original aspect ratio of 16/9 will be cropped from both sides, leaving only the middle part of the image visible

```<code>                <AspectRatio w="400px" ratio={9 / 16}>

                    <Image
                        src="/images/sampleImage.png"
                        objectFit={"cover"}
                    />

                </AspectRatio>
</code>```

What if I want to make the right hand side of the image visible instead of the middle.

I tried using positioning on the <image> and the <AspectRatio> but it made no difference.

```<code>               <AspectRatio w="100vw" ratio={9 / 16} position="relative">

                   <Image
                        src="/images/sampleImage.png"
                        objectFit={"cover"}
                        position={"absolute"}
                        top="-10rem"
                        right={"5rem"}
                    />

               </AspectRatio>
</code>```

Body:
With this simple code below, the image of an original aspect ratio of 16/9 will be cropped from both sides, leaving only the middle part of the image visible

                <AspectRatio w="400px" ratio={9 / 16}>

                    <Image
                        src="/images/sampleImage.png"
                        objectFit={"cover"}
                    />

                </AspectRatio>

What if I want to make the right hand side of the image visible instead of the middle.

I tried using positioning on the <image> and the <AspectRatio> but it made no difference.

               <AspectRatio w="100vw" ratio={9 / 16} position="relative">

                   <Image
                        src="/images/sampleImage.png"
                        objectFit={"cover"}
                        position={"absolute"}
                        top="-10rem"
                        right={"5rem"}
                    />

               </AspectRatio>


问:
React Native error Please report: Excessive number of pending callbacks: 501
I'm using react native I'm trying to create a category filter where it shows me the category list and once the category title is clicked it expends showing the sub-categories I keep getting the error  Please report: Excessive number of pending callbacks: 501. Some pending callbacks that might have leaked by never being called from native code
**
This is my filter screen:**

...
const CategoryFilter = ( { route, navigation: { goBack } } ) => {
    const navigation = useNavigation();
    const {itemStore, itemCategory} = route.params;
    const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableHighlight;

  // use a map to keep track of collapsed state for each category
  const [collapsed, setCollapsed] = useState(
    dummyData.carouselData.reduce((map, category) => ({
      ...map,
      [category.category]: false
    }), {})
  );

  // helper function to toggle collapsed state for a given category
  const toggleCollapsed = useCallback((category) => {
    setCollapsed((prevCollapsed) => ({
      ...prevCollapsed,
      [category]: !prevCollapsed[category],
    }));
  }, []);

  // useRef to keep track of mounted status to avoid memory leaks
  const isMounted = useRef(true);
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);

  // debounce the toggleCollapsed function to prevent excessive callbacks
  const debouncedToggleCollapsed = useDebounce(toggleCollapsed, 500, [
    collapsed,
  ]);

  return (
    <SafeAreaView style={styles.container}>
        <ScrollView>
            <View style={styles.Header}>
                <Touchable
                    style={styles.button}
                    onPress={() => goBack()}
                    activeOpacity={0.5} // Reduce the press delay on iOS
                    delayPressIn={0} // Remove the delay when pressing the button on Android
                >
                    <Icon icon ='arrow-back-outline' color='#000' size={25}/>
                </Touchable>
                <Text style={{fontWeight: '800', fontSize: 20}}>Filter</Text>
            </View >
            <View style={styles.body}>
                <View style={styles.section}>
                    <Text style={{fontSize: 20, fontWeight: '700'}}>Categories:</Text>
                    {dummyData.carouselData.map((category, index) => (
                        <View key={index}>
                        <Touchable
                            onPress={() => toggleCollapsed(category.category)}
                            activeOpacity={0.5}
                            delayPressIn={0}
                        >
                            <View>
                                <Text style={(category.category === itemCategory) ? styles.picked : styles.text}>
                                    {category.category}
                                </Text>
                            </View>
                        </Touchable>

                            <View >
                                {collapsed[category.category] && isMounted.current && (
                                    <View>
                                        {category.subCategory.map((subItem) => (
                                            <Text key={subItem.id} >{subItem.title}</Text>
                                        ))}
                                    </View>
                                )}
                            </View>

                        </View>
                    ))}
                </View>
            </View>
        </ScrollView>
    </SafeAreaView>
  )
}

export default CategoryFilter
```
<p>And this is the data I want to map thru in total I have 18 categories and each category contains too many sub-categories.. the collapse works fine, however, i keep getting the error and my app is really slow</p>
<pre class="lang-js prettyprint-override"><code>const carouselData = [

    {
       image: "https://i.ibb.co/26VTJd3/BUBCAT-3-Bubcat-Bread-220208-1644346379881.png",
       title: "Bakery",
       subCategory: [
            {title: 'All', id: 1, name: 'Bakery'},
            {title: 'Bagels, Buns & Rolls', id: 2, name: 'Bakery, Bagels, Buns & Rolls', image: "https://i.ibb.co/8BrQH1d/pexels-anna-tarazevich-6937426.jpg"},
            {title: 'Cakes & Desserts', id: 3, name: 'Bakery, Cakes & Desserts', image: "https://i.ibb.co/hK0N8Fm/pexels-11719204.jpg"},
            {title: 'Bakery, Bread', id: 4, name: 'Bakery, Bread', image: "https://i.ibb.co/dbxtRKT/pexe"},
            {title: 'Breakfast', id: 5, name: 'Bakery, Breakfast', image: "https://i.ibb.co/dbxtRKT/pexels-ash-376464.jpg"},
        ],
       id: 1,
       category:"Bakery"
   },
]

</code>```

Body:
I'm using react native I'm trying to create a category filter where it shows me the category list and once the category title is clicked it expends showing the sub-categories I keep getting the error  Please report: Excessive number of pending callbacks: 501. Some pending callbacks that might have leaked by never being called from native code
**
This is my filter screen:**

...
const CategoryFilter = ( { route, navigation: { goBack } } ) => {
    const navigation = useNavigation();
    const {itemStore, itemCategory} = route.params;
    const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableHighlight;

  // use a map to keep track of collapsed state for each category
  const [collapsed, setCollapsed] = useState(
    dummyData.carouselData.reduce((map, category) => ({
      ...map,
      [category.category]: false
    }), {})
  );

  // helper function to toggle collapsed state for a given category
  const toggleCollapsed = useCallback((category) => {
    setCollapsed((prevCollapsed) => ({
      ...prevCollapsed,
      [category]: !prevCollapsed[category],
    }));
  }, []);

  // useRef to keep track of mounted status to avoid memory leaks
  const isMounted = useRef(true);
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);

  // debounce the toggleCollapsed function to prevent excessive callbacks
  const debouncedToggleCollapsed = useDebounce(toggleCollapsed, 500, [
    collapsed,
  ]);

  return (
    <SafeAreaView style={styles.container}>
        <ScrollView>
            <View style={styles.Header}>
                <Touchable
                    style={styles.button}
                    onPress={() => goBack()}
                    activeOpacity={0.5} // Reduce the press delay on iOS
                    delayPressIn={0} // Remove the delay when pressing the button on Android
                >
                    <Icon icon ='arrow-back-outline' color='#000' size={25}/>
                </Touchable>
                <Text style={{fontWeight: '800', fontSize: 20}}>Filter</Text>
            </View >
            <View style={styles.body}>
                <View style={styles.section}>
                    <Text style={{fontSize: 20, fontWeight: '700'}}>Categories:</Text>
                    {dummyData.carouselData.map((category, index) => (
                        <View key={index}>
                        <Touchable
                            onPress={() => toggleCollapsed(category.category)}
                            activeOpacity={0.5}
                            delayPressIn={0}
                        >
                            <View>
                                <Text style={(category.category === itemCategory) ? styles.picked : styles.text}>
                                    {category.category}
                                </Text>
                            </View>
                        </Touchable>

                            <View >
                                {collapsed[category.category] && isMounted.current && (
                                    <View>
                                        {category.subCategory.map((subItem) => (
                                            <Text key={subItem.id} >{subItem.title}</Text>
                                        ))}
                                    </View>
                                )}
                            </View>

                        </View>
                    ))}
                </View>
            </View>
        </ScrollView>
    </SafeAreaView>
  )
}

export default CategoryFilter

And this is the data I want to map thru in total I have 18 categories and each category contains too many sub-categories.. the collapse works fine, however, i keep getting the error and my app is really slow

const carouselData = [

    {
       image: "https://i.ibb.co/26VTJd3/BUBCAT-3-Bubcat-Bread-220208-1644346379881.png",
       title: "Bakery",
       subCategory: [
            {title: 'All', id: 1, name: 'Bakery'},
            {title: 'Bagels, Buns & Rolls', id: 2, name: 'Bakery, Bagels, Buns & Rolls', image: "https://i.ibb.co/8BrQH1d/pexels-anna-tarazevich-6937426.jpg"},
            {title: 'Cakes & Desserts', id: 3, name: 'Bakery, Cakes & Desserts', image: "https://i.ibb.co/hK0N8Fm/pexels-11719204.jpg"},
            {title: 'Bakery, Bread', id: 4, name: 'Bakery, Bread', image: "https://i.ibb.co/dbxtRKT/pexe"},
            {title: 'Breakfast', id: 5, name: 'Bakery, Breakfast', image: "https://i.ibb.co/dbxtRKT/pexels-ash-376464.jpg"},
        ],
       id: 1,
       category:"Bakery"
   },
]


问:
Angular website does not load home page(shows blank page) as soon as i login but when i refresh 2 or 3 times then Home page is visible
When I login to my angular website(production) in first go it does not show my home page still after login but when I do refresh 2 or 3 times then it loads home page.

when first time page loads main.js and runtime.js are not loading and showing error as net::ERR_ABORTED 404 (Not Found)

but same project is working fine on staging(a testing platform) but not working properly in prod platform.
below are the commands that I use to make build of my project for in stg and prod.

```<code> "prod-build": "ng build --configuration production --aot false --build-optimizer=false && npm run post-build",
    "stg-build": "ng build --configuration=stg --aot false --build-optimizer=false && npm run post-build",
</code>```

I do not know what to do to fix  the loading issue in production so that as soon as I login , home page should load.

Body:
When I login to my angular website(production) in first go it does not show my home page still after login but when I do refresh 2 or 3 times then it loads home page.

when first time page loads main.js and runtime.js are not loading and showing error as net::ERR_ABORTED 404 (Not Found)

but same project is working fine on staging(a testing platform) but not working properly in prod platform.
below are the commands that I use to make build of my project for in stg and prod.

 "prod-build": "ng build --configuration production --aot false --build-optimizer=false && npm run post-build",
    "stg-build": "ng build --configuration=stg --aot false --build-optimizer=false && npm run post-build",

I do not know what to do to fix  the loading issue in production so that as soon as I login , home page should load.


问:
Popstate Event is not triggered in Safari 16
If someone uses the back button on the page, the user should be redirected to another page. In Chrome and Firefox the following script works without any problems, in Safari the event is not triggered. Does anyone know why this doesn't work in Safari or how else I can implement the function in Safari?</p>
```<code> <script>
        window.history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function (event) {
            window.location.replace(`URL`);
        });
    </script>
</code>```


问:
Cannot Connect Keycloak docker to SQL Server database
I'm using a docker image of keycloak and trying to connect to SQL Server.

I have the database "keycloak" created in the database and here's my DockerFile

```<code>FROM quay.io/keycloak/keycloak:18.0.0

ENV KEYCLOAK_ADMIN=admin
ENV KEYCLOAK_ADMIN_PASSWORD=admin

ENTRYPOINT ["/opt/keycloak/bin/kc.sh", "start", "--hostname-strict=false", "--auto-build", "--proxy=edge", "--db=mssql", "--db-url-host=***", "--db-username=***", "--db-password=***"]
</code>```

When I build and run this, the tables get automatically created in the 'keycloak' database. However, after waiting for keycloak to run, it crashes in the cmd and I get errors like

Violation of UNIQUE KEY constraint 'UK_CLI_SCOPE'. Cannot insert duplicate key in object 'dbo.CLIENT_SCOPE'

I fixed this error but I still get more endless errors and it never seemed to work. Last error I got was

Cannot start server in developlment/production mode

Any idea why this is happening? Am I missing anything in the docker file? Any idea if keycloak actually works with SQL Server?

Thanks!

Body:
I'm using a docker image of keycloak and trying to connect to SQL Server.

I have the database "keycloak" created in the database and here's my DockerFile

FROM quay.io/keycloak/keycloak:18.0.0

ENV KEYCLOAK_ADMIN=admin
ENV KEYCLOAK_ADMIN_PASSWORD=admin

ENTRYPOINT ["/opt/keycloak/bin/kc.sh", "start", "--hostname-strict=false", "--auto-build", "--proxy=edge", "--db=mssql", "--db-url-host=***", "--db-username=***", "--db-password=***"]

When I build and run this, the tables get automatically created in the 'keycloak' database. However, after waiting for keycloak to run, it crashes in the cmd and I get errors like

Violation of UNIQUE KEY constraint 'UK_CLI_SCOPE'. Cannot insert duplicate key in object 'dbo.CLIENT_SCOPE'

I fixed this error but I still get more endless errors and it never seemed to work. Last error I got was

Cannot start server in developlment/production mode

Any idea why this is happening? Am I missing anything in the docker file? Any idea if keycloak actually works with SQL Server?

Thanks!


问:
How can i open several .nc files as one in python with xarray?
I have 30 .nc files with dimensions: time, lat, lon, pres; coordinates: time, lat, lon, pres and 18 different variables. I would like to open them in one dataset.
If I use xarray.open_mfdataset (), it won't work, as the dimensions of pres are all different.
Is there any way to open them as one anyway?

This is what I tried, and which Error I got:

```<code>import xarray as xr

path = ('Data/*.nc')
ds = xr.open_mfdataset(paths = sorted (glob(path)),
                       chunks={"time_counter":1, "y":100, "x":100},
                      coords = 'all', combine = 'by_coords')

</code>```
```<code>ValueError: Resulting object does not have monotonic global indexes along dimension PRES
</code>```

Body:
I have 30 .nc files with dimensions: time, lat, lon, pres; coordinates: time, lat, lon, pres and 18 different variables. I would like to open them in one dataset.
If I use xarray.open_mfdataset (), it won't work, as the dimensions of pres are all different.
Is there any way to open them as one anyway?

This is what I tried, and which Error I got:

import xarray as xr

path = ('Data/*.nc')
ds = xr.open_mfdataset(paths = sorted (glob(path)),
                       chunks={"time_counter":1, "y":100, "x":100},
                      coords = 'all', combine = 'by_coords')

ValueError: Resulting object does not have monotonic global indexes along dimension PRES


问:
Adding new meta-data too multiple legacy services
I have many legacy services with their own Schema.

Currently, I want to adding 1 field into those services to help organize things better.
Example: Field(Account_id) -- Get all item in services A with account_id

The most strange forward thing is to add a Field into all legacy services schema. The cons about this solution is that I have to change all the old schema and re-deploy all of those legacy services.

I also have another solution is to create a service that mapping account-id with legacy services-id. The cons is that it will increase complexity when I try to do search and pagination.

Example: I searching on fields on legacy services and I also want to filter it with account_id in new services. The process-ing of searching on legacy services I will have to return all result to new services in order for it to filter by account_ids and pagination.

So my question is if I want to avoid changing in legacy services. Is there a way to solve the searching and filtering with account_id problem?

Thanks you for reading


问:
Is there a way to find out the total size limit for object urls in javascript?
For a high-performance web application I would like to cache the media (images, videos, audio files) via fetch(), blob() and createObjectURL().

This might be up to 1GB (!). What happens if this exceeds the available space? Is there a browser-specific limit? How to dynamically find it out?. Is the maximum size shared with the js heap?

Is there a better way to tell the browser which resources to cache? I expirienced that most resources larger than a few kB are not cached by default. The main problem in my use case is the delay when a video/audio is started or an image is presented.


问:
google workspace marketplace app, installation requires domain delegation
Iv'e created an application in google workspace marketplace which requires a service account.
the approval of the application is complete, but when I install the application from the marketplace, the service account does not have permissions until i add it to the domain delegation:
https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority

but i noticed this:
enter image description here

so why is it not added in my GCP?

I have tried messing around with the scopes, installing on several organizations, adding and removing the domain delegation.

I am expecting that once i approve the application on my organization the delegations will be added automatically.


问:
Using stored procedure in php
I want to learn to use a stored procedure in php and for some reason it does not work

This is my procedure:

```<code>DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `counter`(INOUT `inc` INT)
    DETERMINISTIC
SET inc=inc+1$$
DELIMITER ;
</code>```

written in phpmyadmin

I want to make a loop that increments a value for each row in a result from another query:

```<code>$nr=0;
  $query2="Call counter(?)";

echo '<table style="width:100%">
  <tr>
    <th>Nr pereche </th>
    <th>Id 1 </th>
    <th>Id 2</th>

  </tr>';

while($result->fetch()){

  $result1 = $connect->prepare($query2);
  $result1 ->bind_param("s",$nr);
  $result1->execute();

  echo '<tr><td width="30%">'.stripslashes($nr).'</td>';
  echo '<td width="30%">Chestionar  '.stripslashes($r1).'</td>';
  echo '<td width="30%">Chestionar '.stripslashes($r2).'</td></tr>';
}
</code>```

what is currently displayed

In the first column, it should be 1,2,3 not 0,0,0.

I know that it can be done much easier but I want to use a stored procedure. Thanks

Title: Using stored procedure in php

Body:
I want to learn to use a stored procedure in php and for some reason it does not work

This is my procedure:

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `counter`(INOUT `inc` INT)
    DETERMINISTIC
SET inc=inc+1$$
DELIMITER ;

written in phpmyadmin

I want to make a loop that increments a value for each row in a result from another query:

$nr=0;
  $query2="Call counter(?)";

echo '

    Nr pereche
    Id 1
    Id 2

';

while($result->fetch()){

  $result1 = $connect->prepare($query2);
  $result1 ->bind_param("s",$nr);
  $result1->execute();

  echo '
'.stripslashes($nr).'	';
  echo 'Chestionar  '.stripslashes($r1).'	';
  echo 'Chestionar '.stripslashes($r2).'
';
}

what is currently displayed

In the first column, it should be 1,2,3 not 0,0,0.

I know that it can be done much easier but I want to use a stored procedure. Thanks