问:
React Native display information on user scroll
I'm making a page in which we can add some filter and display some information with some filters ( ex: with brands, price, ...)

But when I delete a filter with a <TouchableOpacity> nothing changes in my page, but I don't understand why.

There is my code:

```<code> const getProductsBySort = (
    itemId,
    check,
    brand,
    multiSliderValue,
    localOffset
  ) => {
    return new Promise((resolve, reject) => {
      console.log(
        "GETPRODUCTBYSORT: ",
        itemId,
        check,
        brand,
        multiSliderValue,
        localOffset
      );
      dispatch(
        authAction.GetAllProducts(
          itemId,
          check,
          brand,
          multiSliderValue,
          localOffset
        )
      ).then((response) => {
        const updatedList = [...informationsBySort];
        let counter = informationsBySort.length;
        const newArray = response.array.map((item) => ({
          ...item,
          key: counter++, // utilisez un compteur incrémental comme clé unique
        }));
        console.log("iciiii: ", newArray);
        if (newArray.length > 0) {
          setinformationsBySort([...updatedList, ...newArray]);
          setOffset(offset + 5);
        }
        setIsLoading(false);
        resolve(newArray);
      });
    });
  };

  const loadMoreData2 = (itemId, sort, brandName, multiSliderValue) => {
    if (isLoading) {
      console.log("Je passe par ici");
      return; // empêche les appels multiples à la fonction de chargement de données
    }

    setLocalOffset(0);
    console.log(
      "loadMoreData2: ",
      itemId,
      sort,
      brandName,
      multiSliderValue,
      localOffset
    );
    setIsLoading(true);
    getProductsBySort(itemId, sort, brandName, multiSliderValue, localOffset)
      .then((response) => {
        if (response) {
          // mettez à jour votre liste de données avec les nouvelles données
          setinformationsBySort([...informationsBySort, ...response]);
          // mettez à jour l'offset
          setLocalOffset(localOffset + 5);
        } else {
          console.log("NO RESPONSE");
        }
      })
      .catch((error) => {
        console.log("error: ", error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

 {listOfSort.length > 0 ? (
            <View style={{top: 11, marginLeft: 26}}>
              <View
                style={{
                  width: "100%",
                  height: "49%",
                  borderRadius: 20,
                  borderColor: "#ff7b0d",
                  borderWidth: 1,
                  backgroundColor: "#ff7b0d",
                  flexDirection: "row",
                  alignItems: "center",
                }}
              >
                <TouchableOpacity
                  onPress={() => {
                    setListOfSort("");
                    setTrie(0);
                    {
                      brandName.length > 0
                        ? loadMoreData2(
                            itemId,
                            4,
                            brandName,
                            multiSliderValue
                          ) && setIsLoading(false)
                        : setCheckSort(false);
                    }
                  }}
                >
                  <Text style={{color: "#fff", flex: 1, padding: 2}}>
                    Trie : {listOfSort} X
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          ) : (
            ""
          )}
          {brandName.map((element, index) => (
            <View style={{flex: 1, width: "100%", right: "100%"}}>
              <View
                style={{
                  width: "90%",
                  height: "49%",
                  borderRadius: 20,
                  borderColor: "#ff7b0d",
                  borderWidth: 1,
                  backgroundColor: "#ff7b0d",
                  flexDirection: "row",
                  alignItems: "center",
                  marginLeft: 40,
                  top: 10,
                  left: 20,
                }}
              >
                <TouchableOpacity
                  onPress={() => {
                    brandName.splice(index, 1);
                    setCptValue(cptValue - 1);
                    let sort = trie;
                    sort = trie > 0 ? trie : 4;
                    if (brandName.length > 0) {
                      loadMoreData2(itemId, sort, brandName, multiSliderValue);
                      setIsLoading(false);
                    } else if (sort) {
                      loadMoreData2(itemId, sort + 4, [], multiSliderValue);
                      setIsLoading(false);

                      // getProductsBySort(itemId, sort + 4, [], multiSliderValue);
                    } else {
                      setCheckSort(false);
                    }
                  }}
                >
                  <Text
                    style={{
                      color: "#fff",
                      flex: 1,
                      textAlignVertical: "center",
                      left: "20%",
                    }}
                  >
                    {element} X
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          ))}
        </ScrollView>
      ) : (
        ""
      )}
</code>```

And I display the information in a Flatlist:

```<code><FlatList
  onEndReachedThreshold={0.5}
  onEndReached={loadMoreData2}
  ListFooterComponent={isLoading ? <ActivityIndicator /> : null}
  style={{top: "2%"}}
  data={informationsBySort}
  renderItem={({item}) => (
    <View style={styles.Products}>
      <TouchableOpacity
        onPress={() =>
          navigation.navigate("descriptionProduct", {
            data: item,
          })
        }
      >
        <View style={{width: "40%", height: "60%"}}>
          <Image
            style={styles.imageProduct}
            source={{uri: item.image_url}}
          />
        </View>
        <View style={styles.productInfos}>
          <View style={{width: "60%", height: "30%"}}>
            <Text
              style={{
                fontSize: 15,
                bottom: "340%",
              }}
            >
              {item.titre}
            </Text>
          </View>
          <View
            style={{
              display: "flex",
              flexDirection: "row",
              bottom: "1%",
            }}
          >
            <Text style={{color: "grey"}}>à partir de </Text>
            <Text style={styles.price}>{item.prix} €</Text>
            <Text style={{left: "50%", color: "grey"}}>
              {item.boutiqueCpt} offres
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    </View>
  )}
/>
</code>```

So if someone could explain me. I continue my research by my side.
Thanks you in advance guys.

Body:
I'm making a page in which we can add some filter and display some information with some filters ( ex: with brands, price, ...)

But when I delete a filter with a <TouchableOpacity> nothing changes in my page, but I don't understand why.

There is my code:

 const getProductsBySort = (
    itemId,
    check,
    brand,
    multiSliderValue,
    localOffset
  ) => {
    return new Promise((resolve, reject) => {
      console.log(
        "GETPRODUCTBYSORT: ",
        itemId,
        check,
        brand,
        multiSliderValue,
        localOffset
      );
      dispatch(
        authAction.GetAllProducts(
          itemId,
          check,
          brand,
          multiSliderValue,
          localOffset
        )
      ).then((response) => {
        const updatedList = [...informationsBySort];
        let counter = informationsBySort.length;
        const newArray = response.array.map((item) => ({
          ...item,
          key: counter++, // utilisez un compteur incrémental comme clé unique
        }));
        console.log("iciiii: ", newArray);
        if (newArray.length > 0) {
          setinformationsBySort([...updatedList, ...newArray]);
          setOffset(offset + 5);
        }
        setIsLoading(false);
        resolve(newArray);
      });
    });
  };

  const loadMoreData2 = (itemId, sort, brandName, multiSliderValue) => {
    if (isLoading) {
      console.log("Je passe par ici");
      return; // empêche les appels multiples à la fonction de chargement de données
    }

    setLocalOffset(0);
    console.log(
      "loadMoreData2: ",
      itemId,
      sort,
      brandName,
      multiSliderValue,
      localOffset
    );
    setIsLoading(true);
    getProductsBySort(itemId, sort, brandName, multiSliderValue, localOffset)
      .then((response) => {
        if (response) {
          // mettez à jour votre liste de données avec les nouvelles données
          setinformationsBySort([...informationsBySort, ...response]);
          // mettez à jour l'offset
          setLocalOffset(localOffset + 5);
        } else {
          console.log("NO RESPONSE");
        }
      })
      .catch((error) => {
        console.log("error: ", error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

 {listOfSort.length > 0 ? (
            <View style={{top: 11, marginLeft: 26}}>
              <View
                style={{
                  width: "100%",
                  height: "49%",
                  borderRadius: 20,
                  borderColor: "#ff7b0d",
                  borderWidth: 1,
                  backgroundColor: "#ff7b0d",
                  flexDirection: "row",
                  alignItems: "center",
                }}
              >
                <TouchableOpacity
                  onPress={() => {
                    setListOfSort("");
                    setTrie(0);
                    {
                      brandName.length > 0
                        ? loadMoreData2(
                            itemId,
                            4,
                            brandName,
                            multiSliderValue
                          ) && setIsLoading(false)
                        : setCheckSort(false);
                    }
                  }}
                >
                  <Text style={{color: "#fff", flex: 1, padding: 2}}>
                    Trie : {listOfSort} X
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          ) : (
            ""
          )}
          {brandName.map((element, index) => (
            <View style={{flex: 1, width: "100%", right: "100%"}}>
              <View
                style={{
                  width: "90%",
                  height: "49%",
                  borderRadius: 20,
                  borderColor: "#ff7b0d",
                  borderWidth: 1,
                  backgroundColor: "#ff7b0d",
                  flexDirection: "row",
                  alignItems: "center",
                  marginLeft: 40,
                  top: 10,
                  left: 20,
                }}
              >
                <TouchableOpacity
                  onPress={() => {
                    brandName.splice(index, 1);
                    setCptValue(cptValue - 1);
                    let sort = trie;
                    sort = trie > 0 ? trie : 4;
                    if (brandName.length > 0) {
                      loadMoreData2(itemId, sort, brandName, multiSliderValue);
                      setIsLoading(false);
                    } else if (sort) {
                      loadMoreData2(itemId, sort + 4, [], multiSliderValue);
                      setIsLoading(false);

                      // getProductsBySort(itemId, sort + 4, [], multiSliderValue);
                    } else {
                      setCheckSort(false);
                    }
                  }}
                >
                  <Text
                    style={{
                      color: "#fff",
                      flex: 1,
                      textAlignVertical: "center",
                      left: "20%",
                    }}
                  >
                    {element} X
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          ))}
        </ScrollView>
      ) : (
        ""
      )}

And I display the information in a Flatlist:

<FlatList
  onEndReachedThreshold={0.5}
  onEndReached={loadMoreData2}
  ListFooterComponent={isLoading ? <ActivityIndicator /> : null}
  style={{top: "2%"}}
  data={informationsBySort}
  renderItem={({item}) => (
    <View style={styles.Products}>
      <TouchableOpacity
        onPress={() =>
          navigation.navigate("descriptionProduct", {
            data: item,
          })
        }
      >
        <View style={{width: "40%", height: "60%"}}>
          <Image
            style={styles.imageProduct}
            source={{uri: item.image_url}}
          />
        </View>
        <View style={styles.productInfos}>
          <View style={{width: "60%", height: "30%"}}>
            <Text
              style={{
                fontSize: 15,
                bottom: "340%",
              }}
            >
              {item.titre}
            </Text>
          </View>
          <View
            style={{
              display: "flex",
              flexDirection: "row",
              bottom: "1%",
            }}
          >
            <Text style={{color: "grey"}}>à partir de </Text>
            <Text style={styles.price}>{item.prix} €</Text>
            <Text style={{left: "50%", color: "grey"}}>
              {item.boutiqueCpt} offres
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    </View>
  )}
/>

So if someone could explain me. I continue my research by my side.
Thanks you in advance guys.


来源: stackexchange

问:
My Charts.js line chart dissappers when I try to flow my data from mysql using php
I'm having a issue with my charts like I stated in the title. When I try to get my data from MySQL graph disappears and I'm not getting any errors. but graph perfectly works when I'm entering them myself. What could possibly be the fault here? I'm pretty new in this so the code can be a little bit bad sorry for that in advance. Thank you.

```<code><?php

include('./connection.php');

?>

            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initialscale=1.0">
                <title>Nisantasi Cafe</title>
                <link rel="stylesheet" type="text/css" href="grafic1.css">
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
                <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js"></script>
            </head>
            <script>
                const labels = [
                '2022-01-01',
                '2022-02-01',
                '2022-03-01',
                '2022-04-01',
                '2022-05-01',
                '2022-06-01',
                '2022-07-01',
                '2022-08-01',
                '2022-09-01',
                '2022-10-01',
                '2022-11-01',
                '2022-12-01',
                ];
                const data = {
                labels: labels,
                datasets: [{
                label: 'Bitcoin',
                backgroundColor: 'transparent',
                borderColor: 'rgb(255, 0, 255)',
                data: [<?php
                        include("/connection.php");
                        $sql = "SELECT birim_deger.karsilik, tarih.tarih FROM birim_deger, tarih_deger, tarih
                        WHERE birim_deger.deger_id=tarih_deger.deger_id AND tarih_deger.tarih_id=tarih.tarih_id AND birim_deger.coin_id=2 AND birim_deger.itibari_id=1;";

                        $result = $con->query($sql);

                        $data = array();
                        foreach($result as $row){
                        $data[] = $row;
                        }
                        print json_encode($data)
                        ?>
                    ],
                }]
                };
                const config = {
                type: 'line',
                data: data,
                options: {}
                };

            </script>
            <body>
                <div class="container">
                <div class="navigation">
                    <ul>
                        <li>
                            <a href="#">
                                <span class="icon"><i class="fas fapeople-arrows"></i></span>
                                <span class="title">
                                    <h2>NCS</h2>
                                </span>
                            </a>
                        </li>
                        <li>
                            <a href="admin.php">
                                <span class="icon"><i class="fas fahome"></i></span>
                                <span class="title">Ana Sayfa</span>
                            </a>
                        </li>
                        <li>
                    <a href="grafic.php">
                        <span class="icon"><i class="fas fa-chartline"></i></span>
                        <span class="title">Broşürcü</span>
                    </a>
                </li>
                <li>
                    <a href="grafic1.php">
                        <span class="icon"><i class="fas fa-chartline"></i></span>
                        <span class="title">Fal Dağılımı</span>
                    </a>
                </li>
                <li>
                    <a href="grafic2.php">
                        <span class="icon"><i class="fas fa-chartline"></i></span>
                        <span class="title">Falcı</span>
                    </a>
                </li>
                <li>
                        <a href="grafic3.php">
                            <span class="icon"><i class="fas fachart-line"></i></span>
                            <span class="title">Toplam Fal</span>
                        </a>
                </li>
                        <li>
                            <a href="index.php">
                                <span class="icon"><i class="fas fa-signout-alt"></i></span>
                                <span class="title">Çıkış Yap</span>
                            </a>
                        </li>
                    </ul>
                </div>
                <div class="main">
                    <div class="topbar">
                        <div class="toggle" onclick="toggleMenu();"></div>
                        <div class="search">
                            <label>
                            </label>
                        </div>
                        <div class="user">
                        </div>
                    </div>
                <div class="chart-container" style="background:transparent;display:inline-block; text-align:center; height:90vh; width:120vh; position:absolute;left:15%;top:10%;">
                </div>
                <div class="chart-container" style="background:transparent;display:inline-block; text-align:center; height:90vh; width:120vh; position:absolute;left:5%;top:10%;">
                <div clasas="selectBox">
                    <select id="coincesit">
                        <option value="566,641,591,629">Bitcoin</option>
                        <option value="466,341,491,529">Ethereum</option>
                        <option value="666,541,791,529">BNB</option>
                        <option value="xrp">Ripple</option>
                        <option value="doge">Dogecoin</option>
                        <option value="ada">Cardano</option>
                        <option value="Sol">Solana</option>
                        <option value="trx">TRON</option>
                        <option value="avax">Avalanche</option>
                        <option value="ltc">Litecoin</option>
                    </select>
                </div>
                        <label class="" for="myChart1">Token Analizi</label>
                        <canvas id="myChart1"></canvas>
                </div>
            </div>
        <script>
            function toggleMenu() {
                let toggle = document.querySelector('.toggle');
                let navigation = document.querySelector('.navigation');
                let main = document.querySelector('.main');
                toggle.classList.toggle('active');
                navigation.classList.toggle('active');
                main.classList.toggle('active');
            }
        </script>
        <script>
         const coincesit = document.getElementById('coincesit');
         coincesit.addEventListener('change',cointracker);
            function cointracker(){
                const label = coincesit.options[coincesit.selectedIndex].text;
                myChart1.data.datasets[0].label = label;
                console.log(myChart1.data.datasets[0].data = coincesit.value.split(','));
                myChart1.update();
            }
            const myChart1 = new Chart(document.getElementById('myChart1'),
            config
            );
        </script>
</body>
</html>
</code>```

I tried to change the query style from other projects but couldn't implement it to my project perfectly I guess. I want my charts to get data from MySQL.

ContentLicense: CC BY-SA 4.0

Body:
I'm having a issue with my charts like I stated in the title. When I try to get my data from MySQL graph disappears and I'm not getting any errors. but graph perfectly works when I'm entering them myself. What could possibly be the fault here? I'm pretty new in this so the code can be a little bit bad sorry for that in advance. Thank you.

<?php

include('./connection.php');

?>

            <!DOCTYPE html>

                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initialscale=1.0">
                <title>Nisantasi Cafe</title>
                <link rel="stylesheet" type="text/css" href="grafic1.css">
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

NCS

                                Ana Sayfa

                        Broşürcü

                        Fal Dağılımı

                        Falcı

                            Toplam Fal

                                Çıkış Yap

                    <select id="coincesit">
                        <option value="566,641,591,629">Bitcoin</option>
                        <option value="466,341,491,529">Ethereum</option>
                        <option value="666,541,791,529">BNB</option>
                        <option value="xrp">Ripple</option>
                        <option value="doge">Dogecoin</option>
                        <option value="ada">Cardano</option>
                        <option value="Sol">Solana</option>
                        <option value="trx">TRON</option>
                        <option value="avax">Avalanche</option>
                        <option value="ltc">Litecoin</option>
                    </select>

                        Token Analizi
                        <canvas id="myChart1"></canvas>

I tried to change the query style from other projects but couldn't implement it to my project perfectly I guess. I want my charts to get data from MySQL.


问:
How to run in parallel several docker services on a docker-compose file and then check for the global status code?
I need to test a python application on different environments (different python versions, different pip packages) with pytest. For that, I created a Dockerfile which accepts different build arguments, and fill those args from a docker compose template, like this:

```<code>version: '3.9'
services:
  python37:
    image: py3.7.0
    build:
      context: .
      args:
        PYTHON_VER: "3.7.0"
        PIP_VER: "19.0.3"
        NUMPY_VER: "1.17.5"
        PANDAS_VER: "0.24.0"
        SKLEARN_VER: "0.19.2"
  python38:
    image: py3.8.0
    build:
      context: .
      args:
        PYTHON_VER: "3.8.0"
        PIP_VER: "20.3.2"
        NUMPY_VER: "1.20.0"
        PANDAS_VER: "1.0.0"
        SKLEARN_VER: "0.24.2"
  python310:
    image: py3.10.0
    build:
      context: .
      args:
        PYTHON_VER: "3.10.0"
        PIP_VER: "22.3.1"
        NUMPY_VER: "1.24.0"
        PANDAS_VER: "1.5.2"
        SKLEARN_VER: "1.2.0"
</code>```

The CMD in the Dockerfile just calls pytest over some test I've defined.
What I want is to run all services, as in docker-compose up but in a way that if any of the services fails its tests, then the whole execution should also fail.

I've tried docker-compose up --exit-code-from but this only works for a particular service and I want to check the global exit code

Also tried docker-compose up --abort-on-container-exit but the returning code of this is seems to be always 0.

How can I achieve that?

Body:
I need to test a python application on different environments (different python versions, different pip packages) with pytest. For that, I created a Dockerfile which accepts different build arguments, and fill those args from a docker compose template, like this:

version: '3.9'
services:
  python37:
    image: py3.7.0
    build:
      context: .
      args:
        PYTHON_VER: "3.7.0"
        PIP_VER: "19.0.3"
        NUMPY_VER: "1.17.5"
        PANDAS_VER: "0.24.0"
        SKLEARN_VER: "0.19.2"
  python38:
    image: py3.8.0
    build:
      context: .
      args:
        PYTHON_VER: "3.8.0"
        PIP_VER: "20.3.2"
        NUMPY_VER: "1.20.0"
        PANDAS_VER: "1.0.0"
        SKLEARN_VER: "0.24.2"
  python310:
    image: py3.10.0
    build:
      context: .
      args:
        PYTHON_VER: "3.10.0"
        PIP_VER: "22.3.1"
        NUMPY_VER: "1.24.0"
        PANDAS_VER: "1.5.2"
        SKLEARN_VER: "1.2.0"

The CMD in the Dockerfile just calls pytest over some test I've defined.
What I want is to run all services, as in docker-compose up but in a way that if any of the services fails its tests, then the whole execution should also fail.

I've tried docker-compose up --exit-code-from but this only works for a particular service and I want to check the global exit code

Also tried docker-compose up --abort-on-container-exit but the returning code of this is seems to be always 0.

How can I achieve that?


问:
How can i make a canvas that updates in real time for all users?
I want to create a canvas that updates in real time for my RPG web game, that I'm developing with React. I want make a map editor that updates itself in real time for all players. The canvas is the best option or there are a better way?

I was trying to do it with Socket.io library, but I have no idea how to do it and neither where I should start it.


问:
Woocommerce tie two membership statusses together
I have membership setup which is linked to a subscription when a product is purchased. I want to add another membership for elite members but I want to tie it to the first membership. So if membership A which is linked to a subscription expires then membership B must also expire.

So membership B must be linked to Membership A as it's a requirement to have a active membership A in order to have membership b.

How can I do this?

Have not managed to find a solution


问:
Trigger to Autoupdate tables with joins in PostgreSQL and cross database Foreign Data Wrapper
Hello fellow stack overflow wizards. I need to create a Trigger and a Trigger function in a PostgreSQL DB that updates a table from the DB "B" which is connected to DB "A" through Foreign Data Wrapper (FDW). My goal is to have a table in Database B that is automatically updated when a table from database A is changed (Since i'm using FDW, i'm joining the tables in database B, as they have the same data as in DB A). Here's a schema:

Database A

Table 1
Table 2
Table 3
Table 4

Database B

Table 1
Table 2
Table 3
Table 4
Table Join 1-2

I've tried this code for the Trigger Function

```<code>create or replace function update.table()
returns trigger AS $$
BEGIN
if new.table1.column<>old.table1.column
then
    INSERT INTO Table join 1-2 (column 1 <from table 1>,
                          column 2 <from table 2>,
                          column 3 <from table 1>,
                          column 4 <from table 2>
                          )

    VALUES (NEW.Column 1,
            NEW.Column 2,
            NEW.column 3,
            NEW.column 4
            );

RETURN NULL;

END if;
END;
$$ LANGUAGE PLPGSQL;
</code>```

And this code for the Trigger

```<code>CREATE trigger tg_update
    AFTER insert or update
    on table A
FOR EACH ROW
    EXECUTE PROCEDURE update.table();
</code>```

It's not working, the data in the Table join 1-2 is not being updated, altough the trigger function and the trigger itself didn't show any errors

Thanks in advance for any ideas or help! I'm also struggling to find content and examples for triggers in PostgreSQL, if you know a good place to find this kind of content, i would appreciate to know!

Body:
Hello fellow stack overflow wizards. I need to create a Trigger and a Trigger function in a PostgreSQL DB that updates a table from the DB "B" which is connected to DB "A" through Foreign Data Wrapper (FDW). My goal is to have a table in Database B that is automatically updated when a table from database A is changed (Since i'm using FDW, i'm joining the tables in database B, as they have the same data as in DB A). Here's a schema:

Database A

Table 1
Table 2
Table 3
Table 4

Database B

Table 1
Table 2
Table 3
Table 4
Table Join 1-2

I've tried this code for the Trigger Function

create or replace function update.table()
returns trigger AS $$
BEGIN
if new.table1.column<>old.table1.column
then
    INSERT INTO Table join 1-2 (column 1 <from table 1>,
                          column 2 <from table 2>,
                          column 3 <from table 1>,
                          column 4 <from table 2>
                          )

    VALUES (NEW.Column 1,
            NEW.Column 2,
            NEW.column 3,
            NEW.column 4
            );

RETURN NULL;

END if;
END;
$$ LANGUAGE PLPGSQL;

And this code for the Trigger

CREATE trigger tg_update
    AFTER insert or update
    on table A
FOR EACH ROW
    EXECUTE PROCEDURE update.table();

It's not working, the data in the Table join 1-2 is not being updated, altough the trigger function and the trigger itself didn't show any errors

Thanks in advance for any ideas or help! I'm also struggling to find content and examples for triggers in PostgreSQL, if you know a good place to find this kind of content, i would appreciate to know!


问:
Docker-compose container postgresql not available at localhost:5432
I am having the same issue as here, but with Docker-Compose.
Docker container for Postgres 9.1 not exposing port 5432 to host

Please, note, that I am running Docker on Windows 10.

This is the error that I am still getting

And yes, I've tried using docker inspect with container id and indeed got db IP address and managed to connect to it in PGAdmin, but that IP address changes every time I rerun the container.
For example: at one launch it was 172.22.02 and at the next one it was 172.19.0.3 .

When I deploy my whole application I will need to refer to postgresql database by a stable, not-changing IP address, else, I suppose, my application will not start correctly even once.

I have 4 containers in docker-compose: redis, redis-insight, PGAdmin and postgresql.
I successfully access these containers:

redis via localhost:6379

redis_insight via localhost:6380

pgadmin via localhost:8080

But I can't access db (which is postgresql db) via localhost:5432 .

It just makes no sense to me, and I've wasted several hours searching for a solution, I have absolutely no idea how to solve this.

Please, help me. Thanks.

This is my docker-compose.yml:

```<code>version: '3.8'
services:

  db:
    image: postgres:14.1-alpine3.15
    ports:
      - '5432:5432'
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=1234
      - POSTGRES_DB=telegram_bot_db
    restart: always
    container_name: db
    volumes:
      - db:/var/lib/postgresql/data

  pgadmin:
    image: dpage/pgadmin4:latest
    container_name: pgadmin
    restart: always
    depends_on:
      - db
    environment:
      PGADMIN_DEFAULT_EMAIL: some@nicemail.com
      PGADMIN_DEFAULT_PASSWORD: nice
      PGADMIN_LISTEN_PORT: 80
    ports:
      - '8080:80'
    volumes:
      - pgadmin:/var/lib/pgadmin

  redis:
    image: redis
    container_name: redis
    restart: always
    ports:
      - '6379:6379'
    command: redis-server --save 20 1 --loglevel warning --requirepass qwe123qwe
    volumes:
      - redis:/data

  redis_insight:
    image: redislabs/redisinsight:latest
    container_name: redis_insight
    restart: always
    depends_on:
      - redis
    ports:
      - '6380:8001'
    volumes:
      - redis_insight:/db

volumes:
  db:
    driver: local
  redis:
    driver: local
  redis_insight:
    driver: local
  pgadmin:
    driver: local
</code>```

Body:
I am having the same issue as here, but with Docker-Compose.
Docker container for Postgres 9.1 not exposing port 5432 to host

Please, note, that I am running Docker on Windows 10.

This is the error that I am still getting

And yes, I've tried using docker inspect with container id and indeed got db IP address and managed to connect to it in PGAdmin, but that IP address changes every time I rerun the container.
For example: at one launch it was 172.22.02 and at the next one it was 172.19.0.3 .

When I deploy my whole application I will need to refer to postgresql database by a stable, not-changing IP address, else, I suppose, my application will not start correctly even once.

I have 4 containers in docker-compose: redis, redis-insight, PGAdmin and postgresql.
I successfully access these containers:

redis via localhost:6379

redis_insight via localhost:6380

pgadmin via localhost:8080

But I can't access db (which is postgresql db) via localhost:5432 .

It just makes no sense to me, and I've wasted several hours searching for a solution, I have absolutely no idea how to solve this.

Please, help me. Thanks.

This is my docker-compose.yml:

version: '3.8'
services:

  db:
    image: postgres:14.1-alpine3.15
    ports:
      - '5432:5432'
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=1234
      - POSTGRES_DB=telegram_bot_db
    restart: always
    container_name: db
    volumes:
      - db:/var/lib/postgresql/data

  pgadmin:
    image: dpage/pgadmin4:latest
    container_name: pgadmin
    restart: always
    depends_on:
      - db
    environment:
      PGADMIN_DEFAULT_EMAIL: some@nicemail.com
      PGADMIN_DEFAULT_PASSWORD: nice
      PGADMIN_LISTEN_PORT: 80
    ports:
      - '8080:80'
    volumes:
      - pgadmin:/var/lib/pgadmin

  redis:
    image: redis
    container_name: redis
    restart: always
    ports:
      - '6379:6379'
    command: redis-server --save 20 1 --loglevel warning --requirepass qwe123qwe
    volumes:
      - redis:/data

  redis_insight:
    image: redislabs/redisinsight:latest
    container_name: redis_insight
    restart: always
    depends_on:
      - redis
    ports:
      - '6380:8001'
    volumes:
      - redis_insight:/db

volumes:
  db:
    driver: local
  redis:
    driver: local
  redis_insight:
    driver: local
  pgadmin:
    driver: local


问:
How to add values by using a sequence in plsql if only the field is null?
I need to add values for a number field and if only it is null, then I have to add a number by using a sequence. I have created the code for this. But since this field is a unique field
I can't add duplicate values. For example as the first record if I entered number 1 and in the next record if I not pass a value for that field, it will automatically generate a value and if its equals to a old record number its showing an error like record already exists. Can someone help me to solve this.</p>
```<code>PROCEDURE InsertValues(
newrec_ IN OUT myTable%ROWTYPE,
indrec_ IN OUT Indicator_Rec,
attr_   IN OUT VARCHAR2 )
IS
BEGIN

IF(newrec_.id IS null) then
newrec_.id := myTable_id.NEXTVAL;

Client_SYS.Add_To_Attr('ID', newrec_.id, attr_);

END IF;
super(newrec_, indrec_, attr_);

END InsertValues;
</code>```

Body:
I need to add values for a number field and if only it is null, then I have to add a number by using a sequence. I have created the code for this. But since this field is a unique field
I can't add duplicate values. For example as the first record if I entered number 1 and in the next record if I not pass a value for that field, it will automatically generate a value and if its equals to a old record number its showing an error like record already exists. Can someone help me to solve this.

PROCEDURE InsertValues(
newrec_ IN OUT myTable%ROWTYPE,
indrec_ IN OUT Indicator_Rec,
attr_   IN OUT VARCHAR2 )
IS
BEGIN

IF(newrec_.id IS null) then
newrec_.id := myTable_id.NEXTVAL;

Client_SYS.Add_To_Attr('ID', newrec_.id, attr_);

END IF;
super(newrec_, indrec_, attr_);

END InsertValues;


问:
My elif statements are having syntax errors -python
I'm making a menu based tool and when the interpreter gets to the 3rd elif (4th option) it gives me a syntax error.

I am using debians vim command to code.
Here is the error:

```<code> elif (sel == "3"):
    ^^^^

</code>```

I tried:

```<code>elif (sel == "4"):
        toat = "txt.att.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
</code>```

But I only got the error i mentioned earlier. I made as many many edits as I could find but none worked.

heres the whole piece of code:

```<code>HOST = "smtp.gmail.com"
CARRIERS = ["verizon", "tmobile", "sprint", "atnt", "boost", "cricket", "uscellular", "mint"]
CARRIER_ADRESSES = ["vtext.com", "tmomail.net", "messaging.sprintpcs.com", "txt.att.net", "smsmyboostmobile.com", "sms.cricketwireless.net", "email.uscc.net"]
toat = ""
target = input("Target Phone Number")
fromail = input("Your Email")
victim = (target,"@",toat)
#set up vars and lists
menu = True
while menu:
    print("[1] verizon")
    print("[2] tmobile")
    print("[3] sprint")
    print("[4] atnt")
    print("[5] boost")
    print("[6] cricket")
    print("[7] uscellular")
    print("[8] mint")
#Carrier Menu
    sel = input("Select Carrier")
    if (sel == "1"):
        toat = "vtext.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "2"):
        toat = "tmomail.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
        elif (sel == "3"):
        toat = "messaging.sprintpcs.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
    def spam():
            s.send_message(msg)
            return spam()
    def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
    def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
    for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "4"):
        toat = "txt.att.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "5"):
        toat = "smsmyboostmobile.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "6"):
        toat = "sms.cricketwireless.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "7"):
        toat = "email.uscc.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "8"):
        toat = "tmomail.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
    s = smtplib.SMTP('localhost')
#Main set-up complete time for spam
</code>```

Body:
I'm making a menu based tool and when the interpreter gets to the 3rd elif (4th option) it gives me a syntax error.

I am using debians vim command to code.
Here is the error:

 elif (sel == "3"):
    ^^^^

I tried:

elif (sel == "4"):
        toat = "txt.att.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()

But I only got the error i mentioned earlier. I made as many many edits as I could find but none worked.

heres the whole piece of code:

HOST = "smtp.gmail.com"
CARRIERS = ["verizon", "tmobile", "sprint", "atnt", "boost", "cricket", "uscellular", "mint"]
CARRIER_ADRESSES = ["vtext.com", "tmomail.net", "messaging.sprintpcs.com", "txt.att.net", "smsmyboostmobile.com", "sms.cricketwireless.net", "email.uscc.net"]
toat = ""
target = input("Target Phone Number")
fromail = input("Your Email")
victim = (target,"@",toat)
#set up vars and lists
menu = True
while menu:
    print("[1] verizon")
    print("[2] tmobile")
    print("[3] sprint")
    print("[4] atnt")
    print("[5] boost")
    print("[6] cricket")
    print("[7] uscellular")
    print("[8] mint")
#Carrier Menu
    sel = input("Select Carrier")
    if (sel == "1"):
        toat = "vtext.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "2"):
        toat = "tmomail.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
        elif (sel == "3"):
        toat = "messaging.sprintpcs.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
    def spam():
            s.send_message(msg)
            return spam()
    def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
    def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
    for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "4"):
        toat = "txt.att.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "5"):
        toat = "smsmyboostmobile.com"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "6"):
        toat = "sms.cricketwireless.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "7"):
        toat = "email.uscc.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
        s = smtplib.SMTP('localhost')
    #Main set-up complete time for spam
        def spam():
            s.send_message(msg)
            return spam()
        def spam2():
            s.send_message(msg)
            s.send_message(msg)
            spam()
            return spam2()
        def spam3():
            s.send_message(msg)
            s.send_message(msg)
            s.send_message(msg)
            spam2()
            return spam3()
        for i in range(1,17):
            TrueSpam = threading.Thread(target = spam3)
            x.start()
    elif (sel == "8"):
        toat = "tmomail.net"
        with open(eee.txt) as fp:
            msg = EmailMessage()
            msg.set_content(fp.read())
        msg['Subject'] = f'The contents of {eee.txt}'
        msg['From'] = fromail
        msg['To'] = victim
    s = smtplib.SMTP('localhost')
#Main set-up complete time for spam


问:
I am trying to create a Token on the Ethereum Blockchain but it is giving me a "ReferenceError" every time I run the code
Here is my Code:

```<code>const { expect } = require("chai");
const hre = require("hardhat");

describe("JaiToken contract", function() {

    let Token;
    let jaiToken;
    let owner;
    let addr1;
    let addr2;
    let tokenCap = 50000000;
    let tokenBlockReward = 20;

    beforeEach(async function () {

        Token = await ethers.getContractFactory("JaiToken");
        [owner, addr1, addr2] = await hre.ethers.getSigners();

        jaiToken = await Token.deploy(tokenCap, tokenBlockReward);
    });

    describe("Deployment", function () {
        it("Should set the right owner", async function () {
          expect(await jaiToken.owner()).to.equal(owner.address);
        });

        it("Should assign the total supply of tokens to the owner", async function () {
          const ownerBalance = await jaiToken.balanceOf(owner.address);
          expect(await jaiToken.totalSupply()).to.equal(ownerBalance);
        });

        it("Should set the max capped supply to the argument provided during deployment", async function () {
          const cap = await jaiToken.cap();
          expect(Number(hre.ethers.utils.formatEther(cap))).to.equal(tokenCap);
        });

        it("Should set the blockReward to the argument provided during deployment", async function () {
          const blockReward = await jaiToken.blockReward();
          expect(Number(hre.ethers.utils.formatEther(blockReward))).to.equal(tokenBlockReward);
        });
      });

      describe("Transactions", function () {
        it("Should transfer tokens between accounts", async function () {
          // Transfer 50 tokens from owner to addr1
          await jaiToken.transfer(addr1.address, 50);
          const addr1Balance = await jaiToken.balanceOf(addr1.address);
          expect(addr1Balance).to.equal(50);

          // Transfer 50 tokens from addr1 to addr2
          // We use .connect(signer) to send a transaction from another account
          await jaiToken.connect(addr1).transfer(addr2.address, 50);
          const addr2Balance = await jaiToken.balanceOf(addr2.address);
          expect(addr2Balance).to.equal(50);
        });

        it("Should fail if sender doesn't have enough tokens", async function () {
          const initialOwnerBalance = await jaiToken.balanceOf(owner.address);
          // Try to send 1 token from addr1 (0 tokens) to owner (1000000 tokens).
          // `require` will evaluate false and revert the transaction.
          await expect(
            jaiToken.connect(addr1).transfer(owner.address, 1)
          ).to.be.revertedWith("ERC20: transfer amount exceeds balance");

          // Owner balance shouldn't have changed.
          expect(await jaiToken.balanceOf(owner.address)).to.equal(
            initialOwnerBalance
          );
        });

        it("Should update balances after transfers", async function () {
          const initialOwnerBalance = await jaiToken.balanceOf(owner.address);

          // Transfer 100 tokens from owner to addr1.
          await jaiToken.transfer(addr1.address, 100);

          // Transfer another 50 tokens from owner to addr2.
          await jaiToken.transfer(addr2.address, 50);

          // Check balances.
          const finalOwnerBalance = await jaiToken.balanceOf(owner.address);
          expect(finalOwnerBalance).to.equal(initialOwnerBalance.sub(150));

          const addr1Balance = await jaiToken.balanceOf(addr1.address);
          expect(addr1Balance).to.equal(100);

          const addr2Balance = await jaiToken.balanceOf(addr2.address);
          expect(addr2Balance).to.equal(50);
      });
    });

  });
</code>```

Here is my Error:

```<code>describe("JaiToken contract", function() {
^

ReferenceError: describe is not defined
    at Object.<anonymous> (/Users/owner/Desktop/HTML/JaiToken/Jai-Token/test/JaiToken.js:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v17.4.0
</code>```

I was expecting that all 7 tests ran will be passed in the Terminal and check out, instead it throws the Describe Error. I looked through my code multiple times and researched on this error but cannot find out what is wrong. I am using VS Code as my editor or maybe I did not download the right things. This contract is used to apply functionality to my Tokens such as setting the Balance, Cap, making sure it is the Owner, and setting the Block Reward for whom who adds the transaction on the Blockchain. I also have already checked that this file is in the Test file and that these are all test I am running. Please Help!

Body:
Here is my Code:

const { expect } = require("chai");
const hre = require("hardhat");

describe("JaiToken contract", function() {

    let Token;
    let jaiToken;
    let owner;
    let addr1;
    let addr2;
    let tokenCap = 50000000;
    let tokenBlockReward = 20;

    beforeEach(async function () {

        Token = await ethers.getContractFactory("JaiToken");
        [owner, addr1, addr2] = await hre.ethers.getSigners();

        jaiToken = await Token.deploy(tokenCap, tokenBlockReward);
    });

    describe("Deployment", function () {
        it("Should set the right owner", async function () {
          expect(await jaiToken.owner()).to.equal(owner.address);
        });

        it("Should assign the total supply of tokens to the owner", async function () {
          const ownerBalance = await jaiToken.balanceOf(owner.address);
          expect(await jaiToken.totalSupply()).to.equal(ownerBalance);
        });

        it("Should set the max capped supply to the argument provided during deployment", async function () {
          const cap = await jaiToken.cap();
          expect(Number(hre.ethers.utils.formatEther(cap))).to.equal(tokenCap);
        });

        it("Should set the blockReward to the argument provided during deployment", async function () {
          const blockReward = await jaiToken.blockReward();
          expect(Number(hre.ethers.utils.formatEther(blockReward))).to.equal(tokenBlockReward);
        });
      });

      describe("Transactions", function () {
        it("Should transfer tokens between accounts", async function () {
          // Transfer 50 tokens from owner to addr1
          await jaiToken.transfer(addr1.address, 50);
          const addr1Balance = await jaiToken.balanceOf(addr1.address);
          expect(addr1Balance).to.equal(50);

          // Transfer 50 tokens from addr1 to addr2
          // We use .connect(signer) to send a transaction from another account
          await jaiToken.connect(addr1).transfer(addr2.address, 50);
          const addr2Balance = await jaiToken.balanceOf(addr2.address);
          expect(addr2Balance).to.equal(50);
        });

        it("Should fail if sender doesn't have enough tokens", async function () {
          const initialOwnerBalance = await jaiToken.balanceOf(owner.address);
          // Try to send 1 token from addr1 (0 tokens) to owner (1000000 tokens).
          // `require` will evaluate false and revert the transaction.
          await expect(
            jaiToken.connect(addr1).transfer(owner.address, 1)
          ).to.be.revertedWith("ERC20: transfer amount exceeds balance");

          // Owner balance shouldn't have changed.
          expect(await jaiToken.balanceOf(owner.address)).to.equal(
            initialOwnerBalance
          );
        });

        it("Should update balances after transfers", async function () {
          const initialOwnerBalance = await jaiToken.balanceOf(owner.address);

          // Transfer 100 tokens from owner to addr1.
          await jaiToken.transfer(addr1.address, 100);

          // Transfer another 50 tokens from owner to addr2.
          await jaiToken.transfer(addr2.address, 50);

          // Check balances.
          const finalOwnerBalance = await jaiToken.balanceOf(owner.address);
          expect(finalOwnerBalance).to.equal(initialOwnerBalance.sub(150));

          const addr1Balance = await jaiToken.balanceOf(addr1.address);
          expect(addr1Balance).to.equal(100);

          const addr2Balance = await jaiToken.balanceOf(addr2.address);
          expect(addr2Balance).to.equal(50);
      });
    });

  });

Here is my Error:

describe("JaiToken contract", function() {
^

ReferenceError: describe is not defined
    at Object.<anonymous> (/Users/owner/Desktop/HTML/JaiToken/Jai-Token/test/JaiToken.js:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v17.4.0

I was expecting that all 7 tests ran will be passed in the Terminal and check out, instead it throws the Describe Error. I looked through my code multiple times and researched on this error but cannot find out what is wrong. I am using VS Code as my editor or maybe I did not download the right things. This contract is used to apply functionality to my Tokens such as setting the Balance, Cap, making sure it is the Owner, and setting the Block Reward for whom who adds the transaction on the Blockchain. I also have already checked that this file is in the Test file and that these are all test I am running. Please Help!


问:
why separate url for reCAPTCHA v3 trusted types?
Google reCAPTCHA v3 has an option to use a script compatible with Trusted Types.  I'm curious why they provide the option and don't just write their script that way by default. Is there a potential compatibility issue with older browsers or slower performance or maybe they just want the option as a means to educate on trusted types?

https://developers.google.com/recaptcha/docs/v3#tips

https://www.google.com/recaptcha/api.js?trustedtypes=true
vs
https://www.google.com/recaptcha/api.js


问:
font-icons.woff 404 not found with micro frontend
I'm developing a micro frontend, for this I use Webpack 5 Module Federation and ngx-build-plus builder on an Angular 14 application.

When I build my project I get the following files:

dist
├── my-webco
│   ├── 106.js
│   ├── 136.js
│   ├── 497.js
│   ├──    .
│   ├──    .
│   ├──    .
│   ├── icon-font.woff
│   ├── icon-font.woff2
│   ├── index.html
│   ├── main.js
│   ├── remoteEntry.js
│   ├── style.css```
</div>
</div>
</p>
<p>So I want to import the main.js file into another application this way:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://my-host/my-webco/main.js" type="text/javascript"></script>
<my-web-component></my-web-component></code>```

The webcomponent works well but I have a 404 error on the font because my font is on the path "https://my-host/my-webco/font-icons.woff" and my application will load it on the path "https://my-host/font-icons.woff".

do you know where I can set up this path?

Body:
I'm developing a micro frontend, for this I use Webpack 5 Module Federation and ngx-build-plus builder on an Angular 14 application.

When I build my project I get the following files:

dist
├── my-webco
│   ├── 106.js
│   ├── 136.js
│   ├── 497.js
│   ├──    .
│   ├──    .
│   ├──    .
│   ├── icon-font.woff
│   ├── icon-font.woff2
│   ├── index.html
│   ├── main.js
│   ├── remoteEntry.js
│   ├── style.css

So I want to import the main.js file into another application this way:

<my-web-component></my-web-component>

The webcomponent works well but I have a 404 error on the font because my font is on the path "https://my-host/my-webco/font-icons.woff" and my application will load it on the path "https://my-host/font-icons.woff".

do you know where I can set up this path?


问:
How to handle synchronize (rsync) permission errors in Ansible?
We got Permission Denied error when using rsync via synchronize module in Ansible, using sysadmin account, that's an administrative account. Using a remote account, the owner of the destination directories and files, ended with the same result.

Command

ansible-playbook -u sysadmin -i ./inventories/hosts scripts-sync.yml -K
```
<p><strong><code>scripts-sync.yml</code></strong></p>
<pre class="lang-yaml prettyprint-override"><code>- name: Copy scripts to batch server
  synchronize:
    src: scripts
    dest: /dest/scripts/
    recursive: true
</code>```

Error Message

fatal: [batch]: FAILED! => {"changed": false, "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -i /data/ansible/key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --out-format='<<CHANGED>>%i %n%L' /data/ansible/scripts/ sysadmin@10.104.XX.XX:/dest/scripts/", "msg": "Warning: Permanently added '10.104.XX.XX' (ECDSA) to the list of known hosts.\r\nrsync: failed to set times on \"/dest/scripts/\": Operation not permitted (1)\nrsync: failed to set times on \"/dest/scripts/batch\": Operation not permitted (1)\nrsync: recv_generator: mkdir \"/dest/scripts/docs\" failed: Permission denied (13)\n*** Skipping any contents from this failed directory ***\nrsync: failed to set times on \"/dest/scripts/tests\": Operation not permitted (1)\nrsync: connection unexpectedly closed (1748 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.2]\n", "rc": 12}
```
<p>I imagine this error caused by that administrative account has no permission to change the timestamp of the destination files.</p>
<p>Is there an options or setting to achieve <code>rsync</code> not to change the account and owner of the destination files?</p>
<p><strong>Additional Info</strong></p>
<p>We found destination directory had the other owner's hidden files, made by CI/CD pipeline tool. Also confirmed <code>rsync</code> command has been successfully, as long as we don't set <code>-t</code> (timestamp) and <code>-p</code> (permission) options, changed options from <code>--archive</code> (<code>--rlptgoD</code>) to <code>-rlgoD</code>.</p>
<pre class="lang-bash prettyprint-override"><code>rsync --delay-updates -F --compress -rlgoD --rsh='/usr/bin/ssh -S none -i /data/ansible/key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --out-format='<<CHANGED>>%i %n%L' /data/ansible/scripts/ sysadmin@10.104.XX.XX:/dest/scripts/
</code>```

Is there any option in Ansible synchronize module same as -rlgoD?

Body:
We got Permission Denied error when using rsync via synchronize module in Ansible, using sysadmin account, that's an administrative account. Using a remote account, the owner of the destination directories and files, ended with the same result.

Command

ansible-playbook -u sysadmin -i ./inventories/hosts scripts-sync.yml -K

scripts-sync.yml

- name: Copy scripts to batch server
  synchronize:
    src: scripts
    dest: /dest/scripts/
    recursive: true

Error Message

fatal: [batch]: FAILED! => {"changed": false, "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -i /data/ansible/key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --out-format='<<CHANGED>>%i %n%L' /data/ansible/scripts/ sysadmin@10.104.XX.XX:/dest/scripts/", "msg": "Warning: Permanently added '10.104.XX.XX' (ECDSA) to the list of known hosts.\r\nrsync: failed to set times on \"/dest/scripts/\": Operation not permitted (1)\nrsync: failed to set times on \"/dest/scripts/batch\": Operation not permitted (1)\nrsync: recv_generator: mkdir \"/dest/scripts/docs\" failed: Permission denied (13)\n*** Skipping any contents from this failed directory ***\nrsync: failed to set times on \"/dest/scripts/tests\": Operation not permitted (1)\nrsync: connection unexpectedly closed (1748 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.2]\n", "rc": 12}

I imagine this error caused by that administrative account has no permission to change the timestamp of the destination files.

Is there an options or setting to achieve rsync not to change the account and owner of the destination files?

Additional Info

We found destination directory had the other owner's hidden files, made by CI/CD pipeline tool. Also confirmed rsync command has been successfully, as long as we don't set -t (timestamp) and -p (permission) options, changed options from --archive (--rlptgoD) to -rlgoD.

rsync --delay-updates -F --compress -rlgoD --rsh='/usr/bin/ssh -S none -i /data/ansible/key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --out-format='<<CHANGED>>%i %n%L' /data/ansible/scripts/ sysadmin@10.104.XX.XX:/dest/scripts/

Is there any option in Ansible synchronize module same as -rlgoD?


问:
Django pass value to subquery inside annotate in a query set with mptt
i have a class based on ListCreateAPIView where i'm modifing get_queryset method..
i need pass inside a subquery for an annotate a paramether but seem OutherRef dosen't work

i'm using Mptt library ....
subqueryItem works fine,
subqueryNested instead says "This queryset contains a reference to an outer query and may only be used in a subquery."

```<code>  def get_queryset(self):
    queryset = super().get_queryset()

        subqueryItem = Subquery(Item.objects.filter(category=OuterRef('id')).order_by()
                        .values('category').annotate(count=Count('pk'))
                        .values('count'), output_field=IntegerField())

        subqueryNested = Subquery(Item.objects.filter(category__in=ItemCategory.objects.get(pk=OuterRef('id')).get_descendants(include_self=True)).order_by()
                        .values('category').annotate(count=Count('pk'))
                        .values('count'), output_field=IntegerField())

        queryset = queryset.annotate(
            collcount        = Coalesce(subqueryItem, 0),
            collcountdeep    = Coalesce(subqueryNested, 0),
        )
</code>```

Body:
i have a class based on ListCreateAPIView where i'm modifing get_queryset method..
i need pass inside a subquery for an annotate a paramether but seem OutherRef dosen't work

i'm using Mptt library ....
subqueryItem works fine,
subqueryNested instead says "This queryset contains a reference to an outer query and may only be used in a subquery."

  def get_queryset(self):
    queryset = super().get_queryset()

        subqueryItem = Subquery(Item.objects.filter(category=OuterRef('id')).order_by()
                        .values('category').annotate(count=Count('pk'))
                        .values('count'), output_field=IntegerField())

        subqueryNested = Subquery(Item.objects.filter(category__in=ItemCategory.objects.get(pk=OuterRef('id')).get_descendants(include_self=True)).order_by()
                        .values('category').annotate(count=Count('pk'))
                        .values('count'), output_field=IntegerField())

        queryset = queryset.annotate(
            collcount        = Coalesce(subqueryItem, 0),
            collcountdeep    = Coalesce(subqueryNested, 0),
        )


问:
how to correct the mongodb error i get here
```<code>D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\utils.js:698
          throw error;
          ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)
Emitted 'error' event on Database instance at:
    at D:\Others\HTML\login node\node_modules\mongojs\lib\database.js:36:16
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\utils.js:695:9
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\mongo_client.js:285:23
    at connectCallback (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\operations\connect.js:367:5)
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\operations\connect.js:554:14
    at Object.connectHandler [as callback] (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:286:11)
    at Timeout._onTimeout (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:443:25)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Single',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        error: Error: connect ECONNREFUSED ::1:27017
            at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
          name: 'MongoNetworkError'
        },
        roundTripTime: -1,
        lastUpdateTime: 157429114,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      }
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...

</code>```

im new and i havent tried much
i encounter this error whenever i try to psot details into the login page
details are being forwarded through the localhost to the node server but the mongodb database is throwing error

how to correct this error anyone help

whats this error what does this even mean

Body:
D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\utils.js:698
          throw error;
          ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)
Emitted 'error' event on Database instance at:
    at D:\Others\HTML\login node\node_modules\mongojs\lib\database.js:36:16
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\utils.js:695:9
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\mongo_client.js:285:23
    at connectCallback (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\operations\connect.js:367:5)
    at D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\operations\connect.js:554:14
    at Object.connectHandler [as callback] (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:286:11)
    at Timeout._onTimeout (D:\Others\HTML\login node\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:443:25)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Single',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        error: Error: connect ECONNREFUSED ::1:27017
            at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
          name: 'MongoNetworkError'
        },
        roundTripTime: -1,
        lastUpdateTime: 157429114,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      }
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...

im new and i havent tried much
i encounter this error whenever i try to psot details into the login page
details are being forwarded through the localhost to the node server but the mongodb database is throwing error

how to correct this error anyone help

whats this error what does this even mean


问:
Set system proxy variables on GCP Cloud Run behind a VPC
This has been very frustrating to resolve. Is there a way to set system proxy variables for our Java-based application in GCP Cloud Run within a VPC? I've tried numerous settings in our Dockerfile, one for ENTRYPOINT and one as ENV JAVA_OPTS="-Dhttps.proxyHost=hostname -Dhttps.proxyPort=1234 -Dhttps.nonProxyHosts=localhost -Dhttp.proxyHost=..." and neither work.

We also tried setting environment variables in our Cloud Run deployment and no luck. Any ideas?

Our less ideal solution is writing a custom ProxySelector, just seems like the default one takes care of a lot more than what we'd write.

By the way, the underlying APIs our service uses is gRPC, which respects the system properties locally. Just trying to get it working in Cloud Run in a VPC. Any help would be grateful.


问:
Fit wide table in PDF when downloaded using button from renderDT/datatable
I have a shiny app that exports a data table that can be downloaded using PDF, CSV, and Excel "buttons" from DT::datatable(). However, the exported data table is very wide, and so the exported PDF is cut off on the right side. Is there a way to make the pdf export in landscape (or otherwise ensure it fits within the page)?

A minimal reproducible example using the iris dataset is here:

```<code>library(shiny)
library(DT)

ui <- fluidPage(DTOutput('tbl'))

server <- function(input, output) {
  output$tbl = renderDT(
    cbind(iris, iris), # example wide table
    extensions = "Buttons",
    options = list(
      lengthChange = FALSE,
      dom = "tB",
      buttons = c("pdf", "excel", "csv", "copy")
    )
  )
}

shinyApp(ui, server)
</code>```

In options, I have tried orientation = "landscape" and toggling between TRUE and FALSE for fixedColumns, autoWidth and scrollX. Based on this DT help page I tried changing the button to pdfHtml5 (instead of pdf) and extensions = c("Buttons", "pdfHtml5") (along with orientation = "landscape"). Unfortunately none of this worked.

I would prefer to keep within the options/functionality in the renderDT() function as opposed to a fresh approach, if possible.

Body:
I have a shiny app that exports a data table that can be downloaded using PDF, CSV, and Excel "buttons" from DT::datatable(). However, the exported data table is very wide, and so the exported PDF is cut off on the right side. Is there a way to make the pdf export in landscape (or otherwise ensure it fits within the page)?

A minimal reproducible example using the iris dataset is here:

library(shiny)
library(DT)

ui <- fluidPage(DTOutput('tbl'))

server <- function(input, output) {
  output$tbl = renderDT(
    cbind(iris, iris), # example wide table
    extensions = "Buttons",
    options = list(
      lengthChange = FALSE,
      dom = "tB",
      buttons = c("pdf", "excel", "csv", "copy")
    )
  )
}

shinyApp(ui, server)

In options, I have tried orientation = "landscape" and toggling between TRUE and FALSE for fixedColumns, autoWidth and scrollX. Based on this DT help page I tried changing the button to pdfHtml5 (instead of pdf) and extensions = c("Buttons", "pdfHtml5") (along with orientation = "landscape"). Unfortunately none of this worked.

I would prefer to keep within the options/functionality in the renderDT() function as opposed to a fresh approach, if possible.


问:
React adds `\r` to environmental variable when building on windows
My React App (in typescript) uses some environment variables stored in a .env file like so:

```<code>REACT_APP_FIREBASE_PROJECTID=my-project
REACT_APP_FIREBASE_AUTHDOMAIN=my-project.firebaseapp.com
</code>```

When building the app with react-scripts build (react-scripts) on a Mac everything works. Looking at the compiled javascript the environmental variables look like this:

```<code>REACT_APP_FIREBASE_PROJECTID:"my-project",
</code>```

However when I do the same on a Windows machine there is a \r added in the compiled javascript:

```<code>REACT_APP_FIREBASE_PROJECTID:"my-project\r",
</code>```

which leads to errors.

On both systems all files are of LF line ending. And I tried to add this:

```<code>{
    "files.eol": "\n",
}
</code>```

to the settings.json of VSCode on the windows machine, with no effect.

Body:
My React App (in typescript) uses some environment variables stored in a .env file like so:

REACT_APP_FIREBASE_PROJECTID=my-project
REACT_APP_FIREBASE_AUTHDOMAIN=my-project.firebaseapp.com

When building the app with react-scripts build (react-scripts) on a Mac everything works. Looking at the compiled javascript the environmental variables look like this:

REACT_APP_FIREBASE_PROJECTID:"my-project",

However when I do the same on a Windows machine there is a \r added in the compiled javascript:

REACT_APP_FIREBASE_PROJECTID:"my-project\r",

which leads to errors.

On both systems all files are of LF line ending. And I tried to add this:

{
    "files.eol": "\n",
}

to the settings.json of VSCode on the windows machine, with no effect.


问:
LINQ query stops working after adding 'Orderby' clause
I have a working linq query as follows:

public static List<Coins> GetAllCoins(string typeselected)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        List<Coins> allcoins = (from p in db.Table<Coins>()
                    where p.CoinType== typeselected
                    // orderby p.YearMinted
                    select p
                ).ToList();
        return allcoins;
    }
}
```

I want to get the results in order but when I uncomment the 'orderby' line, the query returns nothing.  What's up with that?

I have checked the syntax many times.  I have queried online for linq query format and I find many instances where the orderby clause is used in this manner.  I know I'm missing something but I can't figure what.  Please help!

Body:
I have a working linq query as follows:

public static List<Coins> GetAllCoins(string typeselected)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        List<Coins> allcoins = (from p in db.Table<Coins>()
                    where p.CoinType== typeselected
                    // orderby p.YearMinted
                    select p
                ).ToList();
        return allcoins;
    }
}

I want to get the results in order but when I uncomment the 'orderby' line, the query returns nothing.  What's up with that?

I have checked the syntax many times.  I have queried online for linq query format and I find many instances where the orderby clause is used in this manner.  I know I'm missing something but I can't figure what.  Please help!


问:
Excel chart Categories against variable quantity of Price Points
I have some data which I would like to plot, presumably in a scatter chart. The data is in the following format.

```<code>Category, ID
Cat1, 560000
Cat1, 560005
Cat1, 880011
Cat2, 580000
Cat2, 580001
Cat2, 580002
Cat2, 780052
Cat3, 600000
Cat3, 600010
Cat3, 600011
Cat3, 1003452
</code>```

For non-developers, you could think of this as Categories of Tyres and their Prices. I'd like to see that in the "Car" category, we sell items in a set of different price points and in the "Bicycle" category we sell items at a different set of price points. This metaphor only breaks down in that no 2 products can use the same price.

For developers out there, these are in fact a Long, Primary-Key to a particular relational database table and I'm attempting to plot how much and what parts of the available ID range have been utilised already, based on splitting the data into some categories.

I have 13 categories, so these will have to become the x axis due to excel limiting that to 255.  Therefore ID will be my Y axis.

By using a 2D Line Chart on just the IDs, and squashing the chart, I was able to plot the overall usage of the ID range.

However, I'm unable to get any chart type to split this by category - I presume XY Scatter or Heatmap has this ability somehow.

Update:- Since posting I have encountered this "Contiguity Chart" which is roughly what I'm after but in Excel if feasible
https://qvdesign.wordpress.com/2012/03/29/qlikview-contiguity-chart-aka-that-chart-from-the-windows-disk-defragmenter/

Body:
I have some data which I would like to plot, presumably in a scatter chart. The data is in the following format.

Category, ID
Cat1, 560000
Cat1, 560005
Cat1, 880011
Cat2, 580000
Cat2, 580001
Cat2, 580002
Cat2, 780052
Cat3, 600000
Cat3, 600010
Cat3, 600011
Cat3, 1003452

For non-developers, you could think of this as Categories of Tyres and their Prices. I'd like to see that in the "Car" category, we sell items in a set of different price points and in the "Bicycle" category we sell items at a different set of price points. This metaphor only breaks down in that no 2 products can use the same price.

For developers out there, these are in fact a Long, Primary-Key to a particular relational database table and I'm attempting to plot how much and what parts of the available ID range have been utilised already, based on splitting the data into some categories.

I have 13 categories, so these will have to become the x axis due to excel limiting that to 255.  Therefore ID will be my Y axis.

By using a 2D Line Chart on just the IDs, and squashing the chart, I was able to plot the overall usage of the ID range.

However, I'm unable to get any chart type to split this by category - I presume XY Scatter or Heatmap has this ability somehow.

Update:- Since posting I have encountered this "Contiguity Chart" which is roughly what I'm after but in Excel if feasible
https://qvdesign.wordpress.com/2012/03/29/qlikview-contiguity-chart-aka-that-chart-from-the-windows-disk-defragmenter/


问:
How to add drag to custom layout and change the color of the dragged surface in jetpack compose
I am using this tutorial
https://danielrampelt.com/blog/jetpack-compose-custom-schedule-layout-part-1/ and part 2
to draw a custom schedule. How can I want to use draggable inside of it so I can change the color of the dragged surface in jetpack compose. My aim is to drag an time slot vertically. This is my composable function. I have put the draggable function but I don't know how to implement it. Now my screen freezes, I can't scroll vertically.</p>
```<code>@Composable
fun DynamicSchedule(
    viewModel: CalenderViewModel,
    modifier: Modifier = Modifier,
    appointmentContent: @Composable (appointment: Appointment) -> Unit = {
        ScheduleCard(
            appointment = it
        )
    },
    minDate: LocalDate,
    maxDate: LocalDate,
    dayWidth: Dp,
    hourHeight: Dp
) {
    val numDays = ChronoUnit.DAYS.between(minDate, maxDate).toInt() + 1
    val dividerColor = if (MaterialTheme.colors.isLight) Color.LightGray else Color.DarkGray
    var offsetY by remember { mutableStateOf(0f) }
    Layout(
        content = {
            viewModel.state.value.appointmentList.sortedBy { it.startDate }

                .forEach { appointment ->
                    Box(modifier = Modifier.appointmentData(appointment)) {
                        appointmentContent(appointment)
                    }
                }
        },
        modifier = modifier
            .drawBehind {
                repeat(23) {
                    drawLine(
                        dividerColor,
                        start = Offset(0f, (it + 1) * hourHeight.toPx()),
                        end = Offset(size.width, (it + 1) * hourHeight.toPx()),
                        strokeWidth = 1.dp.toPx()
                    )
                }
                repeat(numDays - 1) {
                    drawLine(
                        dividerColor,
                        start = Offset((it + 1) * dayWidth.toPx(), 0f),
                        end = Offset((it + 1) * dayWidth.toPx(), size.height),
                        strokeWidth = 1.dp.toPx()
                    )
                }
            }
            .pointerInput(Unit) {
                detectTapGestures {
                    val x = it.x.toDp()
                    val y = it.y.toDp()
                    val time = y.value.toInt() / hourHeight.value
                    val date = (x.value.toInt() / dayWidth.value)
                    println("X: $x, Y: $y")
                    println("Day: $date, Time: $time")

                }

            }
            .draggable(
                orientation = Orientation.Vertical,
                state = rememberDraggableState { delta ->
                    offsetY += delta
                    println("Delta: $offsetY")

                }
            ),
    ) { measurables, constraints ->
        println("i got recomposed ======== ")
        val height = hourHeight.roundToPx() * 24
        val width = dayWidth.roundToPx() * numDays
        val placeablesWithAppointment = measurables.map { measurable ->
            val appointment = measurable.parentData as Appointment
            val appointmentDurationInMinutes =
                ChronoUnit.MINUTES.between(
                    appointment.startDate.time.toJavaLocalTime(),
                    appointment.endDate.time.toJavaLocalTime()
                )

            val appointmentHeight =
                ((appointmentDurationInMinutes / 60f) * hourHeight.toPx()).roundToInt()
            val placeable = measurable.measure(
                constraints.copy(
                    minWidth = dayWidth.roundToPx(),
                    maxWidth = dayWidth.roundToPx(),
                    minHeight = appointmentHeight,
                    maxHeight = appointmentHeight
                )
            )
            Pair(placeable, appointment)
        }
        layout(width, height) {
            placeablesWithAppointment.forEach { (placeable, appointment) ->
                //appointment time - midnight
                val appointmentOffsetMinutes =
                    ChronoUnit.MINUTES.between(
                        LocalTime.MIN,
                        appointment.startDate.time.toJavaLocalTime()
                    )
                val appointmentY =
                    ((appointmentOffsetMinutes / 60f) * hourHeight.toPx()).roundToInt()
                val appointmentOffsetDays =
                    ChronoUnit.DAYS.between(
                        minDate,
                        appointment.startDate.date.toJavaLocalDate()
                    ).toInt()

                val appointmentX = appointmentOffsetDays * dayWidth.roundToPx()
                placeable.place(appointmentX, appointmentY)

            }
        }

}
}
</code>```

Body:
I am using this tutorial
https://danielrampelt.com/blog/jetpack-compose-custom-schedule-layout-part-1/ and part 2
to draw a custom schedule. How can I want to use draggable inside of it so I can change the color of the dragged surface in jetpack compose. My aim is to drag an time slot vertically. This is my composable function. I have put the draggable function but I don't know how to implement it. Now my screen freezes, I can't scroll vertically.

@Composable
fun DynamicSchedule(
    viewModel: CalenderViewModel,
    modifier: Modifier = Modifier,
    appointmentContent: @Composable (appointment: Appointment) -> Unit = {
        ScheduleCard(
            appointment = it
        )
    },
    minDate: LocalDate,
    maxDate: LocalDate,
    dayWidth: Dp,
    hourHeight: Dp
) {
    val numDays = ChronoUnit.DAYS.between(minDate, maxDate).toInt() + 1
    val dividerColor = if (MaterialTheme.colors.isLight) Color.LightGray else Color.DarkGray
    var offsetY by remember { mutableStateOf(0f) }
    Layout(
        content = {
            viewModel.state.value.appointmentList.sortedBy { it.startDate }

                .forEach { appointment ->
                    Box(modifier = Modifier.appointmentData(appointment)) {
                        appointmentContent(appointment)
                    }
                }
        },
        modifier = modifier
            .drawBehind {
                repeat(23) {
                    drawLine(
                        dividerColor,
                        start = Offset(0f, (it + 1) * hourHeight.toPx()),
                        end = Offset(size.width, (it + 1) * hourHeight.toPx()),
                        strokeWidth = 1.dp.toPx()
                    )
                }
                repeat(numDays - 1) {
                    drawLine(
                        dividerColor,
                        start = Offset((it + 1) * dayWidth.toPx(), 0f),
                        end = Offset((it + 1) * dayWidth.toPx(), size.height),
                        strokeWidth = 1.dp.toPx()
                    )
                }
            }
            .pointerInput(Unit) {
                detectTapGestures {
                    val x = it.x.toDp()
                    val y = it.y.toDp()
                    val time = y.value.toInt() / hourHeight.value
                    val date = (x.value.toInt() / dayWidth.value)
                    println("X: $x, Y: $y")
                    println("Day: $date, Time: $time")

                }

            }
            .draggable(
                orientation = Orientation.Vertical,
                state = rememberDraggableState { delta ->
                    offsetY += delta
                    println("Delta: $offsetY")

                }
            ),
    ) { measurables, constraints ->
        println("i got recomposed ======== ")
        val height = hourHeight.roundToPx() * 24
        val width = dayWidth.roundToPx() * numDays
        val placeablesWithAppointment = measurables.map { measurable ->
            val appointment = measurable.parentData as Appointment
            val appointmentDurationInMinutes =
                ChronoUnit.MINUTES.between(
                    appointment.startDate.time.toJavaLocalTime(),
                    appointment.endDate.time.toJavaLocalTime()
                )

            val appointmentHeight =
                ((appointmentDurationInMinutes / 60f) * hourHeight.toPx()).roundToInt()
            val placeable = measurable.measure(
                constraints.copy(
                    minWidth = dayWidth.roundToPx(),
                    maxWidth = dayWidth.roundToPx(),
                    minHeight = appointmentHeight,
                    maxHeight = appointmentHeight
                )
            )
            Pair(placeable, appointment)
        }
        layout(width, height) {
            placeablesWithAppointment.forEach { (placeable, appointment) ->
                //appointment time - midnight
                val appointmentOffsetMinutes =
                    ChronoUnit.MINUTES.between(
                        LocalTime.MIN,
                        appointment.startDate.time.toJavaLocalTime()
                    )
                val appointmentY =
                    ((appointmentOffsetMinutes / 60f) * hourHeight.toPx()).roundToInt()
                val appointmentOffsetDays =
                    ChronoUnit.DAYS.between(
                        minDate,
                        appointment.startDate.date.toJavaLocalDate()
                    ).toInt()

                val appointmentX = appointmentOffsetDays * dayWidth.roundToPx()
                placeable.place(appointmentX, appointmentY)

            }
        }

}
}