问:
Gateway Time-out with StreamingResponse and custom Middleware fastapi
I wrote a simple custom Middleware as below:

```<code>class LoggingMiddleware(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request, call_next):
        user_token = request.headers.get("x-token")
        req_id = time_ns()
        try:
            user_phone_number = decode(user_token, JWT_SECRET_KEY, algorithms=[HASH_ALGORITHM]).get("phone_number")
        except:
            user_phone_number = ''
        req_body = await get_json(request)
        reqb = dumps(req_body.decode('utf-8', 'ignore'), ensure_ascii=False)
        self.req_logger.info()

        response_time = 0
        try:
            s = time.time()
            resp = await call_next(request)
            response_time = round(time.time() - s, 2)
        except:
            self.error_logger.error()
            raise CustomException(
                details=ErrorResponseSerializer(
                    )
                ),
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

        resp_body = b""
        async for item in resp.body_iterator:
            resp_body += item
        respb = dumps(resp_body.decode('utf-8', 'ignore'), ensure_ascii=False)
        if resp.status_code != 200:
            self.error_logger.error()
        return Response(
            content=resp_body,
            status_code=resp.status_code,
            headers=dict(resp.headers),
            media_type=resp.media_type
        )
</code>```

and in one of my endpoints I wrote this functionality:

```<code>@router.get("/statistics/contract/count/", response_model=StatisticsCountsResponseSerializer)
def get_contract_count(
        province: str = None,
        dashboard_status: DashboardContractStatus = None,
        status: ContractStatus = None,
        csv: int = 0,
        context: Context = Depends(get_context)):
    repository = PostgresContractRepository(context=context)
    result = repository.get_counts(PROVINCES.get(province), dashboard_status, status)
    if not csv:
        return StatisticsCountsResponseSerializer.parse_obj({"count": result})
    else:
        filename = f"contract_counts_{int(datetime.datetime.utcnow().timestamp())}.csv"
        return StreamingResponse(
            # get_csv() yield an string which has csv format: yield "name,fmaily\nemad,emad"
            get_csv(),
            media_type="text/csv",
            headers={"Content-Disposition": f'attachment; filename="{filename}"'}
        )
</code>```

when I send the request to this endpoint I gave this error in postman:

```<code><html>
<head><title>504 Gateway Time-out</title></head>
<body>
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
</code>```

When I remove my middleware, everything is right and I got the excpected response. Maybe its useful to know that in other endpoints I return FileResponse and with the Middleware everything works fine. Just with StreamingResponse and Middleware I cannot get response.

Edit #1

After reading one of my comments, in this link, I change my code to this one:

```<code>async def dispatch(self, request, call_next):
    # self.check_authorization(request)
    user_token = request.headers.get("x-token")
    try:
        user_phone_number = decode(user_token, JWT_SECRET_KEY, algorithms=[HASH_ALGORITHM]).get("phone_number")
    except:
        user_phone_number = ''

    details = {
        "token": {
            "phone_number": user_phone_number
        },
        "request": {
            "id": time_ns(),
            "url_path": request.url.path,
            "query_params": request.query_params,
            "path_params": request.path_params
        },
        "response": {
            "duration": 0.0,
            "status_code": 200,
            "exception": None
        }
    }

    request_body = await get_json(request)
    try:
        s = time.time()
        response = await call_next(request)
        details["response"]["duration"] = round(time.time() - s, 2)
    except:
        self.error_logger.error(
            Logger.message_formatter(
                request_id=details.get("request").get("id"),
                path=request.url.path,
                token_phone_number=user_phone_number,
                query_params=request.query_params,
                path_params=request.path_params,
                body=request_body.decode('utf-8', 'ignore')
            )
        )
        self.error_logger.error(
            Logger.message_formatter(
                request_id=details.get("request").get("id"),
                path=request.url.path,
                message=traceback.format_exc(),
                status=500
            )
        )
        raise CustomException(
            details=ErrorResponseSerializer(
                metadata=MessageResponseSerializer(
                    type=MessageTypeEnum.error,
                    text=MessageTextResponseSerializer(
                        text="internal server error",
                        translate="..."
                    )
                )
            ),
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

    response_body = b""
    async for item in response.body_iterator:
        response_body += item

    return Response(
        content=response_body,
        status_code=response.status_code,
        headers=dict(response.headers),
        media_type=response.media_type,
        background=BackgroundTask(self.log, request_body, response_body, details)
    )
</code>```

But the problem does not solve. I still get time out.

Body:
I wrote a simple custom Middleware as below:

class LoggingMiddleware(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request, call_next):
        user_token = request.headers.get("x-token")
        req_id = time_ns()
        try:
            user_phone_number = decode(user_token, JWT_SECRET_KEY, algorithms=[HASH_ALGORITHM]).get("phone_number")
        except:
            user_phone_number = ''
        req_body = await get_json(request)
        reqb = dumps(req_body.decode('utf-8', 'ignore'), ensure_ascii=False)
        self.req_logger.info()

        response_time = 0
        try:
            s = time.time()
            resp = await call_next(request)
            response_time = round(time.time() - s, 2)
        except:
            self.error_logger.error()
            raise CustomException(
                details=ErrorResponseSerializer(
                    )
                ),
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

        resp_body = b""
        async for item in resp.body_iterator:
            resp_body += item
        respb = dumps(resp_body.decode('utf-8', 'ignore'), ensure_ascii=False)
        if resp.status_code != 200:
            self.error_logger.error()
        return Response(
            content=resp_body,
            status_code=resp.status_code,
            headers=dict(resp.headers),
            media_type=resp.media_type
        )

and in one of my endpoints I wrote this functionality:

@router.get("/statistics/contract/count/", response_model=StatisticsCountsResponseSerializer)
def get_contract_count(
        province: str = None,
        dashboard_status: DashboardContractStatus = None,
        status: ContractStatus = None,
        csv: int = 0,
        context: Context = Depends(get_context)):
    repository = PostgresContractRepository(context=context)
    result = repository.get_counts(PROVINCES.get(province), dashboard_status, status)
    if not csv:
        return StatisticsCountsResponseSerializer.parse_obj({"count": result})
    else:
        filename = f"contract_counts_{int(datetime.datetime.utcnow().timestamp())}.csv"
        return StreamingResponse(
            # get_csv() yield an string which has csv format: yield "name,fmaily\nemad,emad"
            get_csv(),
            media_type="text/csv",
            headers={"Content-Disposition": f'attachment; filename="{filename}"'}
        )

when I send the request to this endpoint I gave this error in postman:

<title>504 Gateway Time-out</title>

504 Gateway Time-out

nginx/1.20.1

When I remove my middleware, everything is right and I got the excpected response. Maybe its useful to know that in other endpoints I return FileResponse and with the Middleware everything works fine. Just with StreamingResponse and Middleware I cannot get response.

Edit #1

After reading one of my comments, in this link, I change my code to this one:

async def dispatch(self, request, call_next):
    # self.check_authorization(request)
    user_token = request.headers.get("x-token")
    try:
        user_phone_number = decode(user_token, JWT_SECRET_KEY, algorithms=[HASH_ALGORITHM]).get("phone_number")
    except:
        user_phone_number = ''

    details = {
        "token": {
            "phone_number": user_phone_number
        },
        "request": {
            "id": time_ns(),
            "url_path": request.url.path,
            "query_params": request.query_params,
            "path_params": request.path_params
        },
        "response": {
            "duration": 0.0,
            "status_code": 200,
            "exception": None
        }
    }

    request_body = await get_json(request)
    try:
        s = time.time()
        response = await call_next(request)
        details["response"]["duration"] = round(time.time() - s, 2)
    except:
        self.error_logger.error(
            Logger.message_formatter(
                request_id=details.get("request").get("id"),
                path=request.url.path,
                token_phone_number=user_phone_number,
                query_params=request.query_params,
                path_params=request.path_params,
                body=request_body.decode('utf-8', 'ignore')
            )
        )
        self.error_logger.error(
            Logger.message_formatter(
                request_id=details.get("request").get("id"),
                path=request.url.path,
                message=traceback.format_exc(),
                status=500
            )
        )
        raise CustomException(
            details=ErrorResponseSerializer(
                metadata=MessageResponseSerializer(
                    type=MessageTypeEnum.error,
                    text=MessageTextResponseSerializer(
                        text="internal server error",
                        translate="..."
                    )
                )
            ),
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

    response_body = b""
    async for item in response.body_iterator:
        response_body += item

    return Response(
        content=response_body,
        status_code=response.status_code,
        headers=dict(response.headers),
        media_type=response.media_type,
        background=BackgroundTask(self.log, request_body, response_body, details)
    )

But the problem does not solve. I still get time out.


来源: stackexchange

问:
Puppeteer to convert html to pdf using Nodejs in Durable functions(fan out fan in)
I'm working on a small project to convert a large xml to several formatted pdf documents. The large xml contains multiple similar format xmls. So I'm using a single html template for printing all the documents. After producing all the pdf documents I also need to produce a metadata file with some basic info on each document that was printed.

I thought using the fan out fan in scenario of durable functions is a perfect for my use case. I'm working with Nodejs. I setup all my code and it seems to be working fine locally. The Orchestration function looks like the below.

```<code>const df = require("durable-functions");

module.exports = df.orchestrator(function* (context) {
    var xmldata = yield context.df.callActivity("DurablegetblobJS1","");
    var tasks = [];
    for (file of xmldata) {
        tasks.push(context.df.callActivity("Durableactivityjs2", file));
    }
    const outputs = yield context.df.Task.all(tasks);
    var finalout = "";
    for (out of outputs){
        console.log('I am done1 :' + out );
        finalout = finalout + out;
    }
    return finalout;
});
</code>```

DurablegetblobJS1 : Fetches the entire xmls and splits it into multiple smaller xmls(1 per document).

Durableactivityjs2 : Fetches the html template, extracts the different values from the individual xmls and applies them to the html and finally prints out the pdf into an azure storage. It returns  the name of the pdf document that was printed for creation of the metadata file. The code for this is below.

```<code>var fs = require('fs');
var xml2js       = require('xml2js');
var html_to_pdf = require('html-pdf-node');
var parser       = new xml2js.Parser();

module.exports = async function (context) {
    //console.log("Hello from activity :")
    var xmldict = {}
    var xmltext = context.bindings.name;

    //Extract the nodes and attributes
    metadata(xmltext,xmldict);
    report(xmltext,xmldict);
    context.log(xmldict)

    const { BlobServiceClient } = require("@azure/storage-blob");
    // Load the .env file if it exists
    require("dotenv").config();
    const AZURE_STORAGE_CONNECTION_STRING = process.env.STORAGE_CONNECTION_STRING || "";
    const blobServiceClient = BlobServiceClient.fromConnectionString(
        AZURE_STORAGE_CONNECTION_STRING
    );
    var containerClient = blobServiceClient.getContainerClient('test');
    var blobname = 'comb_template.html';
    var blockBlobClient = containerClient.getBlockBlobClient(blobname);
    var downloadBlockBlobResponse = await blockBlobClient.download(0);
    var html_template = await streamToText(downloadBlockBlobResponse.readableStreamBody);

    let options = { format: 'A4'};
    let file = { content: html_template};
    const x = await writepdf1(file, options,blobServiceClient,xmldict);
    console.log("Written Blob PDF");
    return x;

};

async function writepdf1(file, options,blobServiceClient,xmldict){
    const pdfBuffer = await html_to_pdf.generatePdf(file, options);
    const containerClient = blobServiceClient.getContainerClient('test2');
    const targetblob = xmldict['OU'] + '/' + xmldict['ReportName'] + '/' + xmldict['OU'] + '_' + xmldict['ReportName'] + '_' + xmldict['DocumentID'] + '_' + '.pdf';
    console.log('Blob name :' + targetblob);
    const blockBlobClient_t = containerClient.getBlockBlobClient(targetblob);
    const uploadBlobResponse =  await blockBlobClient_t.upload(pdfBuffer, pdfBuffer.length);
    return targetblob;
}

async function streamToText(readable) {
    readable.setEncoding('utf8');
    let data = '';
    for await (const chunk of readable) {
      data += chunk;
    }
    return data;
  }

function metadata(xmltext,xmldict){
    parser.parseString(xmltext, function (err, result) {
        var test1 = result['HPDPSMsg']['DocumentRequest'][0]['MetaData'][0];
        Object.entries(test1).forEach(([key, value]) => {
            xmldict[key] = value[0];
         });
    });
    }

function report(xmltext,xmldict){
        parser.parseString(xmltext, function (err, result) {
            var test2 = result['HPDPSMsg']['DocumentRequest'][0]['Report'][0]['$'];
            Object.entries(test2).forEach(([key, value]) => {
                xmldict[key] = value;
             });
        });
    }
</code>```

However, when I deploy the entire project into a azure premium function(EP1 - Windows), I see some errors in app insights when I try and execute my function and the pdfs are never generated.

Activity function 'Durableactivityjs2' failed: Could not find browser
revision 818858. Run "PUPPETEER_PRODUCT=firefox npm install" or
"PUPPETEER_PRODUCT=firefox yarn install" to download a supported
Firefox browser binary

I'm a bit clueless how I'm supposed to resolve this. Any help or suggestions would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a small project to convert a large xml to several formatted pdf documents. The large xml contains multiple similar format xmls. So I'm using a single html template for printing all the documents. After producing all the pdf documents I also need to produce a metadata file with some basic info on each document that was printed.

I thought using the fan out fan in scenario of durable functions is a perfect for my use case. I'm working with Nodejs. I setup all my code and it seems to be working fine locally. The Orchestration function looks like the below.

const df = require("durable-functions");

module.exports = df.orchestrator(function* (context) {
    var xmldata = yield context.df.callActivity("DurablegetblobJS1","");
    var tasks = [];
    for (file of xmldata) {
        tasks.push(context.df.callActivity("Durableactivityjs2", file));
    }
    const outputs = yield context.df.Task.all(tasks);
    var finalout = "";
    for (out of outputs){
        console.log('I am done1 :' + out );
        finalout = finalout + out;
    }
    return finalout;
});

DurablegetblobJS1 : Fetches the entire xmls and splits it into multiple smaller xmls(1 per document).

Durableactivityjs2 : Fetches the html template, extracts the different values from the individual xmls and applies them to the html and finally prints out the pdf into an azure storage. It returns  the name of the pdf document that was printed for creation of the metadata file. The code for this is below.

var fs = require('fs');
var xml2js       = require('xml2js');
var html_to_pdf = require('html-pdf-node');
var parser       = new xml2js.Parser();

module.exports = async function (context) {
    //console.log("Hello from activity :")
    var xmldict = {}
    var xmltext = context.bindings.name;

    //Extract the nodes and attributes
    metadata(xmltext,xmldict);
    report(xmltext,xmldict);
    context.log(xmldict)

    const { BlobServiceClient } = require("@azure/storage-blob");
    // Load the .env file if it exists
    require("dotenv").config();
    const AZURE_STORAGE_CONNECTION_STRING = process.env.STORAGE_CONNECTION_STRING || "";
    const blobServiceClient = BlobServiceClient.fromConnectionString(
        AZURE_STORAGE_CONNECTION_STRING
    );
    var containerClient = blobServiceClient.getContainerClient('test');
    var blobname = 'comb_template.html';
    var blockBlobClient = containerClient.getBlockBlobClient(blobname);
    var downloadBlockBlobResponse = await blockBlobClient.download(0);
    var html_template = await streamToText(downloadBlockBlobResponse.readableStreamBody);

    let options = { format: 'A4'};
    let file = { content: html_template};
    const x = await writepdf1(file, options,blobServiceClient,xmldict);
    console.log("Written Blob PDF");
    return x;

};

async function writepdf1(file, options,blobServiceClient,xmldict){
    const pdfBuffer = await html_to_pdf.generatePdf(file, options);
    const containerClient = blobServiceClient.getContainerClient('test2');
    const targetblob = xmldict['OU'] + '/' + xmldict['ReportName'] + '/' + xmldict['OU'] + '_' + xmldict['ReportName'] + '_' + xmldict['DocumentID'] + '_' + '.pdf';
    console.log('Blob name :' + targetblob);
    const blockBlobClient_t = containerClient.getBlockBlobClient(targetblob);
    const uploadBlobResponse =  await blockBlobClient_t.upload(pdfBuffer, pdfBuffer.length);
    return targetblob;
}

async function streamToText(readable) {
    readable.setEncoding('utf8');
    let data = '';
    for await (const chunk of readable) {
      data += chunk;
    }
    return data;
  }

function metadata(xmltext,xmldict){
    parser.parseString(xmltext, function (err, result) {
        var test1 = result['HPDPSMsg']['DocumentRequest'][0]['MetaData'][0];
        Object.entries(test1).forEach(([key, value]) => {
            xmldict[key] = value[0];
         });
    });
    }

function report(xmltext,xmldict){
        parser.parseString(xmltext, function (err, result) {
            var test2 = result['HPDPSMsg']['DocumentRequest'][0]['Report'][0]['$'];
            Object.entries(test2).forEach(([key, value]) => {
                xmldict[key] = value;
             });
        });
    }

However, when I deploy the entire project into a azure premium function(EP1 - Windows), I see some errors in app insights when I try and execute my function and the pdfs are never generated.

Activity function 'Durableactivityjs2' failed: Could not find browser
revision 818858. Run "PUPPETEER_PRODUCT=firefox npm install" or
"PUPPETEER_PRODUCT=firefox yarn install" to download a supported
Firefox browser binary

I'm a bit clueless how I'm supposed to resolve this. Any help or suggestions would be appreciated.


问:
Unable to align the content to the top of the screen
I'm writing a react native code where I'm trying to split the screen into 2. There are 3 tabs, and based on the tab I click, I need to display the content. Here My issue is, the content is getting displayed. But the content displayed is not from the top of the screen.

Here is my code.

```<code>import { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const App = () => {
  const [facetGroup, setFacetGroup] = useState([
    { name: 'tab 1', index: 1, description: 'tab one description' },
    { name: 'tab 2', index: 2, description: 'tab two description' },
    { name: 'tab 3', index: 3, description: 'tab three description' },
  ]);
  const [selectedIndex, setSelectedIndex] = useState(1);
  const handlePress = (index) => {
    setSelectedIndex(index);
  };
  return (
    <View style={styles.mainContainer}>
      <View style={{ flexDirection: 'col' }}>
        {facetGroup.map((item: any) => (
          <View key={item.index} style={styles.menuContainer}>
            <TouchableOpacity
              onPress={() => handlePress(item.index)}
              style={styles.title}>
              <Text>{item.name}</Text>
            </TouchableOpacity>
          </View>
        ))}
      </View>
      <View>
        {facetGroup.map((item: any) => (
          <View key={item.index} style={styles.descContainer}>
            <View style={{ marginLeft: 40 }}>
              {selectedIndex === item.index && <Text>{item.description}</Text>}
            </View>
          </View>
        ))}
      </View>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  mainContainer: { flex: 1, height: 500, flexDirection: 'row' },
  menuContainer: {
    backgroundColor: '#fff',
    textAlign: 'center',
    height: 40,
    border: '1px solid black',
    padding: 20,
  },
  descContainer: {
    backgroundColor: '#fff',
    height: 400,
    marginTop: 0,
    justifyContent: 'flex-start',
  },
});
</code>```

And here is working fiddle. Please let me know how can I fix this.

Thanks

Body:
I'm writing a react native code where I'm trying to split the screen into 2. There are 3 tabs, and based on the tab I click, I need to display the content. Here My issue is, the content is getting displayed. But the content displayed is not from the top of the screen.

Here is my code.

import { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

const App = () => {
  const [facetGroup, setFacetGroup] = useState([
    { name: 'tab 1', index: 1, description: 'tab one description' },
    { name: 'tab 2', index: 2, description: 'tab two description' },
    { name: 'tab 3', index: 3, description: 'tab three description' },
  ]);
  const [selectedIndex, setSelectedIndex] = useState(1);
  const handlePress = (index) => {
    setSelectedIndex(index);
  };
  return (
    <View style={styles.mainContainer}>
      <View style={{ flexDirection: 'col' }}>
        {facetGroup.map((item: any) => (
          <View key={item.index} style={styles.menuContainer}>
            <TouchableOpacity
              onPress={() => handlePress(item.index)}
              style={styles.title}>
              <Text>{item.name}</Text>
            </TouchableOpacity>
          </View>
        ))}
      </View>
      <View>
        {facetGroup.map((item: any) => (
          <View key={item.index} style={styles.descContainer}>
            <View style={{ marginLeft: 40 }}>
              {selectedIndex === item.index && <Text>{item.description}</Text>}
            </View>
          </View>
        ))}
      </View>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  mainContainer: { flex: 1, height: 500, flexDirection: 'row' },
  menuContainer: {
    backgroundColor: '#fff',
    textAlign: 'center',
    height: 40,
    border: '1px solid black',
    padding: 20,
  },
  descContainer: {
    backgroundColor: '#fff',
    height: 400,
    marginTop: 0,
    justifyContent: 'flex-start',
  },
});

And here is working fiddle. Please let me know how can I fix this.

Thanks


问:
No output received ... Showing connection refused
I am not receiving any output from the server, while trying to connect with them through android code. I am not trying to connect over localhost ( as some similar questions in stack overflow suggests change URL as they are locally hosted) and my URL when checked with postman is retrieving data. Here I am not able to receive any response. I tried debugging, but cannot understand why no response is received.

```<code>public class SendRequest extends AsyncTask<String, Void, String> {

private final Context context;
private final String webUrl;
private final RequestListeners<String> mRequestListener;
public boolean showProgress;
private Exception exception;
private ProgressDialog dialogLoading;

public SendRequest(Context context, String url, boolean progress, RequestListeners<String> listener) {
    this.context = context;
    webUrl = url;
    showProgress = progress;
    mRequestListener = listener;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    if (!showProgress) return;
    try {
        if (!((Activity) context).isFinishing()) {
            dialogLoading = new ProgressDialog(context);
            dialogLoading.setMessage("Please wait...");
            dialogLoading.setCancelable(false);
            dialogLoading.show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected String doInBackground(String... params) {
    if (context == null) this.cancel(true);
    assert context != null;
    if (!NetworkHelper.isNetworkAvailable(context)) {
        exception = new NoNetworkException();
        return "";
    }
    String results = "";
    for (int i = 0; i < 2; i++) {
        results = new HttpConnection().readWebUrl(webUrl
           .replace(" ", "%20")); // results here is null always
        if (results.length() > 5) break;
    }
    return results;
}

@Override
protected void onPostExecute(String result) {
    try {
        if (showProgress && dialogLoading != null) {
            if (dialogLoading.isShowing())
                dialogLoading.dismiss();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (exception != null) {
        mRequestListener.onRequestFailed(exception);
        return;
    }
    mRequestListener.onRequestCompleted(result);
}

@Override
protected void onCancelled() {
    super.onCancelled();
    if (showProgress && dialogLoading != null)
        dialogLoading.cancel();
}
}
</code>```

The HttpConnecton class:

```<code>public class HttpConnection {

  public String readWebUrl(String weburl) {
    BufferedReader reader;
    HttpURLConnection conn;
    InputStream inStream;
    StringBuilder strResults = new StringBuilder();
    String webC;
    try {
        conn = (HttpURLConnection) new URL(weburl.replace(" ", "%20")).openConnection();
        conn.setConnectTimeout(9000);
        conn.setReadTimeout(59000);
        inStream = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inStream));
        while ((webC = reader.readLine()) != null) {
            strResults.append(webC);
        }
        reader.close();
        inStream.close();
        conn.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strResults.toString();
  }
}
</code>```

This is my logcat:

```<code>W/System.err: java.net.ConnectException: failed to connect to drivee.in/3.6.140.117 (port 443) after 9000ms: isConnected failed: ECONNREFUSED (Connection refused)
W/System.err:     at libcore.io.IoBridge.isConnected(IoBridge.java:234)
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
W/System.err:     at java.net.Socket.connect(Socket.java:884)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)
W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:79)
W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:143)
W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:342)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:331)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:249)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
W/System.err:     at com.sun.drivesupervisor.network.HttpConnection.readWebUrl(HttpConnection.java:21)
W/System.err:     at com.sun.drivesupervisor.network.SendRequest.doInBackground(SendRequest.java:53)
W/System.err:     at com.sun.drivesupervisor.network.SendRequest.doInBackground(SendRequest.java:11)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
W/System.err:     at libcore.io.IoBridge.isConnected(IoBridge.java:223)
</code>```

Body:
I am not receiving any output from the server, while trying to connect with them through android code. I am not trying to connect over localhost ( as some similar questions in stack overflow suggests change URL as they are locally hosted) and my URL when checked with postman is retrieving data. Here I am not able to receive any response. I tried debugging, but cannot understand why no response is received.

public class SendRequest extends AsyncTask<String, Void, String> {

private final Context context;
private final String webUrl;
private final RequestListeners<String> mRequestListener;
public boolean showProgress;
private Exception exception;
private ProgressDialog dialogLoading;

public SendRequest(Context context, String url, boolean progress, RequestListeners<String> listener) {
    this.context = context;
    webUrl = url;
    showProgress = progress;
    mRequestListener = listener;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    if (!showProgress) return;
    try {
        if (!((Activity) context).isFinishing()) {
            dialogLoading = new ProgressDialog(context);
            dialogLoading.setMessage("Please wait...");
            dialogLoading.setCancelable(false);
            dialogLoading.show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected String doInBackground(String... params) {
    if (context == null) this.cancel(true);
    assert context != null;
    if (!NetworkHelper.isNetworkAvailable(context)) {
        exception = new NoNetworkException();
        return "";
    }
    String results = "";
    for (int i = 0; i < 2; i++) {
        results = new HttpConnection().readWebUrl(webUrl
           .replace(" ", "%20")); // results here is null always
        if (results.length() > 5) break;
    }
    return results;
}

@Override
protected void onPostExecute(String result) {
    try {
        if (showProgress && dialogLoading != null) {
            if (dialogLoading.isShowing())
                dialogLoading.dismiss();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (exception != null) {
        mRequestListener.onRequestFailed(exception);
        return;
    }
    mRequestListener.onRequestCompleted(result);
}

@Override
protected void onCancelled() {
    super.onCancelled();
    if (showProgress && dialogLoading != null)
        dialogLoading.cancel();
}
}

The HttpConnecton class:

public class HttpConnection {

  public String readWebUrl(String weburl) {
    BufferedReader reader;
    HttpURLConnection conn;
    InputStream inStream;
    StringBuilder strResults = new StringBuilder();
    String webC;
    try {
        conn = (HttpURLConnection) new URL(weburl.replace(" ", "%20")).openConnection();
        conn.setConnectTimeout(9000);
        conn.setReadTimeout(59000);
        inStream = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inStream));
        while ((webC = reader.readLine()) != null) {
            strResults.append(webC);
        }
        reader.close();
        inStream.close();
        conn.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return strResults.toString();
  }
}

This is my logcat:

W/System.err: java.net.ConnectException: failed to connect to drivee.in/3.6.140.117 (port 443) after 9000ms: isConnected failed: ECONNREFUSED (Connection refused)
W/System.err:     at libcore.io.IoBridge.isConnected(IoBridge.java:234)
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
W/System.err:     at java.net.Socket.connect(Socket.java:884)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)
W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:79)
W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:143)
W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:342)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:331)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:249)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
W/System.err:     at com.sun.drivesupervisor.network.HttpConnection.readWebUrl(HttpConnection.java:21)
W/System.err:     at com.sun.drivesupervisor.network.SendRequest.doInBackground(SendRequest.java:53)
W/System.err:     at com.sun.drivesupervisor.network.SendRequest.doInBackground(SendRequest.java:11)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
W/System.err:     at libcore.io.IoBridge.isConnected(IoBridge.java:223)


问:
How to set up Ubuntu 22.04 VPS for laravel deploy?
I want to set up and deploy my laravel project to Ubuntu 22.04 VPS (unmanaged) I tried all tutorials, guides etc. Tried installing nginx instead of apache and vice versa, all the "needed" php modules/plugins (different tutorial, different amount on modules) to set up and install laravel on a ubuntu server. None on them solve my problem, one tutorial works just half way, another tutorial works but composer create-project stucks and so. So I dont know how to do all that VPS set up and installation with LARAVEL on Ubuntu for deployement, all the tutorials are different. So I want you guys to help me set up Ubuntu 22.04 for Laravel server vps.

Tried youtube tutorials, web tutorials, guides. Every tutorial is different so I dont know how to do it right... Tried to change Ubuntu versions, change web servers (nginx and apache) none of that works for me.


问:
Exception caught by widgets library -- The following StateError was thrown building Builder: Bad state: No element

Although I have been researching for 2 days, I have not found the solution to the problem despite comparing the codes. Can you help?

I get this error when switching to the product add page. I didn't normally get an error like this.


问:
How to make cloudfront not cache any html file
I have a React application served on S3, with CloudFront. I know it's a common question on how to not cache the index.html file. I could make it work changing the Behavior of CloudFront distribution, but the issue I am facing is different.

Basically, on a SPA all URL are redirected to /, so React knows how to serve each one. My issue is that when I try to access https://mywebsite.com/login, a login.html is served from CloudFront (even if I don't have this file). This file is actually index.html. My issue is that the Behavior of CloudFront distribution doesn't work for this path, and a cached index.html file is served.

I tried to change the Path Pattern to be /*.html, but this is not a valid config in CloudFront.

My question is: what's the best way to tell CloudFront that I don't want to cache any html files, and that I want to hit S3 on every request of a html file?

Thank you!


问:
Error when installing ref-napi in Node.js
I'm trying to install the ref-napi library in Node.js on Macbook M1 chip, but I need some help. The steps I did were as follows:

Installation of node-gyp npm install -g node-gyp.

Installation of Command Line Tools for Xcode 14.2.

Creation of files binding.gyp and src/binding.cc which is empty.

```<code>// binding.gyp
{
  "targets": [
    {
      "target_name": "binding",
      "sources": [ "src/binding.cc" ]
    }
  ]
}
</code>```

Building the node-gyp node-gyp configure node-gyp build and everything is OK.

```<code>gyp info it worked if it ends with ok.

gyp info using node-gyp@9.3.0
gyp info using node@16.17.0 | darwin | arm64
gyp info find Python using Python version 3.10.8 found at "/opt/homebrew/opt/python@3.10/bin/python3.10"
gyp info spawn /opt/homebrew/opt/python@3.10/bin/python3.10
gyp info spawn args [
gyp info spawn args   '/usr/local/lib/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/juanan/Desktop/Paper TFG/hola/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/juanan/Library/Caches/node-gyp/16.17.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/juanan/Library/Caches/node-gyp/16.17.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/lib/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/juanan/Library/Caches/node-gyp/16.17.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/juanan/Desktop/Paper TFG/hola',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/binding/src/binding.o
  SOLINK_MODULE(target) Release/binding.node
gyp info ok
</code>```

However, when I run npm install ref-napi, the installation fails.

```<code>npm ERR! code 1
npm ERR! path /Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi
npm ERR! command failed
npm ERR! command sh -c node-gyp-build
npm ERR! CC(target) Release/obj.target/nothing/../node-addon-api/nothing.o
npm ERR!   LIBTOOL-STATIC Release/nothing.a
npm ERR!   CXX(target) Release/obj.target/binding/src/binding.o
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.3.0
npm ERR! gyp info using node@16.17.0 | darwin | arm64
npm ERR! gyp info find Python using Python version 3.10.8 found at "/opt/homebrew/opt/python@3.10/bin/python3.10"
npm ERR! gyp info spawn /opt/homebrew/opt/python@3.10/bin/python3.10
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/juanan/Library/Caches/node-gyp/16.17.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/juanan/Library/Caches/node-gyp/16.17.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/juanan/Library/Caches/node-gyp/16.17.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! warning: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: archive library: Release/nothing.a the table of contents is empty (no object file members in the library define global symbols)
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/node-addon-api'
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/get-symbol-from-current-process-h/include'
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/ref-napi/include'
npm ERR! make: *** [Release/obj.target/binding/src/binding.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:203:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Darwin 22.2.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd /Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi
npm ERR! gyp ERR! node -v v16.17.0
npm ERR! gyp ERR! node-gyp -v v9.3.0
npm ERR! gyp ERR! not ok
</code>```

Node version: v16.17.0
node-gyp version: v9.3.0

I don't understand what are the troubles.

Trying to install ref-napi library.

Body:
I'm trying to install the ref-napi library in Node.js on Macbook M1 chip, but I need some help. The steps I did were as follows:

Installation of node-gyp npm install -g node-gyp.

Installation of Command Line Tools for Xcode 14.2.

Creation of files binding.gyp and src/binding.cc which is empty.

// binding.gyp
{
  "targets": [
    {
      "target_name": "binding",
      "sources": [ "src/binding.cc" ]
    }
  ]
}

Building the node-gyp node-gyp configure node-gyp build and everything is OK.

gyp info it worked if it ends with ok.

gyp info using node-gyp@9.3.0
gyp info using node@16.17.0 | darwin | arm64
gyp info find Python using Python version 3.10.8 found at "/opt/homebrew/opt/python@3.10/bin/python3.10"
gyp info spawn /opt/homebrew/opt/python@3.10/bin/python3.10
gyp info spawn args [
gyp info spawn args   '/usr/local/lib/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/juanan/Desktop/Paper TFG/hola/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/Users/juanan/Library/Caches/node-gyp/16.17.0/include/node/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/Users/juanan/Library/Caches/node-gyp/16.17.0',
gyp info spawn args   '-Dnode_gyp_dir=/usr/local/lib/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=/Users/juanan/Library/Caches/node-gyp/16.17.0/<(target_arch)/node.lib',
gyp info spawn args   '-Dmodule_root_dir=/Users/juanan/Desktop/Paper TFG/hola',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/binding/src/binding.o
  SOLINK_MODULE(target) Release/binding.node
gyp info ok

However, when I run npm install ref-napi, the installation fails.

npm ERR! code 1
npm ERR! path /Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi
npm ERR! command failed
npm ERR! command sh -c node-gyp-build
npm ERR! CC(target) Release/obj.target/nothing/../node-addon-api/nothing.o
npm ERR!   LIBTOOL-STATIC Release/nothing.a
npm ERR!   CXX(target) Release/obj.target/binding/src/binding.o
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.3.0
npm ERR! gyp info using node@16.17.0 | darwin | arm64
npm ERR! gyp info find Python using Python version 3.10.8 found at "/opt/homebrew/opt/python@3.10/bin/python3.10"
npm ERR! gyp info spawn /opt/homebrew/opt/python@3.10/bin/python3.10
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/juanan/Library/Caches/node-gyp/16.17.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/juanan/Library/Caches/node-gyp/16.17.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/juanan/Library/Caches/node-gyp/16.17.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! warning: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: archive library: Release/nothing.a the table of contents is empty (no object file members in the library define global symbols)
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/node-addon-api'
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/get-symbol-from-current-process-h/include'
npm ERR! clang: error: no such file or directory: 'TFG/hola/node_modules/ref-napi/include'
npm ERR! make: *** [Release/obj.target/binding/src/binding.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:203:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:513:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
npm ERR! gyp ERR! System Darwin 22.2.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd /Users/juanan/Desktop/Paper TFG/hola/node_modules/ref-napi
npm ERR! gyp ERR! node -v v16.17.0
npm ERR! gyp ERR! node-gyp -v v9.3.0
npm ERR! gyp ERR! not ok

Node version: v16.17.0
node-gyp version: v9.3.0

I don't understand what are the troubles.

Trying to install ref-napi library.


问:
Add external link, product_url single product woocommerce next to desciption
i need to add product link url (of external affiliate) under long description in woocommerce single product page. how to do? thank you

I put this code in functions.php but it doesn't print the url near the description.

```<code>add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_description( $content ){
 // Only for single product pages
 if( ! is_product() ) return $content;

 // Set the limit of words
 $limit = 13;

 if (str_word_count($content, 0) > $limit) {
     $arr = str_word_count($content, 2);
     $pos = array_keys($arr);
     $text = '<p>' . substr($content, 0, $pos[$limit]) . "..<a href='" . esc_url( $product_url ) . "' class='goto_more_offer_tab button'>...continue reading</a></p>";
     $content = force_balance_tags($text); // needed
 }
 return $content;
 }
</code>```

Body:
i need to add product link url (of external affiliate) under long description in woocommerce single product page. how to do? thank you

I put this code in functions.php but it doesn't print the url near the description.

add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_description( $content ){
 // Only for single product pages
 if( ! is_product() ) return $content;

 // Set the limit of words
 $limit = 13;

 if (str_word_count($content, 0) > $limit) {
     $arr = str_word_count($content, 2);
     $pos = array_keys($arr);
     $text = '
' . substr($content, 0, $pos[$limit]) . ".....continue reading
";
     $content = force_balance_tags($text); // needed
 }
 return $content;
 }


问:
C++ Cereal XML-Archive not working with stringstream
I am trying to get cereal-serialization to work. But somehow it does not work with the XML-Archive in combination with a stringstream.

Here is my example:

```<code>std::stringstream ss;

cereal::XMLOutputArchive oarchive(ss);
oarchive(cereal::make_nvp("data", mydata));

ss.str(); //empty
</code>```

The wierd thing is, that the JSON-Archive is working totally fine, and if a put the std::cout into the XML-Archive, it prints out my serialization. Only the stringstream stays empty.

I tried to find a solution in the documentation but did not find anything about it. Did someone else have a similar problem?

Thanks in advance!

Body:
I am trying to get cereal-serialization to work. But somehow it does not work with the XML-Archive in combination with a stringstream.

Here is my example:

std::stringstream ss;

cereal::XMLOutputArchive oarchive(ss);
oarchive(cereal::make_nvp("data", mydata));

ss.str(); //empty

The wierd thing is, that the JSON-Archive is working totally fine, and if a put the std::cout into the XML-Archive, it prints out my serialization. Only the stringstream stays empty.

I tried to find a solution in the documentation but did not find anything about it. Did someone else have a similar problem?

Thanks in advance!


问:
wp rest api controller feching categories image
I am working on  Wp Rest Api Controller I featch category using this url https://hindwatch.in/wp-json/wp/v2/categories?_embed but  am  not getting image of categories

i am  reached a lots but find right solution how can get image of categoris


问:
How to access connect client and server using zeroRPC
I am using pexpect library of python to interact with mysql client and Opening the client using server.py which is invoking the mysql client u and client.py is inserting data into the mysql.

I am not able to connect my client and server.

server.py

```<code>#!/usr/bin/python3

import pexpect
import zerorpc

class HelloRPC(object):
    def __init__(self):
        self.PROMPT = ['# ', '>>> ', '> ', '\$ ']

    def send_command(self, child, cmd):
        child.sendline(cmd)
        child.expect(self.PROMPT)
        print(child.before)

    def connectSql(self, sqlCmd, password):
        child = pexpect.spawn(sqlCmd)
        child.expect('Enter password:')
        child.sendline(password)
        child.expect ('mysql> ')
        print(child.before)
        child.expect(self.PROMPT)
        return child

    def createTable(self,dbSelct,tableCreate):
        print("we are creating table")
        # child.wait()
        # child.expect('mysql> ')
        # child.sendline('CREATE TABLE IF NOT EXISTS info(serial int NOT NULL,name varchar(45) NOT NULL);')
        # child.expect('mysql> ')
        # Child.sendline('INSERT INTO info (serial, name) VALUES (1, "Lalit");')
        # child.wait()
        # child.expect('mysql> ')
        # child.sendline('quit')

    def main(self):
        host = '172.XX.XX.XX'
        user = 'root'
        password = 'XXXXXX'
        sqlCmd = 'mysql -u root -p'
        child = self.connectSql(sqlCmd, password)
        send_command(child, 'cat /etc/shadow | grep root')

HelloRPC().main()
s = zerorpc.Server(HelloRPC())
s.bind("tcp://172.XX.XX.XX:8000")
s.run()
</code>```

client.py

```<code>#!/usr/bin/python3

import pexpect
import zerorpc

class Client:
    def run(self):
        print("run started")
        c = zerorpc.Client()
        c.connect("tcp://172.XX.XX.XX:8000")
        print("connected")
        dbSelct = "USE pexpectDB;"
        tableCreate = "CREATE TABLE IF NOT EXISTS info(serial int NOT NULL,name varchar(45) NOT NULL);"
        c.createTable(dbSelct,tableCreate)

Client().run()

</code>```

When I am calling function c.createTable(dbSelct,tableCreate) it is not taking me to the server and I am getting timeout exception.

Please help me how I can connect both of them in such a way that my client will send the argument to the server.py & I can insert my data to the table.

Body:
I am using pexpect library of python to interact with mysql client and Opening the client using server.py which is invoking the mysql client u and client.py is inserting data into the mysql.

I am not able to connect my client and server.

server.py

#!/usr/bin/python3

import pexpect
import zerorpc

class HelloRPC(object):
    def __init__(self):
        self.PROMPT = ['# ', '>>> ', '> ', '\$ ']

    def send_command(self, child, cmd):
        child.sendline(cmd)
        child.expect(self.PROMPT)
        print(child.before)

    def connectSql(self, sqlCmd, password):
        child = pexpect.spawn(sqlCmd)
        child.expect('Enter password:')
        child.sendline(password)
        child.expect ('mysql> ')
        print(child.before)
        child.expect(self.PROMPT)
        return child

    def createTable(self,dbSelct,tableCreate):
        print("we are creating table")
        # child.wait()
        # child.expect('mysql> ')
        # child.sendline('CREATE TABLE IF NOT EXISTS info(serial int NOT NULL,name varchar(45) NOT NULL);')
        # child.expect('mysql> ')
        # Child.sendline('INSERT INTO info (serial, name) VALUES (1, "Lalit");')
        # child.wait()
        # child.expect('mysql> ')
        # child.sendline('quit')

    def main(self):
        host = '172.XX.XX.XX'
        user = 'root'
        password = 'XXXXXX'
        sqlCmd = 'mysql -u root -p'
        child = self.connectSql(sqlCmd, password)
        send_command(child, 'cat /etc/shadow | grep root')

HelloRPC().main()
s = zerorpc.Server(HelloRPC())
s.bind("tcp://172.XX.XX.XX:8000")
s.run()

client.py

#!/usr/bin/python3

import pexpect
import zerorpc

class Client:
    def run(self):
        print("run started")
        c = zerorpc.Client()
        c.connect("tcp://172.XX.XX.XX:8000")
        print("connected")
        dbSelct = "USE pexpectDB;"
        tableCreate = "CREATE TABLE IF NOT EXISTS info(serial int NOT NULL,name varchar(45) NOT NULL);"
        c.createTable(dbSelct,tableCreate)

Client().run()

When I am calling function c.createTable(dbSelct,tableCreate) it is not taking me to the server and I am getting timeout exception.

Please help me how I can connect both of them in such a way that my client will send the argument to the server.py & I can insert my data to the table.


问:
Is there a way to make faster requests from django using APIKey or auth check_password?
I have django rest_framework app, and I implemented the hasApiKey approach to restrict the access to my views methods, what is happening is the requests taking from 500 ms till 800 ms to be processed, when I remove the hasAPiKey the requests taking 20 ms to be handled, which is so much diffrence.

how can I improve the speed of my requests in this case, even I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app.

any recomendations? thanks!

I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app.


问:
Anki: Appending New Dropdown Option on MenuBar? (Pycharm, Windows)
Beginner in the whole Python/Anki thing. Learning more about coding for fun and I have set up a debugging environment with pycharm and an Anki profile with the bazelfixes and it seems to start anki up fine. I want to append an extra dropdown menu on the main menu toolbar in Anki so that I can connect the actions to my functions.

I went through the hooks and the toolbar hook worked but it is not exactly what I was going for because it adds to the toolbar, not the menu. I want to add a new dropdown into the actual main menu next to tools, help, etc. connect them to functions I have made. Kind of like this

I have looked at others and sometimes they work partially but it's like a fragmented puzzle some use qmainwindow and it makes a popup separate from anki when I run it, or other approaches where they use the aqt.mw.form() functions in various ways but when I do it it will be like "nonetype doesn't take .form function." or form is not an expected argument. I want to figure out the first basic step.
I have also looked at the aqt MW thing but I am kind of confused about how it works so I am not sure if that is a better approach to read up on. The whole class>def variable> mw.append type of structure I have been seeing in other's code is a little confusing for me. Or am I going about it the completely wrong way and should use html/CSS? Any help or advice is greatly appreciated!

Also here is the bazelfixes code I have been using on pycharm.

try:
   import bazelfixes

   bazelfixes.fix_pywin32_in_bazel()
   bazelfixes.fix_extraneous_path_in_bazel()
   bazelfixes.fix_run_on_macos()
except ImportError:
   pass

if not os.environ.get(“ANKI_IMPORT_ONLY”):
   aqt.run()
```

TL;DR How do I, within this code on pycharm append an extra dropdown item on the main menu bar. Is there a hook I am missing (not the init toolbar one)? Or a different approach I should try?

Body:
Beginner in the whole Python/Anki thing. Learning more about coding for fun and I have set up a debugging environment with pycharm and an Anki profile with the bazelfixes and it seems to start anki up fine. I want to append an extra dropdown menu on the main menu toolbar in Anki so that I can connect the actions to my functions.

I went through the hooks and the toolbar hook worked but it is not exactly what I was going for because it adds to the toolbar, not the menu. I want to add a new dropdown into the actual main menu next to tools, help, etc. connect them to functions I have made. Kind of like this

I have looked at others and sometimes they work partially but it's like a fragmented puzzle some use qmainwindow and it makes a popup separate from anki when I run it, or other approaches where they use the aqt.mw.form() functions in various ways but when I do it it will be like "nonetype doesn't take .form function." or form is not an expected argument. I want to figure out the first basic step.
I have also looked at the aqt MW thing but I am kind of confused about how it works so I am not sure if that is a better approach to read up on. The whole class>def variable> mw.append type of structure I have been seeing in other's code is a little confusing for me. Or am I going about it the completely wrong way and should use html/CSS? Any help or advice is greatly appreciated!

Also here is the bazelfixes code I have been using on pycharm.

try:
   import bazelfixes

   bazelfixes.fix_pywin32_in_bazel()
   bazelfixes.fix_extraneous_path_in_bazel()
   bazelfixes.fix_run_on_macos()
except ImportError:
   pass

if not os.environ.get(“ANKI_IMPORT_ONLY”):
   aqt.run()

TL;DR How do I, within this code on pycharm append an extra dropdown item on the main menu bar. Is there a hook I am missing (not the init toolbar one)? Or a different approach I should try?


问:
How to Pass Data from fragment B to Fragment A using Callback Listener
I tried to pass data from fragment B to Fragment A but it did'nt work.

I need to pass some data from fragment B to fragment A using Callback listener in android Studio(Java)


问:
UPSERT: duplicate key value violates unique constraint
I want to increment search counter when user searches a word.

```<code>create table public."SearchLog" (
  id integer primary key not null default nextval('"SearchLog_id_seq"'::regclass),
  search character varying(192),
  replacement character varying(192),
  qty integer,
  visible boolean,
  created_at timestamp(3) without time zone default CURRENT_TIMESTAMP(3),
  updated_at timestamp(3) without time zone default CURRENT_TIMESTAMP(3)
);
</code>```

when i run the code

```<code>insert into "SearchLog" (search)
values ('test')
on conflict(search) do update set qty        = excluded.qty + 1,
                                  updated_at = current_timestamp(3);
</code>```

i get this error:

```<code>[23505] ERROR: duplicate key value violates unique constraint "SearchLog_pkey"
</code>```

why "on coflict" doesn't trigger? how it can violates pkey if i even didn't provided it?

Body:
I want to increment search counter when user searches a word.

create table public."SearchLog" (
  id integer primary key not null default nextval('"SearchLog_id_seq"'::regclass),
  search character varying(192),
  replacement character varying(192),
  qty integer,
  visible boolean,
  created_at timestamp(3) without time zone default CURRENT_TIMESTAMP(3),
  updated_at timestamp(3) without time zone default CURRENT_TIMESTAMP(3)
);

when i run the code

insert into "SearchLog" (search)
values ('test')
on conflict(search) do update set qty        = excluded.qty + 1,
                                  updated_at = current_timestamp(3);

i get this error:

[23505] ERROR: duplicate key value violates unique constraint "SearchLog_pkey"

why "on coflict" doesn't trigger? how it can violates pkey if i even didn't provided it?


问:
pyplot default marker size for circle in terms of coordinates
I plot something in Python like this:

```<code>import matplotlib.pyplot as plt
import numpy as np

plt.figure()
x = [1,2,3,4,5,6]
y = [2,4,6,8,10,12]
plt.plot(x,y,'o-')

r = 0.25 # this should be the radius of the marker
x2 = np.array(x)
y2 = np.array(y)-r
plt.plot(x2,y2,'-')
plt.show()
</code>```

and I get this plot:

now I want that line2 is always "one radius of the marker" under line1, so that line2 and the marker of line1 are just touching. The problem is that I can eyeball the radius for one scale but if the scale of the y axis changes, the radius of the marker "in terms of coordinates" changes as well. I know that I can use markersize to change the size of the marker. But a markersize of i.e. 6 does not correspond to 6 units on the y axis. So, I'm looking for a way to express the markersize in terms of units on the y axis.

Body:
I plot something in Python like this:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
x = [1,2,3,4,5,6]
y = [2,4,6,8,10,12]
plt.plot(x,y,'o-')

r = 0.25 # this should be the radius of the marker
x2 = np.array(x)
y2 = np.array(y)-r
plt.plot(x2,y2,'-')
plt.show()

and I get this plot:

now I want that line2 is always "one radius of the marker" under line1, so that line2 and the marker of line1 are just touching. The problem is that I can eyeball the radius for one scale but if the scale of the y axis changes, the radius of the marker "in terms of coordinates" changes as well. I know that I can use markersize to change the size of the marker. But a markersize of i.e. 6 does not correspond to 6 units on the y axis. So, I'm looking for a way to express the markersize in terms of units on the y axis.


问:
NextAuth works in local but not in production with Vercel deployment?
Most of the answers I look at on Stackoverflow mentioned checking the correct config variables like:

GOOGLE_CLIENT_ID

GOOGLE_CLIENT_SECRET

NEXTAUTH_URL

I made sure that all the values are correct. Same code works perfectly in local, but in production I keep getting callback error.

I also made sure that I used the right callback uri's in Google Console with my domain.

Please find the below screenshots of Vercel Console and Google API Console. What else am I missing here?

enter image description here


问:
next-redux-wrapper wrapper.getServerSlideProps error
On my index.tsx page where i shoud get tracks from server:
`

```<code>export const getServerSideProps = wrapper.getServerSideProps(async ({store}) => {
    const dispatch = store.dispatch as NextThunkDispatch
    await dispatch(await fetchTracks())
})
</code>```

`
Problem

This is Store, also with errors
`

```<code>import {Context, createWrapper, MakeStore} from "next-redux-wrapper";
import {AnyAction, applyMiddleware, createStore} from "redux";
import {reducer, RootState} from "./reducers";
import thunk, {ThunkDispatch} from "redux-thunk";

// create a makeStore function
const makeStore: MakeStore<RootState>
    = (context: Context) => createStore(reducer, applyMiddleware(thunk));

// export an assembled wrapper
export const wrapper = createWrapper<RootState>(makeStore, {debug: true});

export type NextThunkDispatch = ThunkDispatch<RootState, any, AnyAction>
</code>```

`
Store error
I guess all this errors send me to thise files:

reducers/index.ts
`

```<code>import {combineReducers} from "redux";
import {playerReducer} from "./playerReducer";
import {HYDRATE} from "next-redux-wrapper";
import {trackReducer} from "./trackReducer";

const rootReducer = combineReducers({
    player: playerReducer,
    track: trackReducer
})

export const reducer = (state:any, action:any) => {
    if (action.type === HYDRATE) {
        const nextState = {
            ...state, // use previous state
            ...action.payload, // apply delta from hydration
        };
        if (state.count) nextState.count = state.count; // preserve count value on client side navigation
        return nextState;
    } else {
        return rootReducer(state, action);
    }
};

export type RootState = ReturnType<typeof rootReducer>
</code>```

reducers/playerReducer.ts

```<code>import {PlayerAction, PlayerActionTypes, PlayerState} from "../../types/player";

const initialState: PlayerState = {
    currentTime: 0,
    duration: 0,
    active: null,
    volume: 30,
    pause: true
}

export const playerReducer = (state = initialState, action: PlayerAction): PlayerState => {
    switch (action.type) {
        case PlayerActionTypes.PAUSE:
            return {...state, pause:true}
        case PlayerActionTypes.PLAY:
            return {...state, pause:false}
        case PlayerActionTypes.SET_CURRENT_TIME:
            return {...state, currentTime: action.payload}
        case PlayerActionTypes.SET_VOLUME:
            return {...state, volume: action.payload}
        case PlayerActionTypes.SET_DURATION:
            return {...state, duration: action.payload}
        case PlayerActionTypes.SET_ACTIVE:
            return {...state, active: action.payload, duration: 0, currentTime: 0}
        default:
            return state

    }
}
</code>```

reducers/trackReducer.ts

```<code>import {TrackAction, TrackActionTypes, TrackState} from "../../types/track";

const initialState: TrackState = {
    tracks: [],
    error: ''
}

export const trackReducer = (state = initialState, action: TrackAction): TrackState => {
    switch (action.type) {
        case TrackActionTypes.FETCH_TRACKS_ERROR:
            return {...state, error: action.payload}
        case TrackActionTypes.FETCH_TRACKS:
            return {error: '', tracks: action.payload}
        default:
            return state
    }
}
</code>```

`
Also console error:
enter image description here

I don't understant a problem, something wrong with types, in result i should get tracks from server

Body:
On my index.tsx page where i shoud get tracks from server:
`

export const getServerSideProps = wrapper.getServerSideProps(async ({store}) => {
    const dispatch = store.dispatch as NextThunkDispatch
    await dispatch(await fetchTracks())
})

`
Problem

This is Store, also with errors
`

import {Context, createWrapper, MakeStore} from "next-redux-wrapper";
import {AnyAction, applyMiddleware, createStore} from "redux";
import {reducer, RootState} from "./reducers";
import thunk, {ThunkDispatch} from "redux-thunk";

// create a makeStore function
const makeStore: MakeStore<RootState>
    = (context: Context) => createStore(reducer, applyMiddleware(thunk));

// export an assembled wrapper
export const wrapper = createWrapper<RootState>(makeStore, {debug: true});

export type NextThunkDispatch = ThunkDispatch<RootState, any, AnyAction>

`
Store error
I guess all this errors send me to thise files:

reducers/index.ts
`

import {combineReducers} from "redux";
import {playerReducer} from "./playerReducer";
import {HYDRATE} from "next-redux-wrapper";
import {trackReducer} from "./trackReducer";

const rootReducer = combineReducers({
    player: playerReducer,
    track: trackReducer
})

export const reducer = (state:any, action:any) => {
    if (action.type === HYDRATE) {
        const nextState = {
            ...state, // use previous state
            ...action.payload, // apply delta from hydration
        };
        if (state.count) nextState.count = state.count; // preserve count value on client side navigation
        return nextState;
    } else {
        return rootReducer(state, action);
    }
};

export type RootState = ReturnType<typeof rootReducer>

reducers/playerReducer.ts

import {PlayerAction, PlayerActionTypes, PlayerState} from "../../types/player";

const initialState: PlayerState = {
    currentTime: 0,
    duration: 0,
    active: null,
    volume: 30,
    pause: true
}

export const playerReducer = (state = initialState, action: PlayerAction): PlayerState => {
    switch (action.type) {
        case PlayerActionTypes.PAUSE:
            return {...state, pause:true}
        case PlayerActionTypes.PLAY:
            return {...state, pause:false}
        case PlayerActionTypes.SET_CURRENT_TIME:
            return {...state, currentTime: action.payload}
        case PlayerActionTypes.SET_VOLUME:
            return {...state, volume: action.payload}
        case PlayerActionTypes.SET_DURATION:
            return {...state, duration: action.payload}
        case PlayerActionTypes.SET_ACTIVE:
            return {...state, active: action.payload, duration: 0, currentTime: 0}
        default:
            return state

    }
}

reducers/trackReducer.ts

import {TrackAction, TrackActionTypes, TrackState} from "../../types/track";

const initialState: TrackState = {
    tracks: [],
    error: ''
}

export const trackReducer = (state = initialState, action: TrackAction): TrackState => {
    switch (action.type) {
        case TrackActionTypes.FETCH_TRACKS_ERROR:
            return {...state, error: action.payload}
        case TrackActionTypes.FETCH_TRACKS:
            return {error: '', tracks: action.payload}
        default:
            return state
    }
}

`
Also console error:
enter image description here

I don't understant a problem, something wrong with types, in result i should get tracks from server


问:
how to jenkins pipeline set variable in sh

```<code>pipeline {
    agent any
    stages {
        stage('a') {
            steps {
                    sh """
                    #!/bin/bash
                    a="test"
                    """
            }
        }
        stage('b') {
            steps {
                sh """
                #!/bin/bash
                echo ${a} => this result is stage 'a' in variable(test)
                ""
            }
        }
    }
}
</code>```

HI, I want to use stage 'a' steps sh variable in stage 'b' steps

But, I don't want to use readFile function

Please tell me how to configuration jenkins pipeline

Thank you.

Body:
pipeline {
    agent any
    stages {
        stage('a') {
            steps {
                    sh """
                    #!/bin/bash
                    a="test"
                    """
            }
        }
        stage('b') {
            steps {
                sh """
                #!/bin/bash
                echo ${a} => this result is stage 'a' in variable(test)
                ""
            }
        }
    }
}

HI, I want to use stage 'a' steps sh variable in stage 'b' steps

But, I don't want to use readFile function

Please tell me how to configuration jenkins pipeline

Thank you.


问:
Sequelize Throwing Error "Foreign Key for User is missing on Friends"
So I m trying to make a chat application with node js and Sequelize. I m trying to do the association, relationship between user and friend which was working but the moment I created message, friendMessage, and then tried to make the Many to Many relationships between friends and Messages and then it threw error.

This is the User table

```<code>``import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  HasMany,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import Friends from "../models/friends";
interface UserAttrs {
  id?: number;
  name: string;
  email: string;
  password: string;
}

@Table({
  timestamps: true,
})
class User extends Model<UserAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @AllowNull(false)
  @Column(DataType.STRING)
  name: string;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @AllowNull(false)
  @Column(DataType.STRING)
  password: string;

  @HasMany(() => Friends)
  friends: Friends[];
}

export default User;
</code>```

This is the Friends table

```<code>import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  ForeignKey,
  BelongsTo,
  BelongsToMany,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import User from "../models/user";
import Message from "./message";
import FriendMessage from "./friendMessage";
interface FriendsAttrs {
  id?: number;
  email: string;
  userId: number;
}

@Table({
  timestamps: true,
})
class Friends extends Model<FriendsAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @ForeignKey(() => User)
  @Column(DataType.INTEGER)
  userId: number;

  @BelongsTo(() => User, { foreignKey: "userId" })
  user: User;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @BelongsToMany(() => Message, () => FriendMessage)
  messages: Message[];

}

export default Friends;
</code>```

This is the Message Table

```<code>import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  DataType,
  BelongsToMany,
} from "sequelize-typescript";
import FriendMessage from "./friendMessage";
import Friends from "./friends";
interface MessageAttrs {
  id?: number;
  message: string;
}

@Table({
  timestamps: true,
})
class Message extends Model<MessageAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @Column(DataType.STRING)
  message: string;

  @BelongsToMany(() => Friends, () => FriendMessage)
  friends: Friends[];

}

export default Message;
</code>```

Then at last this is the friend Message table

```<code>import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  ForeignKey,
  BelongsTo,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import Friends from "./friends";
import Message from "./message";

interface FriendMessageAttrs {
  id?: number;
  friendsId: number;
  messageId: number;
}

@Table({
  timestamps: true,
})
class FriendMessage extends Model<FriendMessageAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @ForeignKey(() => Friends)
  @Column(DataType.INTEGER)
  friendId: number;

  @ForeignKey(() => Message)
  @Column(DataType.INTEGER)
  messageId: number;

  @ForeignKey(() => Friends)
  @Column(DataType.INTEGER)
  userId: number;

}

export default FriendMessage;
</code>```

It only works if I remove HasMany(() => Friends) from the User table, I m not sure what is the problem maybe the problem is with FriendMessage. But I m not 100% sure

Body:
So I m trying to make a chat application with node js and Sequelize. I m trying to do the association, relationship between user and friend which was working but the moment I created message, friendMessage, and then tried to make the Many to Many relationships between friends and Messages and then it threw error.

This is the User table

``import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  HasMany,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import Friends from "../models/friends";
interface UserAttrs {
  id?: number;
  name: string;
  email: string;
  password: string;
}

@Table({
  timestamps: true,
})
class User extends Model<UserAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @AllowNull(false)
  @Column(DataType.STRING)
  name: string;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @AllowNull(false)
  @Column(DataType.STRING)
  password: string;

  @HasMany(() => Friends)
  friends: Friends[];
}

export default User;

This is the Friends table

import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  ForeignKey,
  BelongsTo,
  BelongsToMany,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import User from "../models/user";
import Message from "./message";
import FriendMessage from "./friendMessage";
interface FriendsAttrs {
  id?: number;
  email: string;
  userId: number;
}

@Table({
  timestamps: true,
})
class Friends extends Model<FriendsAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @ForeignKey(() => User)
  @Column(DataType.INTEGER)
  userId: number;

  @BelongsTo(() => User, { foreignKey: "userId" })
  user: User;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @BelongsToMany(() => Message, () => FriendMessage)
  messages: Message[];

}

export default Friends;

This is the Message Table

import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  DataType,
  BelongsToMany,
} from "sequelize-typescript";
import FriendMessage from "./friendMessage";
import Friends from "./friends";
interface MessageAttrs {
  id?: number;
  message: string;
}

@Table({
  timestamps: true,
})
class Message extends Model<MessageAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @Column(DataType.STRING)
  message: string;

  @BelongsToMany(() => Friends, () => FriendMessage)
  friends: Friends[];

}

export default Message;

Then at last this is the friend Message table

import {
  Table,
  Column,
  Model,
  AutoIncrement,
  PrimaryKey,
  ForeignKey,
  BelongsTo,
  AllowNull,
  DataType,
} from "sequelize-typescript";
import Friends from "./friends";
import Message from "./message";

interface FriendMessageAttrs {
  id?: number;
  friendsId: number;
  messageId: number;
}

@Table({
  timestamps: true,
})
class FriendMessage extends Model<FriendMessageAttrs> {
  @AutoIncrement
  @PrimaryKey
  @Column(DataType.INTEGER)
  id?: number;

  @AllowNull(false)
  @Column(DataType.STRING)
  email: string;

  @ForeignKey(() => Friends)
  @Column(DataType.INTEGER)
  friendId: number;

  @ForeignKey(() => Message)
  @Column(DataType.INTEGER)
  messageId: number;

  @ForeignKey(() => Friends)
  @Column(DataType.INTEGER)
  userId: number;

}

export default FriendMessage;

It only works if I remove HasMany(() => Friends) from the User table, I m not sure what is the problem maybe the problem is with FriendMessage. But I m not 100% sure


问:
Hybridauth sign in with apple requirements
I'm implementing some providers with Hybridauth and was taking a look at Apple. Do I need a paid Apple developer membership to use it for website sign-in?</p>


问:
Delivery plans and custom link types on xml process
We use Azure DevOps server 2022 with old xml collection with some custom defined types.

We have some custom work items links types.

Is it possible to custumize Delivery plans to show whem? Documentation says that  "Predecessor-Successor link type or other custom dependency link type" can be used, but I can see only Parent/Child and Predecessor/Successor links.

Links types definition looks like:

<LinkType ReferenceName="Custom.Roadmap" ForwardName="Roadmap Child" ReverseName="Roadmap Parent" Topology="Tree" />

<LinkType ReferenceName="Custom.ReleaseInclude" ForwardName="Release Include" ReverseName="Release Included In" Topology="Dependency" />

I'm expecting to see them on Delivery plans

But I only can see parent/Child and Predcessor/successor links


问:
PyQt6 program crashes when using two TreeView delegates
I've prepared a minimal reproducible example of this problem. There are two TreeView delegates: one for checkboxes and one for progress bars. If I add any one of these delegates, but not the other one, the program doesn't crash. But if I add both, it crashes (upon trying to show the rows and the delegates). It gives the Segmentation Fault error when crashing.

delegates.py

```<code>from PySide6 import QtWidgets
from PySide6.QtCore import Qt, QEvent, QPoint, QRect
from PySide6 import QtCore, QtGui

class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
    """
    A delegate that places a fully functioning QCheckBox cell of the column to which it's applied.
    """
    def __init__(self, parent = None):
        QtWidgets.QStyledItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        """
        Important, otherwise an editor is created if the user clicks in this cell.
        """
        return None

    def paint(self, painter, option, index):
        checked = bool(index.model().data(index, Qt.DisplayRole))
        check_box_style_option = QtWidgets.QStyleOptionButton()
        if (index.flags() & Qt.ItemIsEditable):
            check_box_style_option.state |= QtWidgets.QStyle.State_Enabled
        else:
            check_box_style_option.state |= QtWidgets.QStyle.State_ReadOnly
        if checked:
            check_box_style_option.state |= QtWidgets.QStyle.State_On
        else:
            check_box_style_option.state |= QtWidgets.QStyle.State_Off
        check_box_style_option.rect = self.getCheckBoxRect(option)
        QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_CheckBox, check_box_style_option, painter)

    def editorEvent(self, event, model, option, index):
        if not (index.flags() & Qt.ItemIsEditable):
            return False
        # Do not change the checkbox-state
        if event.type() == QEvent.MouseButtonRelease or event.type() == QEvent.MouseButtonDblClick:
            if event.button() != Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()):
                return False
            if event.type() == QEvent.MouseButtonDblClick:
                return True
        elif event.type() == QEvent.KeyPress:
            if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select:
                return False
        else:
            return False
        # Change the checkbox-state
        self.setModelData(None, model, index)
        return True

    def getCheckBoxRect(self, option):
        check_box_style_option = QtWidgets.QStyleOptionButton()
        check_box_rect = QtWidgets.QApplication.style().subElementRect(QtWidgets.QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
        check_box_point = QPoint (option.rect.x() +
                                option.rect.width() / 2 -
                                check_box_rect.width() / 2,
                                option.rect.y() +
                                option.rect.height() / 2 -
                                check_box_rect.height() / 2)
        return QRect(check_box_point, check_box_rect.size())

    def setModelData (self, editor, model, index):
        newValue = not bool(index.model().data(index, Qt.DisplayRole))
        model.setData(index, newValue, Qt.EditRole)

class ProgressBarDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None):
            super().__init__(parent)

    def paint(self, painter, option, index):
        # Get the data for the item
        progress = index.data(QtCore.Qt.ItemDataRole.UserRole)

        # Draw the progress bar
        painter.save()
        rect = option.rect
        rect.setWidth(int(rect.width() * progress))
        painter.fillRect(rect, QtGui.QColor("#00c0ff"))
        painter.restore()

</code>```

mainwindow.py

```<code>from ui_form import Ui_MainWindow
from PySide6.QtCore import QThread, SIGNAL, Slot
from PySide6 import QtGui, QtCore
from PySide6.QtWidgets import QApplication, QMainWindow

from delegates import CheckBoxDelegate, ProgressBarDelegate

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.row_data = []
        self.model = QtGui.QStandardItemModel()
        self.ui.actionExit.triggered.connect(self.exit)

    def reinit_model(self):
        self.model.clear()
        self.rootItem = self.model.invisibleRootItem()
        self.model.setHorizontalHeaderLabels(['Checkbox', 'Title', 'Progress'])
        self.ui.treeView.setModel(self.model)

    def get_row_data(self):
        row_data = []
        for i in range(3):
            title = f"Col 1 Row {i}"
            row_data.append([title])
        return row_data

    def reset_row_data(self):
        self.row_data.clear()
        self.row_data = self.get_row_data()

    class Show_list(QThread):
        def __init__(self, AppWindow):
            QThread.__init__(self)
            self.AppWindow = AppWindow

        def run(self):
            self.AppWindow.reset_row_data()

    def populate_window_list(self):
        self.reinit_model()
        for title_link in self.row_data:
            item = [QtGui.QStandardItem(),
                    QtGui.QStandardItem(title_link[0]),
                    QtGui.QStandardItem()]
            progress = 0.5
            item[2].setData(progress, QtCore.Qt.ItemDataRole.UserRole)
            self.rootItem.appendRow(item)
        self.ui.treeView.show()
        cb_delegate = CheckBoxDelegate()
        pb_delegate = ProgressBarDelegate()
        self.ui.treeView.setItemDelegateForColumn(0, cb_delegate)
        # self.ui.treeView.setItemDelegateForColumn(2, pb_delegate)
        for i in range(3):
            self.ui.treeView.resizeColumnToContents(i)

    @Slot()
    def show_list(self):
        self.thread = self.Show_list(self)
        self.connect(self.thread, SIGNAL("finished()"),
                     self.populate_window_list)
        self.thread.start()

    def exit(self):
        QApplication.quit()

</code>```

main.py

```<code>import sys
from mainwindow import MainWindow
from PySide6.QtWidgets import QApplication

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = MainWindow()
    widget.reinit_model()
    getRowDataButton = widget.ui.getRowDataButton
    getRowDataButton.clicked.connect(widget.show_list)
    widget.show()
    sys.exit(app.exec())

</code>```

Here's also ui_form.py.

I've tried to add cb_delegate.deleteLater() and pb_delegate.deleteLater(), but it didn't help. The program loaded the list and crashed immediately.

Body:
I've prepared a minimal reproducible example of this problem. There are two TreeView delegates: one for checkboxes and one for progress bars. If I add any one of these delegates, but not the other one, the program doesn't crash. But if I add both, it crashes (upon trying to show the rows and the delegates). It gives the Segmentation Fault error when crashing.

delegates.py

from PySide6 import QtWidgets
from PySide6.QtCore import Qt, QEvent, QPoint, QRect
from PySide6 import QtCore, QtGui

class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
    """
    A delegate that places a fully functioning QCheckBox cell of the column to which it's applied.
    """
    def __init__(self, parent = None):
        QtWidgets.QStyledItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        """
        Important, otherwise an editor is created if the user clicks in this cell.
        """
        return None

    def paint(self, painter, option, index):
        checked = bool(index.model().data(index, Qt.DisplayRole))
        check_box_style_option = QtWidgets.QStyleOptionButton()
        if (index.flags() & Qt.ItemIsEditable):
            check_box_style_option.state |= QtWidgets.QStyle.State_Enabled
        else:
            check_box_style_option.state |= QtWidgets.QStyle.State_ReadOnly
        if checked:
            check_box_style_option.state |= QtWidgets.QStyle.State_On
        else:
            check_box_style_option.state |= QtWidgets.QStyle.State_Off
        check_box_style_option.rect = self.getCheckBoxRect(option)
        QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_CheckBox, check_box_style_option, painter)

    def editorEvent(self, event, model, option, index):
        if not (index.flags() & Qt.ItemIsEditable):
            return False
        # Do not change the checkbox-state
        if event.type() == QEvent.MouseButtonRelease or event.type() == QEvent.MouseButtonDblClick:
            if event.button() != Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()):
                return False
            if event.type() == QEvent.MouseButtonDblClick:
                return True
        elif event.type() == QEvent.KeyPress:
            if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select:
                return False
        else:
            return False
        # Change the checkbox-state
        self.setModelData(None, model, index)
        return True

    def getCheckBoxRect(self, option):
        check_box_style_option = QtWidgets.QStyleOptionButton()
        check_box_rect = QtWidgets.QApplication.style().subElementRect(QtWidgets.QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
        check_box_point = QPoint (option.rect.x() +
                                option.rect.width() / 2 -
                                check_box_rect.width() / 2,
                                option.rect.y() +
                                option.rect.height() / 2 -
                                check_box_rect.height() / 2)
        return QRect(check_box_point, check_box_rect.size())

    def setModelData (self, editor, model, index):
        newValue = not bool(index.model().data(index, Qt.DisplayRole))
        model.setData(index, newValue, Qt.EditRole)

class ProgressBarDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None):
            super().__init__(parent)

    def paint(self, painter, option, index):
        # Get the data for the item
        progress = index.data(QtCore.Qt.ItemDataRole.UserRole)

        # Draw the progress bar
        painter.save()
        rect = option.rect
        rect.setWidth(int(rect.width() * progress))
        painter.fillRect(rect, QtGui.QColor("#00c0ff"))
        painter.restore()

mainwindow.py

from ui_form import Ui_MainWindow
from PySide6.QtCore import QThread, SIGNAL, Slot
from PySide6 import QtGui, QtCore
from PySide6.QtWidgets import QApplication, QMainWindow

from delegates import CheckBoxDelegate, ProgressBarDelegate

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.row_data = []
        self.model = QtGui.QStandardItemModel()
        self.ui.actionExit.triggered.connect(self.exit)

    def reinit_model(self):
        self.model.clear()
        self.rootItem = self.model.invisibleRootItem()
        self.model.setHorizontalHeaderLabels(['Checkbox', 'Title', 'Progress'])
        self.ui.treeView.setModel(self.model)

    def get_row_data(self):
        row_data = []
        for i in range(3):
            title = f"Col 1 Row {i}"
            row_data.append([title])
        return row_data

    def reset_row_data(self):
        self.row_data.clear()
        self.row_data = self.get_row_data()

    class Show_list(QThread):
        def __init__(self, AppWindow):
            QThread.__init__(self)
            self.AppWindow = AppWindow

        def run(self):
            self.AppWindow.reset_row_data()

    def populate_window_list(self):
        self.reinit_model()
        for title_link in self.row_data:
            item = [QtGui.QStandardItem(),
                    QtGui.QStandardItem(title_link[0]),
                    QtGui.QStandardItem()]
            progress = 0.5
            item[2].setData(progress, QtCore.Qt.ItemDataRole.UserRole)
            self.rootItem.appendRow(item)
        self.ui.treeView.show()
        cb_delegate = CheckBoxDelegate()
        pb_delegate = ProgressBarDelegate()
        self.ui.treeView.setItemDelegateForColumn(0, cb_delegate)
        # self.ui.treeView.setItemDelegateForColumn(2, pb_delegate)
        for i in range(3):
            self.ui.treeView.resizeColumnToContents(i)

    @Slot()
    def show_list(self):
        self.thread = self.Show_list(self)
        self.connect(self.thread, SIGNAL("finished()"),
                     self.populate_window_list)
        self.thread.start()

    def exit(self):
        QApplication.quit()

main.py

import sys
from mainwindow import MainWindow
from PySide6.QtWidgets import QApplication

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = MainWindow()
    widget.reinit_model()
    getRowDataButton = widget.ui.getRowDataButton
    getRowDataButton.clicked.connect(widget.show_list)
    widget.show()
    sys.exit(app.exec())

Here's also ui_form.py.

I've tried to add cb_delegate.deleteLater() and pb_delegate.deleteLater(), but it didn't help. The program loaded the list and crashed immediately.