问:
using Pinia store with vue js i want the action to make subarrays in the returned data so that new data fetched from database wont be deleted
using pinia store with firebase firestore and vuejs i want the action to make a new array inside an array that wont be deleted when the action is called with a different id like in my case paymentId

```<code>    import { defineStore } from 'pinia'
    import {
      collection, onSnapshot,where,
      query,orderBy,addDoc,deleteDoc,doc,updateDoc
    } from 'firebase/firestore'
    import {db} from '/src/js/firebase'
    import { useStoreAuth } from './storeAuth'
    import {today} from '@quasar/quasar-ui-qcalendar/src/index.js'
    import { uid } from 'quasar'
    import {useDynamicSort} from 'src/use/useDynamicSort'

    let paymentsCollectionRef
    let paymentsCollectionQuery
    let getPaymentsSnapshot=null

    export const useStorePayments= defineStore('storePayments', {
      state: () => {

        return {
           loadingPayments:false,
           payments:[],
           Mainpayments:[],
           transition:'',
           dayPayments:[],
           selectedDate:today()
        }
      },

 actions:{
    init(){
      const storeAuth=useStoreAuth()
      paymentsCollectionRef = collection(db, 'users',storeAuth.user.id,'payments')
   },
    async getPayments(id) {
      paymentsCollectionQuery = query(paymentsCollectionRef, where("patientid", "==",id),orderBy("date","desc"))
      this.loadingPayments=true
          getPaymentsSnapshot=onSnapshot(paymentsCollectionQuery, (querySnapshot) => {
          const payments=[]
          querySnapshot.forEach((doc) => {
          let payment={
            id:doc.data().id,
            details:doc.data().details,
            date:doc.data().date,
            currencyhavetopay:doc.data().currencyhavetopay,
            currencypaid:doc.data().currencypaid,
            moneyhavetopay:doc.data().moneyhavetopay,
            moneypaid:doc.data().moneypaid,
            tooth:doc.data().tooth,
            doctor:doc.data().doctor,
            patientid:doc.data().patientid,
          }
          payments.push(payment)
          })

            this.Mainpayments=payments
       this.loadingPayments=false
        },error=>{
          console.log('error',error.message)

      })
   },

    })
</code>```

so my problem is when the action fetching data array with specific id the Mainpayments array will be updated with the data containing that id but when i want to fetch data with new id the old array with previous id will be deleted and updated with the data with the new id and my question is could i make sub arrays for each data fetched from firestore inside the Mainpayments array with the name of the payment id ? so when new data with new id wont overwrite my previous array?

Body:
using pinia store with firebase firestore and vuejs i want the action to make a new array inside an array that wont be deleted when the action is called with a different id like in my case paymentId

    import { defineStore } from 'pinia'
    import {
      collection, onSnapshot,where,
      query,orderBy,addDoc,deleteDoc,doc,updateDoc
    } from 'firebase/firestore'
    import {db} from '/src/js/firebase'
    import { useStoreAuth } from './storeAuth'
    import {today} from '@quasar/quasar-ui-qcalendar/src/index.js'
    import { uid } from 'quasar'
    import {useDynamicSort} from 'src/use/useDynamicSort'

    let paymentsCollectionRef
    let paymentsCollectionQuery
    let getPaymentsSnapshot=null

    export const useStorePayments= defineStore('storePayments', {
      state: () => {

        return {
           loadingPayments:false,
           payments:[],
           Mainpayments:[],
           transition:'',
           dayPayments:[],
           selectedDate:today()
        }
      },

 actions:{
    init(){
      const storeAuth=useStoreAuth()
      paymentsCollectionRef = collection(db, 'users',storeAuth.user.id,'payments')
   },
    async getPayments(id) {
      paymentsCollectionQuery = query(paymentsCollectionRef, where("patientid", "==",id),orderBy("date","desc"))
      this.loadingPayments=true
          getPaymentsSnapshot=onSnapshot(paymentsCollectionQuery, (querySnapshot) => {
          const payments=[]
          querySnapshot.forEach((doc) => {
          let payment={
            id:doc.data().id,
            details:doc.data().details,
            date:doc.data().date,
            currencyhavetopay:doc.data().currencyhavetopay,
            currencypaid:doc.data().currencypaid,
            moneyhavetopay:doc.data().moneyhavetopay,
            moneypaid:doc.data().moneypaid,
            tooth:doc.data().tooth,
            doctor:doc.data().doctor,
            patientid:doc.data().patientid,
          }
          payments.push(payment)
          })

            this.Mainpayments=payments
       this.loadingPayments=false
        },error=>{
          console.log('error',error.message)

      })
   },

    })

so my problem is when the action fetching data array with specific id the Mainpayments array will be updated with the data containing that id but when i want to fetch data with new id the old array with previous id will be deleted and updated with the data with the new id and my question is could i make sub arrays for each data fetched from firestore inside the Mainpayments array with the name of the payment id ? so when new data with new id wont overwrite my previous array?


来源: stackexchange

问:
Unable to write data to the transport connection Error while sending data via Socket in C#
I'm trying to Broadcast data to my FrontEnd Applications using C# but I'm getting this error.

Here is my code looks like.

```<code>          Socket socket = new Socket(
              AddressFamily.InterNetwork,
              SocketType.Stream,
              ProtocolType.Tcp
           );
            socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15001));
            socket.Listen(10);
            socket.SendTimeout = 50000000;
            socket.ReceiveTimeout = 50000000;
            socket.SendBufferSize = 1048510;
            socket.ReceiveBufferSize = 1048510;
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            socket.NoDelay = true;

              var acceptedCoonection =  socket.Accept();

            // get the network stream from the accepted connection
            var stream = new NetworkStream(acceptedCoonection);

            while (acceptedCoonection.Connected )
            {

                Console.WriteLine("Transmitting Feed ..");
                try
                {
                    var JSON_DATA = PrepareMarkertDataToJSON(data);
                    stream.Write(JSON_DATA, 0, JSON_DATA.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    Thread.Sleep(1000);
                }
                //socketInformation.Close();
            }
            socketInformation.Listen();
            Console.WriteLine("Waiting for Connection .....");
</code>```

Here is how my Console Looks like

Transmitting Feed ..

Transmitting Feed ..

Transmitting Feed ..

Unable to write data to the transport connection: An established
connection was aborted by the software in your host machine

It runs 3 times but the fourth time it fails. Funny enough, on my frontend there is no data even when the console writes Transmitting.

I have tried solutions to questions with a similar problem but Still getting the same error.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to Broadcast data to my FrontEnd Applications using C# but I'm getting this error.

Here is my code looks like.

          Socket socket = new Socket(
              AddressFamily.InterNetwork,
              SocketType.Stream,
              ProtocolType.Tcp
           );
            socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15001));
            socket.Listen(10);
            socket.SendTimeout = 50000000;
            socket.ReceiveTimeout = 50000000;
            socket.SendBufferSize = 1048510;
            socket.ReceiveBufferSize = 1048510;
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            socket.NoDelay = true;

              var acceptedCoonection =  socket.Accept();

            // get the network stream from the accepted connection
            var stream = new NetworkStream(acceptedCoonection);

            while (acceptedCoonection.Connected )
            {

                Console.WriteLine("Transmitting Feed ..");
                try
                {
                    var JSON_DATA = PrepareMarkertDataToJSON(data);
                    stream.Write(JSON_DATA, 0, JSON_DATA.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    Thread.Sleep(1000);
                }
                //socketInformation.Close();
            }
            socketInformation.Listen();
            Console.WriteLine("Waiting for Connection .....");

Here is how my Console Looks like

Transmitting Feed ..

Transmitting Feed ..

Transmitting Feed ..

Unable to write data to the transport connection: An established
connection was aborted by the software in your host machine

It runs 3 times but the fourth time it fails. Funny enough, on my frontend there is no data even when the console writes Transmitting.

I have tried solutions to questions with a similar problem but Still getting the same error.


问:
how to capture values of type int - GO, GIN, POSTFORM
I'm building a simple crud integrated with html. My crud consists of a table of products, in my table I have the following fields:

package models

type Produtos struct {
    IDProd       int    `json:"id_Prod" gorm:"primaryKey"`
    NomeProduto  string `json:"nome_produto"`
    Quantidade   int    `json:"quantidade"`
    PrecoProduto int    `json:"preco_produto"`
}```
</div>
</div>
</p>
<p>I'm trying to make a fullstack crud, but I'm stuck in the part where I enter the Quantity and Product_Price values.
My GO code is like this:</p>
<p><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>package handlers

import (
    "github.com/gin-gonic/gin"
    "github.com/guilherm5/crud/models"
)

func (h Handler) CreateProduct(c *gin.Context) {
    //CREATE IN WEBSITE

    var createHTML = []models.Produtos{{
        NomeProduto:  c.Request.FormValue("nome_produto"),
        Quantidade:   c.Request.FormValue("quantidade"),
        PrecoProduto: c.Request.FormValue("preco_produto")}}

    h.DB.Create(&createHTML)</code>```

my html code like this:

        <form action="/create" method="post" enctype="multipart/form-data">

Crie seu usuario

                <input placeholder="nome do produto" type="text" id="nome_produto" name="nome_produto">

                <input placeholder="quantidade em estoque" type="number" id="quantidade" name="quantidade">

                <input placeholder="preco do produto" type="number" id="preco_produto" name="preco_produto">

            <button id="botao" type="submit" class="glow-on-hover" type="button">Enviar</button>
        </form>```
</div>
</div>
</p>
<p>my problem is in the GO code, in my Quantity part it is issuing the following error:</p>
<p>my problem is in the GO code, in my Quantity part: <code>c.Request.FormValue("quantidade")</code>, it is issuing the following error:</p>
```cannot use c.Request.FormValue("quantidade") (value of type string) as int value in struct literal
```

the parameter c.Request.FormValue does not accept int in its entries, how can I solve this? Is there any other parameter to be used? can someone help me?

Body:
I'm building a simple crud integrated with html. My crud consists of a table of products, in my table I have the following fields:

package models

type Produtos struct {
    IDProd       int    `json:"id_Prod" gorm:"primaryKey"`
    NomeProduto  string `json:"nome_produto"`
    Quantidade   int    `json:"quantidade"`
    PrecoProduto int    `json:"preco_produto"`
}

I'm trying to make a fullstack crud, but I'm stuck in the part where I enter the Quantity and Product_Price values.
My GO code is like this:

package handlers

import (
    "github.com/gin-gonic/gin"
    "github.com/guilherm5/crud/models"
)

func (h Handler) CreateProduct(c *gin.Context) {
    //CREATE IN WEBSITE

    var createHTML = []models.Produtos{{
        NomeProduto:  c.Request.FormValue("nome_produto"),
        Quantidade:   c.Request.FormValue("quantidade"),
        PrecoProduto: c.Request.FormValue("preco_produto")}}

    h.DB.Create(&createHTML)

my html code like this:

        <form action="/create" method="post" enctype="multipart/form-data">

Crie seu usuario

                <input placeholder="nome do produto" type="text" id="nome_produto" name="nome_produto">

                <input placeholder="quantidade em estoque" type="number" id="quantidade" name="quantidade">

                <input placeholder="preco do produto" type="number" id="preco_produto" name="preco_produto">

            <button id="botao" type="submit" class="glow-on-hover" type="button">Enviar</button>
        </form>

my problem is in the GO code, in my Quantity part it is issuing the following error:

my problem is in the GO code, in my Quantity part: c.Request.FormValue("quantidade"), it is issuing the following error:

cannot use c.Request.FormValue("quantidade") (value of type string) as int value in struct literal

the parameter c.Request.FormValue does not accept int in its entries, how can I solve this? Is there any other parameter to be used? can someone help me?


问:
How to enable transaction mode on PublishJMS processor in Apache NIFI?
I hope to enable transaction mode when using PublishJMS processor in Apache NIFI. However, there are no such properties in the properties of PublishJMS processor.

So, any suggestion? Thanks


问:
how to create Domain Identity in aws SES using javascipt sdk
I installed following package (AWS SDK for JavaScript v3) , not the entire pacakge only SES module as described in here
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ses/index.html

my goal is to create Domain Identity using api.

I can't find the correct command to achieve my goal. I assume all available commands are listed here
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ses/globals.html

is it something impossible to do with this version of sdk ?


问:
When I add a chart into excel using VBA sometimes it becomes a pivot chart and causes errors
I have a pivot table with 3 values in it. Volume Processed, Volume Billed, and Billed Revenue. VB is always a subset of VP, and BR is often in the 100,000s compared to VB and VP which are usually less than 1,000. Additionally, there are over 1000 data points in my test data. I've only loaded in 2 months, and when it's done it has to be able to quickly handle an entire year. So Pivot Charts won't work. BR is a currency and VB and VP are just numbers. The chart I want is to show (VP-VB) stacked on top of VB where the height of VB = BR and the height of (VP-VB)+VB = (VP*BR)/VB. I also try to use a smaller amount of data points. If all the IDs are showing, that's over 1000 columns on the graph, it's much easier to see them group by buildings until you use a slicer to bring down the number of IDs to something more manageable.

My solution is to use VBA to make my own graph, scrape the data from the pivot table, figure out what graph the user wants to see, and then build it from scratch.

The problem is that sometimes the chart preloads with a pivot chart and then when I try to add in my data it throws a Run-time error. I am having trouble even creating the error because it doesn't always happen.

```<code>Dim MyChart as Object
Dim chtrng as Range
Dim srs as Series
Dim arrayvalues() as Double
Dim areayXvalues() as Variant

Set chtrng = Sheets("Pivot").Range("H30:T50")
Set MyChart = ThisWorkbook.Sheets("Pivot").ChartObjects.Add(Left:=chtrng.left,Width:=chtrng.width,Top:=chtrng.Top,Height:=chrrng.Height)
With MyChart.Chart
.ChartType = xlColumnStacked
.Has title = True
.ChartTitle.text = GraphName(0)
For j = 1 to 2
   For I = 1 to GraphList.Count
     Arrayvalues(i-1) = GraphList(I)(j)
   Next I

   Set srs = .Series collection.NewSeries
   With srs
      .Xvalues = areayXvalues
      .Values = areayvalues
      .Name = GraphName(j)
   End With
Next j
End With
</code>```

"Set srs" is where the error comes in. This is also the first pass of j. When I step through the code, the times that it works, at "Set MyChart" the graph is empty, but the times it doesn't work, the graph has a pivot chart inside. At the beginning of the actual code I delete all charts on the sheet.

Every scenario I try, with different data displayed in the pivot table has done both. I can't figure out what is even causing the issue.

I've tried making sure MyChart is set to nothing. I have code that calls the makegraph sub when the pivot table updates, I created a on/off switch for that. I've tried to disconnect all of my data scraping from the pivot table so that by the time I start on the graph none of my variables are attached to the table.

Most of the time the graph works exactly as expected, but every now and then it gives me a Run-time error '1004' on "Set srs"

Body:
I have a pivot table with 3 values in it. Volume Processed, Volume Billed, and Billed Revenue. VB is always a subset of VP, and BR is often in the 100,000s compared to VB and VP which are usually less than 1,000. Additionally, there are over 1000 data points in my test data. I've only loaded in 2 months, and when it's done it has to be able to quickly handle an entire year. So Pivot Charts won't work. BR is a currency and VB and VP are just numbers. The chart I want is to show (VP-VB) stacked on top of VB where the height of VB = BR and the height of (VP-VB)+VB = (VP*BR)/VB. I also try to use a smaller amount of data points. If all the IDs are showing, that's over 1000 columns on the graph, it's much easier to see them group by buildings until you use a slicer to bring down the number of IDs to something more manageable.

My solution is to use VBA to make my own graph, scrape the data from the pivot table, figure out what graph the user wants to see, and then build it from scratch.

The problem is that sometimes the chart preloads with a pivot chart and then when I try to add in my data it throws a Run-time error. I am having trouble even creating the error because it doesn't always happen.

Dim MyChart as Object
Dim chtrng as Range
Dim srs as Series
Dim arrayvalues() as Double
Dim areayXvalues() as Variant

Set chtrng = Sheets("Pivot").Range("H30:T50")
Set MyChart = ThisWorkbook.Sheets("Pivot").ChartObjects.Add(Left:=chtrng.left,Width:=chtrng.width,Top:=chtrng.Top,Height:=chrrng.Height)
With MyChart.Chart
.ChartType = xlColumnStacked
.Has title = True
.ChartTitle.text = GraphName(0)
For j = 1 to 2
   For I = 1 to GraphList.Count
     Arrayvalues(i-1) = GraphList(I)(j)
   Next I

   Set srs = .Series collection.NewSeries
   With srs
      .Xvalues = areayXvalues
      .Values = areayvalues
      .Name = GraphName(j)
   End With
Next j
End With

"Set srs" is where the error comes in. This is also the first pass of j. When I step through the code, the times that it works, at "Set MyChart" the graph is empty, but the times it doesn't work, the graph has a pivot chart inside. At the beginning of the actual code I delete all charts on the sheet.

Every scenario I try, with different data displayed in the pivot table has done both. I can't figure out what is even causing the issue.

I've tried making sure MyChart is set to nothing. I have code that calls the makegraph sub when the pivot table updates, I created a on/off switch for that. I've tried to disconnect all of my data scraping from the pivot table so that by the time I start on the graph none of my variables are attached to the table.

Most of the time the graph works exactly as expected, but every now and then it gives me a Run-time error '1004' on "Set srs"


问:
Clang: autovectorize conversion of bool[64] array to uint64_t bit mask
I want to convert a bool[64] into a uint64_t where each bit represents the value of an element in the input array.

On modern x86 processors, this can be done quite efficiently, e.g. using vptestmd with AVX512 or vpmovmskb with AVX256. When I use clang's bool vector extension in combination with __builtin_convertvector, I'm happy with the results:

uint64_t handvectorized(const bool* input_) noexcept {
    const bool* __restrict input = std::assume_aligned<64>(input_);

    using VecBool64 __attribute__((vector_size(64))) = char;
    using VecBitmaskT __attribute__((ext_vector_type(64))) = bool;

    auto input_vec = *reinterpret_cast<const VecBool64*>(input);
    auto result_vec = __builtin_convertvector(input_vec, VecBitmaskT);

    return reinterpret_cast<uint64_t&>(result_vec);
}
```
<p>produces (godbolt):</p>
```vmovdqa64  zmm0, zmmword ptr [rdi]
vptestmb   k0, zmm0, zmm0
kmovq      rax, k0
vzeroupper
ret
```
<p>However, I can not get clang (or GCC, or ICX) to produce anything that uses vector mask extraction like this with (portable) scalar code.
For this implementation:</p>
<pre class="lang-cpp prettyprint-override"><code>uint64_t loop(const bool* input_) noexcept {
    const bool* __restrict input = std::assume_aligned<64>(input_);

    uint64_t result = 0;
    for(size_t i = 0; i < 64; ++i) {
        if(input[i]) {
            result |= 1ull << i;
        }
    }
    return result;
}
</code>```

clang produces a 64*8B = 512B lookup table and 39 instructions.

This implementation, and some other scalar implementations (branchless, inverse bit order, using std::bitset) that I've tried, can all be found on godbolt. None of them results in code close to the handwritten vector instructions.

Is there anything I'm missing or any reason the optimization doesn't work well here? Is there a scalar version I can write that produces reasonably vectorized code?

I'm wondering especially since the "handvectorized" version doesn't use any platform-specific intrinsics, and doesn't really have much programming to it. All it does is "load as vector" and "convert to bitmask". Perhaps clang simply doesn't detect the loop pattern? It just feels strange to me, a simple bitwise OR reduction loop feels like a common pattern, and the documentation of the loop vectorizer explicitly lists reductions using OR as a supported feature.

Edit: Updated godbolt link with suggestions from the comments

Edit2: I just realized there is an open LLVM issue for exactly this problem: https://github.com/llvm/llvm-project/issues/41997

Body:
I want to convert a bool[64] into a uint64_t where each bit represents the value of an element in the input array.

On modern x86 processors, this can be done quite efficiently, e.g. using vptestmd with AVX512 or vpmovmskb with AVX256. When I use clang's bool vector extension in combination with __builtin_convertvector, I'm happy with the results:

uint64_t handvectorized(const bool* input_) noexcept {
    const bool* __restrict input = std::assume_aligned<64>(input_);

    using VecBool64 __attribute__((vector_size(64))) = char;
    using VecBitmaskT __attribute__((ext_vector_type(64))) = bool;

    auto input_vec = *reinterpret_cast<const VecBool64*>(input);
    auto result_vec = __builtin_convertvector(input_vec, VecBitmaskT);

    return reinterpret_cast<uint64_t&>(result_vec);
}

produces (godbolt):

vmovdqa64  zmm0, zmmword ptr [rdi]
vptestmb   k0, zmm0, zmm0
kmovq      rax, k0
vzeroupper
ret

However, I can not get clang (or GCC, or ICX) to produce anything that uses vector mask extraction like this with (portable) scalar code.
For this implementation:

uint64_t loop(const bool* input_) noexcept {
    const bool* __restrict input = std::assume_aligned<64>(input_);

    uint64_t result = 0;
    for(size_t i = 0; i < 64; ++i) {
        if(input[i]) {
            result |= 1ull << i;
        }
    }
    return result;
}

clang produces a 64*8B = 512B lookup table and 39 instructions.

This implementation, and some other scalar implementations (branchless, inverse bit order, using std::bitset) that I've tried, can all be found on godbolt. None of them results in code close to the handwritten vector instructions.

Is there anything I'm missing or any reason the optimization doesn't work well here? Is there a scalar version I can write that produces reasonably vectorized code?

I'm wondering especially since the "handvectorized" version doesn't use any platform-specific intrinsics, and doesn't really have much programming to it. All it does is "load as vector" and "convert to bitmask". Perhaps clang simply doesn't detect the loop pattern? It just feels strange to me, a simple bitwise OR reduction loop feels like a common pattern, and the documentation of the loop vectorizer explicitly lists reductions using OR as a supported feature.

Edit: Updated godbolt link with suggestions from the comments

Edit2: I just realized there is an open LLVM issue for exactly this problem: https://github.com/llvm/llvm-project/issues/41997


问:
Spring Batch Remote Chunking Kafka
I Have currently implemented Spring Batch Remote Chunking with Kafka. I have one Manager and Workers (21 copy of the workers).
Currently I am facing below issue

I want to know if it is possible to run two same Remote chunking step with different parameters parallelly at the same time. The problem I see here since i am using the same reply channel and the responses are getting mixed up of the two different instances of the same chunk steps.

Second problem is I have more than 250000 record to process and my chunk size is 1000 and number of workers are 21 and  I have also the throttle limit to 20 and maxtimeoutcount to 10000. I want to know what should be throttle limit and maxtimeoutcount for processing huge records

Please do suggest me regarding the above issue as I am stuck.

Title: Spring Batch Remote Chunking Kafka


问:
Select Bigint colunn return a float number
id => colunn bigint (7185470932130075125)

```<code>SELECT id FROM table;
</code>```

But return sql : 7185470932130075000

Why return a around id ?

Body:
id => colunn bigint (7185470932130075125)

SELECT id FROM table;

But return sql : 7185470932130075000

Why return a around id ?


问:
Use GrapesJS with Node
I am trying to use GrapesJS with node JS and am new to both. I have run npm i grapesjs and set type: module in my package.json file.

I run - node myjsfile.js in cmd prompt but the problem is that I get unknown file extension for the css file when I am just following GrapesJS getting started guide and adding the following 2 lines to myjsfile.js.

```<code>import 'grapesjs/dist/css/grapes.min.css';
import grapesjs from 'grapesjs';
</code>```

If I remove the css import line of code and call node myjsfile.js then I get document not defined for the import grapesjs from 'grapesjs'

Is there something I am missing when importing the JS and CSS for GrapesJS in a node js file?

Tried to import GrapesJS

Title: Use GrapesJS with Node

Body:
I am trying to use GrapesJS with node JS and am new to both. I have run npm i grapesjs and set type: module in my package.json file.

I run - node myjsfile.js in cmd prompt but the problem is that I get unknown file extension for the css file when I am just following GrapesJS getting started guide and adding the following 2 lines to myjsfile.js.

import 'grapesjs/dist/css/grapes.min.css';
import grapesjs from 'grapesjs';

If I remove the css import line of code and call node myjsfile.js then I get document not defined for the import grapesjs from 'grapesjs'

Is there something I am missing when importing the JS and CSS for GrapesJS in a node js file?

Tried to import GrapesJS


问:
D8016 '/clr' and '/MT' command-line options are incompatible
I have made an Windows Application using visual c++[CLR Empty Project].But when I run that .exe file in another PC i get error of ucrtbased.dll, VCRUNTIME140D and MSVCP140D file is missing.

For this, we have changed the Runtime Library from Multi-threaded Debug DLL(/MDd) to Multi-threaded(/MT). Then also i am getting error like :-

Error : D8016 '/clr' and '/MT' command-line options are incompatible.

So, if any one have any idea to resolve this problem will be appreciated.

Thanks in advance !!!


问:
How to set default card without any selection
I am developing e-commerce app in which users can set multiple options for address. Which by default they have to select every time. Each address have a separate address id which helps in identification of address selected. To reduce extra click of users i want to make first address i.e. address id present on position 0 as default selected address. Different address are present in different material card view so you can easily select one of them. My app screen shot is present as below.
enter image description here

My code is as following

```<code>
import android.content.Context
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.sbhs.stone.R
import com.sbhs.stone.data.UserData
import com.sbhs.stone.databinding.LayoutAddressCardBinding
import com.sbhs.stone.ui.getCompleteAddress

private const val TAG = "AddressAdapter"

class AddressAdapter(
    private val context: Context,
    addresses: List<UserData.Address>,
    private val isSelect: Boolean,
) :
    RecyclerView.Adapter<AddressAdapter.ViewHolder>() {

    lateinit var onClickListener: OnClickListener
    var data: List<UserData.Address> = addresses

    var lastCheckedAddress: String? = null
    private var lastCheckedCard: MaterialCardView? = null
    var selectedAddressPos = -1

    inner class ViewHolder(private var binding: LayoutAddressCardBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(address: UserData.Address, position: Int) {
            binding.addressCard.isChecked = position == selectedAddressPos
            binding.addressPersonNameTv.text =
                context.getString(R.string.person_name, address.fName, address.lName)
            binding.addressCompleteAddressTv.text = getCompleteAddress(address)
            binding.addressMobileTv.text = address.phoneNumber
            if (isSelect) {
                binding.addressCard.setOnClickListener {
                    onCardClick(position, address.addressId, it as MaterialCardView)
                }
            }
            //binding.addressCard.setOnFocusChangeListener { view: View, b: Boolean ->
            //  onCardClick(0, address.addressId, 0 as MaterialCardView)
            //}
            binding.addressEditBtn.setOnClickListener {
                onClickListener.onEditClick(address.addressId)
            }
            binding.addressDeleteBtn.setOnClickListener {
                onClickListener.onDeleteClick(address.addressId)
                notifyDataSetChanged()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutAddressCardBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(data[position], position)
    }

    override fun getItemCount(): Int = data.size

    interface OnClickListener {
        fun onEditClick(addressId: String)
        fun onDeleteClick(addressId: String)
    }

    private fun onCardClick(position: Int, addressTd: String, card: MaterialCardView) {
        if (addressTd != lastCheckedAddress) {
            card.apply {
                strokeColor = context.getColor(R.color.blue_accent_300)
                isChecked = true
                strokeWidth = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    2F,
                    resources.displayMetrics
                ).toInt()
            }
            lastCheckedCard?.apply {
                strokeColor = context.getColor(R.color.light_gray)
                isChecked = false
                strokeWidth = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    1F,
                    resources.displayMetrics
                ).toInt()
            }

            lastCheckedAddress = addressTd
            lastCheckedCard = card
            selectedAddressPos = position
            Log.d(TAG, "onCardClick: selected address = $addressTd")
        }
    }
}

</code>```

So in above code i want to make selectedAddressPos = 0, & last checked Address as addressTd of address present on position 0. Remember my address can be null so this condition should only applied when address is non-null. Please help me i am new in coding. The information about user address are stored in firebase. so i cant make any card as default from xml.

I tried to make selectedAddressPos as 0 at time of initiation but it will only show it in app and no address id is taken.

Body:
I am developing e-commerce app in which users can set multiple options for address. Which by default they have to select every time. Each address have a separate address id which helps in identification of address selected. To reduce extra click of users i want to make first address i.e. address id present on position 0 as default selected address. Different address are present in different material card view so you can easily select one of them. My app screen shot is present as below.
enter image description here

My code is as following

import android.content.Context
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.sbhs.stone.R
import com.sbhs.stone.data.UserData
import com.sbhs.stone.databinding.LayoutAddressCardBinding
import com.sbhs.stone.ui.getCompleteAddress

private const val TAG = "AddressAdapter"

class AddressAdapter(
    private val context: Context,
    addresses: List<UserData.Address>,
    private val isSelect: Boolean,
) :
    RecyclerView.Adapter<AddressAdapter.ViewHolder>() {

    lateinit var onClickListener: OnClickListener
    var data: List<UserData.Address> = addresses

    var lastCheckedAddress: String? = null
    private var lastCheckedCard: MaterialCardView? = null
    var selectedAddressPos = -1

    inner class ViewHolder(private var binding: LayoutAddressCardBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(address: UserData.Address, position: Int) {
            binding.addressCard.isChecked = position == selectedAddressPos
            binding.addressPersonNameTv.text =
                context.getString(R.string.person_name, address.fName, address.lName)
            binding.addressCompleteAddressTv.text = getCompleteAddress(address)
            binding.addressMobileTv.text = address.phoneNumber
            if (isSelect) {
                binding.addressCard.setOnClickListener {
                    onCardClick(position, address.addressId, it as MaterialCardView)
                }
            }
            //binding.addressCard.setOnFocusChangeListener { view: View, b: Boolean ->
            //  onCardClick(0, address.addressId, 0 as MaterialCardView)
            //}
            binding.addressEditBtn.setOnClickListener {
                onClickListener.onEditClick(address.addressId)
            }
            binding.addressDeleteBtn.setOnClickListener {
                onClickListener.onDeleteClick(address.addressId)
                notifyDataSetChanged()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutAddressCardBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(data[position], position)
    }

    override fun getItemCount(): Int = data.size

    interface OnClickListener {
        fun onEditClick(addressId: String)
        fun onDeleteClick(addressId: String)
    }

    private fun onCardClick(position: Int, addressTd: String, card: MaterialCardView) {
        if (addressTd != lastCheckedAddress) {
            card.apply {
                strokeColor = context.getColor(R.color.blue_accent_300)
                isChecked = true
                strokeWidth = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    2F,
                    resources.displayMetrics
                ).toInt()
            }
            lastCheckedCard?.apply {
                strokeColor = context.getColor(R.color.light_gray)
                isChecked = false
                strokeWidth = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    1F,
                    resources.displayMetrics
                ).toInt()
            }

            lastCheckedAddress = addressTd
            lastCheckedCard = card
            selectedAddressPos = position
            Log.d(TAG, "onCardClick: selected address = $addressTd")
        }
    }
}

So in above code i want to make selectedAddressPos = 0, & last checked Address as addressTd of address present on position 0. Remember my address can be null so this condition should only applied when address is non-null. Please help me i am new in coding. The information about user address are stored in firebase. so i cant make any card as default from xml.

I tried to make selectedAddressPos as 0 at time of initiation but it will only show it in app and no address id is taken.


问:
Problem with CORS, Symfony + NGINX + Nuxt
I have two docker containers with nuxt 3 for frontend and another with symfony and nginx for backend.

I never have hear about CORS so after some research I found that I needed a bundle named nelmio.

After installed it and configured it still getting the same error on my website (I have tested with Postman and everything works fine, I can register my user)

This is the error:

Access to fetch at 'http://127.0.0.1:8000/api/register' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.

POST http://127.0.0.1:8000/api/register net::ERR_FAILED 500

Here is my nelmio_cors.yaml:

```<code>nelmio_cors:
  defaults:
    origin_regex: true
    allow_origin: [ '%env(CORS_ALLOW_ORIGIN)%' ]
    allow_methods: [ 'GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE' ]
    allow_headers: [ 'Content-Type', 'Authorization' ]
    expose_headers: [ 'Link' ]
    max_age: 3600
  paths:
    '^/api/':
      allow_origin: [ '*' ]
      allow_headers: [ '*' ]
      allow_methods: [ 'POST', 'PUT', 'GET', 'DELETE' ]
      max_age: 3600
    '^/':
      origin_regex: true
      allow_origin: [ '^http://localhost:[0-9]+' ]
      allow_headers: [ 'X-Custom-Auth' ]
      allow_methods: [ 'POST', 'PUT', 'GET', 'DELETE' ]
      max_age: 3600
      hosts: [ '^api\.' ]
</code>```

In my env I have:

```<code>CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
</code>```

In my nuxt I have this fetch call:

```<code>submitForm: function (data) {
      $fetch('http://127.0.0.1:8000/api/register', {
        method: 'POST',
        body: data
      }).catch((e) => {
        console.log(e)
      })
    }
</code>```

Anyone knows why I'm still getting the cors error?

EDIT: I also tryed to set on the nginx config this line for cors but still not working...

```<code>add_header Access-Control-Allow-Origin "localhost";
</code>```

EDIT2: Ill put my nginx config here, maybe can be helpful:

```<code>server {
    listen 80;
    root /app/public;

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass app:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}
</code>```

EDIT3: Tryed on my nuxt 3 to set a proxy with nitro and vite but also not working...

nuxt.config.ts:

with nitro:

```<code>nitro: {
    devProxy: {
        "/api": {
            target:"http://127.0.0.1:8000/",
            changeOrigin: true,
            prependPath: true,
        }
    }
},
</code>```

with vite:

```<code>vite: {
        server: {
            watch: { usePolling: true },
            proxy: {
                '/backend': {
                    target: 'http://127.0.0.1:8000/',
                    ws: true,
                },
            },
        }
    }
</code>```

Body:
I have two docker containers with nuxt 3 for frontend and another with symfony and nginx for backend.

I never have hear about CORS so after some research I found that I needed a bundle named nelmio.

After installed it and configured it still getting the same error on my website (I have tested with Postman and everything works fine, I can register my user)

This is the error:

Access to fetch at 'http://127.0.0.1:8000/api/register' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.

POST http://127.0.0.1:8000/api/register net::ERR_FAILED 500

Here is my nelmio_cors.yaml:

nelmio_cors:
  defaults:
    origin_regex: true
    allow_origin: [ '%env(CORS_ALLOW_ORIGIN)%' ]
    allow_methods: [ 'GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE' ]
    allow_headers: [ 'Content-Type', 'Authorization' ]
    expose_headers: [ 'Link' ]
    max_age: 3600
  paths:
    '^/api/':
      allow_origin: [ '*' ]
      allow_headers: [ '*' ]
      allow_methods: [ 'POST', 'PUT', 'GET', 'DELETE' ]
      max_age: 3600
    '^/':
      origin_regex: true
      allow_origin: [ '^http://localhost:[0-9]+' ]
      allow_headers: [ 'X-Custom-Auth' ]
      allow_methods: [ 'POST', 'PUT', 'GET', 'DELETE' ]
      max_age: 3600
      hosts: [ '^api\.' ]

In my env I have:

CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'

In my nuxt I have this fetch call:

submitForm: function (data) {
      $fetch('http://127.0.0.1:8000/api/register', {
        method: 'POST',
        body: data
      }).catch((e) => {
        console.log(e)
      })
    }

Anyone knows why I'm still getting the cors error?

EDIT: I also tryed to set on the nginx config this line for cors but still not working...

add_header Access-Control-Allow-Origin "localhost";

EDIT2: Ill put my nginx config here, maybe can be helpful:

server {
    listen 80;
    root /app/public;

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass app:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

EDIT3: Tryed on my nuxt 3 to set a proxy with nitro and vite but also not working...

nuxt.config.ts:

with nitro:

nitro: {
    devProxy: {
        "/api": {
            target:"http://127.0.0.1:8000/",
            changeOrigin: true,
            prependPath: true,
        }
    }
},

with vite:

vite: {
        server: {
            watch: { usePolling: true },
            proxy: {
                '/backend': {
                    target: 'http://127.0.0.1:8000/',
                    ws: true,
                },
            },
        }
    }


问:
how to load banner admob at the same time with content of list in flutter?
I put the banner admob in listview. banners in list appears after the contents is loaded.
As the banner appears, the content location moves. so, users make a click mistake.

```<code>Future<void> addAdToList(PagePostModel pagePostModel) async {
  _withAdList.clear();
  _withAdList.addAll(pagePostModel.list!);

  for (int i = 0; i < pagePostModel.list!.length; i += 5) {
    final banner = BannerAd(
        size: AdSize.getInlineAdaptiveBannerAdSize(
            340.w.toInt(), 187.h.toInt()),
        adUnitId: AdHelper.testBannerAdUnitId,
        request: const AdRequest(),
        listener: const BannerAdListener());
    banner.load().then((value) => _withAdList.insert(i, banner));
  }
  _pagePostList.addAll(_withAdList);
  logger.d(_pagePostList);
  _isLastPage = pagePostModel.isLastPage!;
}
</code>```

we expect that banner appears at the same time with content of list.

Body:
I put the banner admob in listview. banners in list appears after the contents is loaded.
As the banner appears, the content location moves. so, users make a click mistake.

Future<void> addAdToList(PagePostModel pagePostModel) async {
  _withAdList.clear();
  _withAdList.addAll(pagePostModel.list!);

  for (int i = 0; i < pagePostModel.list!.length; i += 5) {
    final banner = BannerAd(
        size: AdSize.getInlineAdaptiveBannerAdSize(
            340.w.toInt(), 187.h.toInt()),
        adUnitId: AdHelper.testBannerAdUnitId,
        request: const AdRequest(),
        listener: const BannerAdListener());
    banner.load().then((value) => _withAdList.insert(i, banner));
  }
  _pagePostList.addAll(_withAdList);
  logger.d(_pagePostList);
  _isLastPage = pagePostModel.isLastPage!;
}

we expect that banner appears at the same time with content of list.


问:
homebridge ssh connection wrong username
im trying to use a ssh plugin for the homebridge to turn off my truenas. if havve the following config

```<code>{
    "accessory": "SSH",
    "name": "Remote Command",
    "command": "sudo shutdown -h now",
    "sshConfig": {
        "host": "truenas",
        "username": "root",
        "privateKey": "/home/pi/dev/SSH Shutdown/privatekey.ssh"
    }
}
</code>```

im getting the error

Error: Invalid username
at Client.connect (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh2/lib/client.js:130:11)
at connect (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh-exec/index.js:53:12)
at ReadFileContext.callback (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh-exec/index.js:109:7)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:314:13)

The SSH connection with that username and private key is working from the same pi. I tested that. I tried the same with another user and got the same error.
can someone help? Am I missing someothing obvisous?

Body:
im trying to use a ssh plugin for the homebridge to turn off my truenas. if havve the following config

{
    "accessory": "SSH",
    "name": "Remote Command",
    "command": "sudo shutdown -h now",
    "sshConfig": {
        "host": "truenas",
        "username": "root",
        "privateKey": "/home/pi/dev/SSH Shutdown/privatekey.ssh"
    }
}

im getting the error

Error: Invalid username
at Client.connect (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh2/lib/client.js:130:11)
at connect (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh-exec/index.js:53:12)
at ReadFileContext.callback (/usr/lib/node_modules/homebridge-ssh/node_modules/ssh-exec/index.js:109:7)
at FSReqCallback.readFileAfterOpen [as oncomplete] (node:fs:314:13)

The SSH connection with that username and private key is working from the same pi. I tested that. I tried the same with another user and got the same error.
can someone help? Am I missing someothing obvisous?


问:
Error when checking : expected dense_Dense_1_input to have 2 dimensions, but got array with shape [224, 224, 3]
I get the following error:

```<code>Error when checking : expected dense_Dense_1_input to have 2 dimensions, but got array with shape [224, 224, 3]
</code>```

When I run the following code:

      const modelJson = require("../offline_model/pose-model.json");
      const modelWeights = require("../offline_model/weights.bin");
      let imageTensor = images.next().value as tf.Tensor3D;

      tf.loadLayersModel(bundleResourceIO(modelJson, modelWeights)).then(model => {

        try {
          imageTensor = tf.image.resizeBilinear(
            imageTensor,
            [224, 224],
            false
          );

          const normalized = imageTensor.cast('float32').div(127.5).sub(1);
          model.predict(normalized)
```
<p>Maybe this code is not the most correct but I already tried every other code from stackoverflow and youtube videos and they all give some error. I think the problem is that in my model.json file (I trained the model with teachable machine) I find this value:</p>
```"name":"dense_Dense1", "batch_input_shape":[null,14739]
```

This is why it expects 2 dimensions and I have 3. I guess I am not sure how to change the 3 dimension tensor I have to fit the dimensions of the batch input shape.

Body:
I get the following error:

Error when checking : expected dense_Dense_1_input to have 2 dimensions, but got array with shape [224, 224, 3]

When I run the following code:

      const modelJson = require("../offline_model/pose-model.json");
      const modelWeights = require("../offline_model/weights.bin");
      let imageTensor = images.next().value as tf.Tensor3D;

      tf.loadLayersModel(bundleResourceIO(modelJson, modelWeights)).then(model => {

        try {
          imageTensor = tf.image.resizeBilinear(
            imageTensor,
            [224, 224],
            false
          );

          const normalized = imageTensor.cast('float32').div(127.5).sub(1);
          model.predict(normalized)

Maybe this code is not the most correct but I already tried every other code from stackoverflow and youtube videos and they all give some error. I think the problem is that in my model.json file (I trained the model with teachable machine) I find this value:

"name":"dense_Dense1", "batch_input_shape":[null,14739]

This is why it expects 2 dimensions and I have 3. I guess I am not sure how to change the 3 dimension tensor I have to fit the dimensions of the batch input shape.


问:
Building wheel for lxml (setup.py): finished with status 'error'
I have this error while running docker

Everything works in server but locally lxml finishes with this error:

```<code>#0 55.92   Stored in directory: /root/.cache/pip/wheels/02/f8/c2/4a8e9dce6caefe8931213e951f7d1b19e6a7d86fc2becc228e
#0 55.92   Building wheel for lxml (setup.py): started
#0 57.58   Building wheel for lxml (setup.py): finished with status 'error'
#0 57.60   error: subprocess-exited-with-error
#0 57.60
#0 57.60   × python setup.py bdist_wheel did not run successfully.
#0 57.60   │ exit code: 1
#0 57.60   ╰─> [88 lines of output]
#0 57.60       Building lxml version 4.6.3.
#0 57.60       Building without Cython.
#0 57.60       Building against libxml2 2.9.10 and libxslt 1.1.34
#0 57.60       running bdist_wheel
#0 57.60       running build
#0 57.60       running build_py
#0 57.60       creating build
#0 57.60       creating build/lib.linux-x86_64-cpython-311
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/sax.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/cssselect.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/builder.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/diff.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/formfill.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/clean.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_html5builder.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/soupparser.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/builder.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/defs.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/ElementSoup.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/html5parser.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron
#0 57.60       copying src/lxml/isoschematron/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron
#0 57.60       copying src/lxml/etree.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/etree_api.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/lxml.etree.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/lxml.etree_api.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/includes/__init__.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/dtdvalid.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/uri.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/config.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlschema.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xslt.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/htmlparser.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/tree.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/schematron.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xpath.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/c14n.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/relaxng.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlparser.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlerror.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xinclude.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/etreepublic.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/etree_defs.h -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/rng
#0 57.60       copying src/lxml/isoschematron/resources/rng/iso-schematron.rng -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/rng
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       copying src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       copying src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       warning: build_py: byte-compiling is disabled, skipping.
#0 57.60
#0 57.60       running build_ext
#0 57.60       building 'lxml.etree' extension
#0 57.60       creating build/temp.linux-x86_64-cpython-311
#0 57.60       creating build/temp.linux-x86_64-cpython-311/src
#0 57.60       creating build/temp.linux-x86_64-cpython-311/src/lxml
#0 57.60       gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DCYTHON_CLINE_IN_TRACEBACK=0 -I/usr/include/libxml2 -Isrc -Isrc/lxml/includes -I/usr/local/include/python3.11 -c src/lxml/etree.c -o build/temp.linux-x86_64-cpython-311/src/lxml/etree.o -w
#0 57.60       src/lxml/etree.c:289:12: fatal error: longintrepr.h: No such file or directory
#0 57.60         289 |   #include "longintrepr.h"
#0 57.60             |            ^~~~~~~~~~~~~~~
#0 57.60       compilation terminated.
#0 57.60       Compile failed: command '/usr/bin/gcc' failed with exit code 1
#0 57.60       creating tmp
#0 57.60       cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitzmdan9ao.c -o tmp/xmlXPathInitzmdan9ao.o
#0 57.60       cc tmp/xmlXPathInitzmdan9ao.o -lxml2 -o a.out
#0 57.60       error: command '/usr/bin/gcc' failed with exit code 1
#0 57.60       [end of output]
</code>```

pyodbc finishes with the similar error:

```<code>#0 71.15       In file included from src/buffer.cpp:12:
#0 71.15       src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
#0 71.15          56 | #include <sql.h>
</code>```

What I tried to do:

Cmake 3.25.0 was added to requirements.txt

RUN apt-get -y install python3-lxml

RUN apt-get -y install libxml2-dev libxslt-dev python-dev

RUN apt -y install libgmp-dev libmpfr-dev libmpc-dev

RUN apt-get -y install libgmp3-dev libmpfr-dev

was added to dockerfile

But error is still the same

Dockerfile:

```<code>FROM python:3
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update && ACCEPT_EULA=Y apt-get -y install mssql-tools msodbcsql17
RUN apt-get -y install libldap2-dev libsasl2-dev ldap-utils

RUN apt-get -y install python3-lxml
RUN apt-get -y install libxml2-dev libxslt-dev python-dev
RUN apt -y install libgmp-dev libmpfr-dev libmpc-dev
RUN apt-get -y install libgmp3-dev libmpfr-dev

RUN echo 'export PATH=""' >> ~/.bash_profile
RUN echo 'export PATH=""' >> ~/.bashrc
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
</code>```

docker-compose.yml:

version: "3.3"

services:

```<code>db:

  image: postgres
  restart: always
  volumes:
    - ./data/db:/var/lib/postgresql/data4/
  environment:
    - POSTGRES_DB=
    - POSTGRES_USER=
    - POSTGRES_PASSWORD=
web:
  build: .
  command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
  restart: always
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  environment:
    - PATH=""
    - MSSQL_DB_NAME_KN=
    - MSSQL_DB_NAME_DAPOS=
    - MSSQL_DB_USER=
    - MSSQL_DB_PASSWORD=
    - MSSQL_ADDRESS=
    - MSSQL_PORT=
    - BIND_PASS=
    - POSTGRES_NAME=
    - POSTGRES_USER=
    - POSTGRES_PASSWORD=
  depends_on:
    - db
</code>```

Body:
I have this error while running docker

Everything works in server but locally lxml finishes with this error:

#0 55.92   Stored in directory: /root/.cache/pip/wheels/02/f8/c2/4a8e9dce6caefe8931213e951f7d1b19e6a7d86fc2becc228e
#0 55.92   Building wheel for lxml (setup.py): started
#0 57.58   Building wheel for lxml (setup.py): finished with status 'error'
#0 57.60   error: subprocess-exited-with-error
#0 57.60
#0 57.60   × python setup.py bdist_wheel did not run successfully.
#0 57.60   │ exit code: 1
#0 57.60   ╰─> [88 lines of output]
#0 57.60       Building lxml version 4.6.3.
#0 57.60       Building without Cython.
#0 57.60       Building against libxml2 2.9.10 and libxslt 1.1.34
#0 57.60       running bdist_wheel
#0 57.60       running build
#0 57.60       running build_py
#0 57.60       creating build
#0 57.60       creating build/lib.linux-x86_64-cpython-311
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/sax.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/cssselect.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/builder.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/diff.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/formfill.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/clean.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/_html5builder.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/soupparser.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/builder.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/defs.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/ElementSoup.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       copying src/lxml/html/html5parser.py -> build/lib.linux-x86_64-cpython-311/lxml/html
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron
#0 57.60       copying src/lxml/isoschematron/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron
#0 57.60       copying src/lxml/etree.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/etree_api.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/lxml.etree.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/lxml.etree_api.h -> build/lib.linux-x86_64-cpython-311/lxml
#0 57.60       copying src/lxml/includes/__init__.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/dtdvalid.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/uri.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/config.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlschema.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xslt.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/htmlparser.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/tree.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/schematron.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xpath.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/c14n.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/relaxng.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlparser.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xmlerror.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/xinclude.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/etreepublic.pxd -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/etree_defs.h -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-cpython-311/lxml/includes
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/rng
#0 57.60       copying src/lxml/isoschematron/resources/rng/iso-schematron.rng -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/rng
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       copying src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       copying src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl
#0 57.60       creating build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt -> build/lib.linux-x86_64-cpython-311/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
#0 57.60       warning: build_py: byte-compiling is disabled, skipping.
#0 57.60
#0 57.60       running build_ext
#0 57.60       building 'lxml.etree' extension
#0 57.60       creating build/temp.linux-x86_64-cpython-311
#0 57.60       creating build/temp.linux-x86_64-cpython-311/src
#0 57.60       creating build/temp.linux-x86_64-cpython-311/src/lxml
#0 57.60       gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DCYTHON_CLINE_IN_TRACEBACK=0 -I/usr/include/libxml2 -Isrc -Isrc/lxml/includes -I/usr/local/include/python3.11 -c src/lxml/etree.c -o build/temp.linux-x86_64-cpython-311/src/lxml/etree.o -w
#0 57.60       src/lxml/etree.c:289:12: fatal error: longintrepr.h: No such file or directory
#0 57.60         289 |   #include "longintrepr.h"
#0 57.60             |            ^~~~~~~~~~~~~~~
#0 57.60       compilation terminated.
#0 57.60       Compile failed: command '/usr/bin/gcc' failed with exit code 1
#0 57.60       creating tmp
#0 57.60       cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitzmdan9ao.c -o tmp/xmlXPathInitzmdan9ao.o
#0 57.60       cc tmp/xmlXPathInitzmdan9ao.o -lxml2 -o a.out
#0 57.60       error: command '/usr/bin/gcc' failed with exit code 1
#0 57.60       [end of output]

pyodbc finishes with the similar error:

#0 71.15       In file included from src/buffer.cpp:12:
#0 71.15       src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
#0 71.15          56 | #include <sql.h>

What I tried to do:

Cmake 3.25.0 was added to requirements.txt

RUN apt-get -y install python3-lxml

RUN apt-get -y install libxml2-dev libxslt-dev python-dev

RUN apt -y install libgmp-dev libmpfr-dev libmpc-dev

RUN apt-get -y install libgmp3-dev libmpfr-dev

was added to dockerfile

But error is still the same

Dockerfile:

FROM python:3
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update && ACCEPT_EULA=Y apt-get -y install mssql-tools msodbcsql17
RUN apt-get -y install libldap2-dev libsasl2-dev ldap-utils

RUN apt-get -y install python3-lxml
RUN apt-get -y install libxml2-dev libxslt-dev python-dev
RUN apt -y install libgmp-dev libmpfr-dev libmpc-dev
RUN apt-get -y install libgmp3-dev libmpfr-dev

RUN echo 'export PATH=""' >> ~/.bash_profile
RUN echo 'export PATH=""' >> ~/.bashrc
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

docker-compose.yml:

version: "3.3"

services:

db:

  image: postgres
  restart: always
  volumes:
    - ./data/db:/var/lib/postgresql/data4/
  environment:
    - POSTGRES_DB=
    - POSTGRES_USER=
    - POSTGRES_PASSWORD=
web:
  build: .
  command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
  restart: always
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  environment:
    - PATH=""
    - MSSQL_DB_NAME_KN=
    - MSSQL_DB_NAME_DAPOS=
    - MSSQL_DB_USER=
    - MSSQL_DB_PASSWORD=
    - MSSQL_ADDRESS=
    - MSSQL_PORT=
    - BIND_PASS=
    - POSTGRES_NAME=
    - POSTGRES_USER=
    - POSTGRES_PASSWORD=
  depends_on:
    - db


问:
java.net.SocketException connection reset error on Android 11+
My app crashes extremaly often on this error.
**java.net.SocketException connection reset **

I have no any specified line in Stacktrace to write that block here.
I mean there are some informations and error line numbers but none of them are written by me, it's library issue I guess?

It's weird, because if it's my fault in code, why does app crash for Android 11+ only?

I use Retrofit2 library for network calls.

This is a Stacktrace.

Fatal Exception: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:215) at java.net.SocketInputStream.read(SocketInputStream.java:144) at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.readFromSocket(ConscryptEngineSocket.java:945) at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.processDataFromSocket(ConscryptEngineSocket.java:909) at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.readUntilDataAvailable(ConscryptEngineSocket.java:824) at com.android.org.conscrypt.ConscryptEngineSocket$SSLInputStream.read(ConscryptEngineSocket.java:797) at okio.Okio$2.read(Okio.java:140) at okio.AsyncTimeout$2.read(AsyncTimeout.java:237) at okio.RealBufferedSource.read(RealBufferedSource.java:47) at okhttp3.internal.http1.Http1Codec$AbstractSource.read(Http1Codec.java:363) at okhttp3.internal.http1.Http1Codec$ChunkedSource.read(Http1Codec.java:453) at okio.RealBufferedSource.read(RealBufferedSource.java:47) at okio.ForwardingSource.read(ForwardingSource.java:35) at retrofit2.OkHttpCall$ExceptionCatchingResponseBody$1.read(OkHttpCall.java:288) at okio.RealBufferedSource$1.read(RealBufferedSource.java:439) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:291) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:355) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:181) at java.io.InputStreamReader.read(InputStreamReader.java:184) at okhttp3.ResponseBody$BomAwareReader.read(ResponseBody.java:259) at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1289) at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1029) at com.google.gson.stream.JsonReader.nextString(JsonReader.java:814) at com.google.gson.internal.bind.TypeAdapters$15.read(TypeAdapters.java:380) at com.google.gson.internal.bind.TypeAdapters$15.read(TypeAdapters.java:368) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39) at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27) at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:225) at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:121) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:206) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:920)

I was seeking very long time to find, where was my error but I couldn't.
I tried to increase Timeouts, because sometimes I get **Socket Closed ** exception as well


问:
Xcode scene size GUI values ignored for macOS apps
The scene size values, set via the Xcode GUI, seem to only apply to iOS and are ignored by macOS.

So I programmatically set the window size of my macOS app, within NSViewController, using:

```<code>self.view.frame.size = NSSize(width: 375, height: 650)
</code>```

or even something like:

```<code>    let screenWidth = NSScreen.main?.frame.width
    let screenHeight = NSScreen.main?.frame.height
    let windowSize = NSSize(width: screenWidth!/4, height: screenHeight!/2)
    self.view.frame.size = windowSize
</code>```

Is this the correct way to set the window size or am I missing something?

Body:
The scene size values, set via the Xcode GUI, seem to only apply to iOS and are ignored by macOS.

So I programmatically set the window size of my macOS app, within NSViewController, using:

self.view.frame.size = NSSize(width: 375, height: 650)

or even something like:

    let screenWidth = NSScreen.main?.frame.width
    let screenHeight = NSScreen.main?.frame.height
    let windowSize = NSSize(width: screenWidth!/4, height: screenHeight!/2)
    self.view.frame.size = windowSize

Is this the correct way to set the window size or am I missing something?


问:
SQLite data undefined in ipcMain
I am writing a small ElectronJS application to interact with a database using the NodeJS implementation of SQLite3.
I am able to store data in the database, no problems.

```<code>//renderer.js
document.querySelector('#new-store-add').addEventListener('click', _ => {
    console.log("Adding new Store");
    let storeName = document.querySelector("#new-store-name-input").value;
    ipcRenderer.send('db-add-new-store', storeName);
});

//main.js
ipcMain.on('db-add-new-store', (e, r) => {
  addStore(r);
});

//storemgr.js
exports.addStore = (newStore) => {
    const sql = `INSERT INTO STORE (store_name) VALUES('${newStore}')`;
    db.exec(sql);
}

</code>```

Problems arise when I try to read and display data from the same table.
I have tried a couple of different approaches including the current async Promise approach

```<code>//renderer.js
document.querySelector('#main-get-stores').addEventListener('click', () => {
    ipcRenderer.send('db-get-all-stores');
});

ipcRenderer.on('db-got-all-stores', (e,r) => {
    console.log('r -> ', r);
    console.log('e -> ', e);
    console.log('e.stores -> ', e.stores);
})

//main.js
ipcMain.on('db-get-all-stores', async (e,r) => { //NOTE async here
  console.log("Get All Stores");

  let stores = await getAllStores();

  console.log('stores -> ', stores);

  e.sender.send('db-got-all-stores', stores);

});

//storemgr.js
exports.getAllStores = () => {

    return new Promise((resolve, reject) => { //NOTE returns a Promise

        const sql = "select * from STORE";
        let res = [];
        db.each(sql, (err, row) => {
            console.log('row -> ', row); //NOTE actually correctly logs the data to the console
            res.push(row);
        });
        console.log('res -> ', res); //NOTE this is still an empty array
        resolve(res);
    });
}

</code>```

The stores variable in main.js is always undefined. So is res in storemgr.js.

My question is, what is the best approach to handle the Database connection when trying to display the data as soon as I have read it?

Forget about actually displaying the data for now, I am stumped as to why the return object is always undefined after I have already read it from the database.

I also tried different db functions such as .all, the result is much the same.

Title: SQLite data undefined in ipcMain

Body:
I am writing a small ElectronJS application to interact with a database using the NodeJS implementation of SQLite3.
I am able to store data in the database, no problems.

//renderer.js
document.querySelector('#new-store-add').addEventListener('click', _ => {
    console.log("Adding new Store");
    let storeName = document.querySelector("#new-store-name-input").value;
    ipcRenderer.send('db-add-new-store', storeName);
});

//main.js
ipcMain.on('db-add-new-store', (e, r) => {
  addStore(r);
});

//storemgr.js
exports.addStore = (newStore) => {
    const sql = `INSERT INTO STORE (store_name) VALUES('${newStore}')`;
    db.exec(sql);
}

Problems arise when I try to read and display data from the same table.
I have tried a couple of different approaches including the current async Promise approach

//renderer.js
document.querySelector('#main-get-stores').addEventListener('click', () => {
    ipcRenderer.send('db-get-all-stores');
});

ipcRenderer.on('db-got-all-stores', (e,r) => {
    console.log('r -> ', r);
    console.log('e -> ', e);
    console.log('e.stores -> ', e.stores);
})

//main.js
ipcMain.on('db-get-all-stores', async (e,r) => { //NOTE async here
  console.log("Get All Stores");

  let stores = await getAllStores();

  console.log('stores -> ', stores);

  e.sender.send('db-got-all-stores', stores);

});

//storemgr.js
exports.getAllStores = () => {

    return new Promise((resolve, reject) => { //NOTE returns a Promise

        const sql = "select * from STORE";
        let res = [];
        db.each(sql, (err, row) => {
            console.log('row -> ', row); //NOTE actually correctly logs the data to the console
            res.push(row);
        });
        console.log('res -> ', res); //NOTE this is still an empty array
        resolve(res);
    });
}

The stores variable in main.js is always undefined. So is res in storemgr.js.

My question is, what is the best approach to handle the Database connection when trying to display the data as soon as I have read it?

Forget about actually displaying the data for now, I am stumped as to why the return object is always undefined after I have already read it from the database.

I also tried different db functions such as .all, the result is much the same.


问:
use gpu to accelerate data preprocessing in google colab (Python)
I am trying to train my model. The input data consists of similar patches. Generating similar patches (8x8x10) function takes a very long time, even when Colab is connected to a GPU (but not used).

```<code>Patches_label = img_to_Patches(images_label, sP, nSP, offset)
# This line takes very long
Patches_in = SearchSimilarPatches(images_in, sP, nSP, sW, offset)

history = model.fit(Patches_in, Patches_label, steps_per_epoch=2000, epochs=400, verbose=1, initial_epoch=initial_epoch, callbacks=[checkpointer,csv_logger,lr_scheduler])

</code>```

Colab notified me that I am connected to a GPU, but it is not in use.

How can I make sure Colab is using GPU for data preprocessing?

Body:
I am trying to train my model. The input data consists of similar patches. Generating similar patches (8x8x10) function takes a very long time, even when Colab is connected to a GPU (but not used).

Patches_label = img_to_Patches(images_label, sP, nSP, offset)
# This line takes very long
Patches_in = SearchSimilarPatches(images_in, sP, nSP, sW, offset)

history = model.fit(Patches_in, Patches_label, steps_per_epoch=2000, epochs=400, verbose=1, initial_epoch=initial_epoch, callbacks=[checkpointer,csv_logger,lr_scheduler])

Colab notified me that I am connected to a GPU, but it is not in use.

How can I make sure Colab is using GPU for data preprocessing?


问:
chrome.tabs.sendMessage - why callback fails?
I have been experimenting with messaging APIs in Chrome extensions. I wanted to send a message from the background script to the content script and get some response back. I prepared a function just for that. Here are the two versions of that funcion:

V1:

```<code>public static async sendToContentScript<R>(tabId: number, command: CommandToContent): Promise<R> {
    const payload: CommandBody = { command };
    return await chrome.tabs.sendMessage(tabId, payload);
}
</code>```

V2:

```<code>public static async sendToContentScript<R>(tabId: number, command: CommandToContent): Promise<R> {
    return new Promise((resolve, _) => {
        const payload: CommandBody = { command };

        chrome.runtime.sendMessage(payload, function (response: R) {
            resolve(response);
            return true;
        });
    });
}
</code>```

Version V1 works, while versions V2 does not. It throws the following error:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I've read a few posts about that error and it's not the first time that I see it. However, I did not find any explanation that would really "click" for me, I basically don't understand why V1 works and V2 does not. It would be great if you could help me understand that.

Body:
I have been experimenting with messaging APIs in Chrome extensions. I wanted to send a message from the background script to the content script and get some response back. I prepared a function just for that. Here are the two versions of that funcion:

V1:

public static async sendToContentScript<R>(tabId: number, command: CommandToContent): Promise<R> {
    const payload: CommandBody = { command };
    return await chrome.tabs.sendMessage(tabId, payload);
}

V2:

public static async sendToContentScript<R>(tabId: number, command: CommandToContent): Promise<R> {
    return new Promise((resolve, _) => {
        const payload: CommandBody = { command };

        chrome.runtime.sendMessage(payload, function (response: R) {
            resolve(response);
            return true;
        });
    });
}

Version V1 works, while versions V2 does not. It throws the following error:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I've read a few posts about that error and it's not the first time that I see it. However, I did not find any explanation that would really "click" for me, I basically don't understand why V1 works and V2 does not. It would be great if you could help me understand that.


问:
SSH / SFTP is not correctly executed from IIS in .NET Application
I took over a .NET application and the application is run under an ApplicationPoolIdentity User with LoadProfile set on True.

The Application executes ssh and sftp commands from the windows cmd. But since the ssh host changed its IP, the commands don't seem to work any more. We're using the standard OpenSSH client on a Windows Server.

Is there a possibility to try and run these commands manually under the ApplicationPoolIdentity user?

I already tried the following

succesfully connected and executed GET and PUT with my own user account

checked and set the permissions on the ssh and key files

checked with the destination server

checked port and IP

Tried using FQDN

Updated the know_hosts file

Thanks for any feedback.


问:
heroku rejecting git push with error message showing stale files
My rails app has only one branch, main When I view the file causing the error on the github site page for my repository it shows the updated code, but the error message I receive from Heroku shows the old code still causing the same error It also says I must now use git push heroku <branch-name>:main What does that mean? It seems redundant Maybe they mean repository-name:main? I tried running git push heroku main:main and it fails with the same error showing my old outdated code


问:
srcset attribute not working when the image in srcset is already used in the page
I don't know if this is the expected behaviour with the srcset attribute. But for some reason, it's not working for me.

So, I'm testing on windows and mac, srcset differentiates them by the pixel density. So 1x means lower (Windows) and 2x means higher (Mac)

But for some reason, even in Windows, it's showing the 2x image instead of 1x. This happens only for those images which have already been used in the page.

```<code>somewhere in the same file
<img src="already_used_image.jpg" >

<img
srcset="already_used_image.jpg 2x, normal_image.jpg 1x"
src="fallback_image.jpg"
>
</code>```

I have checked the docs but couldn't find relevant info regarding this particular case.

Body:
I don't know if this is the expected behaviour with the srcset attribute. But for some reason, it's not working for me.

So, I'm testing on windows and mac, srcset differentiates them by the pixel density. So 1x means lower (Windows) and 2x means higher (Mac)

But for some reason, even in Windows, it's showing the 2x image instead of 1x. This happens only for those images which have already been used in the page.

somewhere in the same file

I have checked the docs but couldn't find relevant info regarding this particular case.


问:
How could I scrape data using scrapy and playwright to scrapy data and images and save them dynamically
I need to scrap each product from this site (all pages) and then for each product I need
to extract data and save the images in a dynamic way but I face problems with saving images and creating folders.

When I run the script it work and don't rise problems but it don't do what it suppose to do
it just open pages and pass without scraping and some pages get all images and some get just one or two .
note: I'm using ubuntu.

import scrapy
from ..items import ShoppingItem
import re
import csv
import os

class AstraSpider(scrapy.Spider):
    name = 'Astra'
    start_urls = ['https://www.asos.com/search/?page=1&q=women%20cloth']
    page_number = 2
    product_number = 1
    ########## File 1
    f1 = open('file1.csv','a')
    pen = csv.writer(f1)
    pen.writerow(['Product_id','URL','product_title','product_details','sizes'])
    f1.close()
    ######### File 2
    f2 = open('file2.csv','a')
    pen = csv.writer(f2)
    pen.writerow(['Product_id','images path','images URLs'])
    f2.close()

    def parse(self, response):
        for url in response.css('a.productLink_KM4PI::attr(href)').extract():
            yield scrapy.Request(url,self.parse_products, meta={'playwright': True})
        #===================================================================
        print(AstraSpider.page_number)
        print('='*100)
        if AstraSpider.page_number < 1300:
            AstraSpider.page_number += 1
            next_page = f'https://www.asos.com/search/?page={AstraSpider.page_number}&q=women%20cloth'
            yield response.follow(next_page,callback = self.parse)

    def parse_products(self, response):
        #open_in_browser(response)
        items = ShoppingItem()
        #========= getting the data
        ch = response.url
        res = re.search(r'prd/\d+',ch)
        items['url'] = ch
        items['product_id'] = res.group()[4:]
        items['product_title'] = response.css('h1.jcdpl::text').get()
        #####################
        part1 = response.css('div.F_yfF ul li::text').extract()
        part2 = response.css('p.Jk9Oz::text').extract()
        items['product_details'] = part1 + part2
        items['sizes'] = response.css('option::text').extract()
        #####################
        f1 = open('file1.csv','a')
        pen = csv.writer(f1)
        pen.writerow([items['product_id'],items['url'],items['product_title'],items['product_details'],items['sizes'][1:]])
        f1.close()
        #========= image part
        images_urls = response.css('img.img::attr(src)').extract()
        folder_name = f'data/page_{AstraSpider.page_number}/product_{AstraSpider.product_number}'
        f2 = open('file2.csv','a')
        pen = csv.writer(f2)
        pen.writerow([items['product_id'],folder_name,images_urls])
        f2.close()
        os.makedirs(folder_name)
        for url in images_urls:
            yield scrapy.Request(url, callback=self.save_image, meta={'folder': folder_name})
        AstraSpider.product_number += 1

    def save_image(self, response):
        folder = response.meta['folder']
        file_name = response.url.split("/")[-1]
        with open(f'{folder}/{file_name}.jpg', 'wb') as f:
            f.write(response.body)

```


问:
Nginx panic, my project was fine and it started to throw 502 errors
I'm deploying my project, I had no problem until i decided to buy a domain for my digital ocean droplet i added the records from my namecheap domain to my droplet i was working on it then suddenly when i want access to myproject/api it's now showing 502 errors i'll give you all the informations so maybe you can help me with it

1 ) mongoDB atlas status : All good ; i even tried " npm start " to see if DB can't connect but it connects perfectly fine. I refreshed in .env the connecting string, it stills connect with no problems.

2 ) Nginx error.log shows this information i don't really understand, i guess it's the key point :

86 connect() failed (111: Connection refused) while connecting to upstream, client: 164.92.206.160, server: _, request: "GET /api/category/cinema HTTP/1.1", upstream: "http://[::1]:8000/api

3 ) The front is perfectly showing himself on my project domain url it starts showing 502 error when i click something using my DB/server.

4 ) i rebuilded and restarted front & back + nginx multiple times

5 ) i updated endpoints and .env variables to match with my fresh domain and it works, only the API side is breaking

6 ) nginx conf file :

```<code>
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name _;

        location /api {
    proxy_pass http://localhost:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

</code>```

I tried barely everything and it's still not working as it was used to work.

Body:
I'm deploying my project, I had no problem until i decided to buy a domain for my digital ocean droplet i added the records from my namecheap domain to my droplet i was working on it then suddenly when i want access to myproject/api it's now showing 502 errors i'll give you all the informations so maybe you can help me with it

1 ) mongoDB atlas status : All good ; i even tried " npm start " to see if DB can't connect but it connects perfectly fine. I refreshed in .env the connecting string, it stills connect with no problems.

2 ) Nginx error.log shows this information i don't really understand, i guess it's the key point :

86 connect() failed (111: Connection refused) while connecting to upstream, client: 164.92.206.160, server: _, request: "GET /api/category/cinema HTTP/1.1", upstream: "http://[::1]:8000/api

3 ) The front is perfectly showing himself on my project domain url it starts showing 502 error when i click something using my DB/server.

4 ) i rebuilded and restarted front & back + nginx multiple times

5 ) i updated endpoints and .env variables to match with my fresh domain and it works, only the API side is breaking

6 ) nginx conf file :

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name _;

        location /api {
    proxy_pass http://localhost:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

I tried barely everything and it's still not working as it was used to work.


问:
Can I get a hidden value from the backend form by hook?
In Typo3 9.5 I'm trying to read a hidden value from a page which holds the ID of a specific content element. I'm using a hook for some calculation and thought I could reuse the hook to check if a value changed. If the value changed I want to delete the content element. Right now I can create the element and save the ID in the hiddenValue. But the hiddenValue is never passed to the preProcessFieldArray or the postProcessFieldArray which I use.

I did add a passthrough field but this seems to not affect the fieldArray. I can't find anything on the passthrough type in the documentation