How to draw rectangle on canvas in correct position after window resizing?

I’m making a webpage which streams user’s camera output and detects faces on the video. The canvas and the video seem to resize properly. However, after resizing, the rectangles around detected faces keep being drawn in the same position as before resizing. The code below is for initializing the video and canvas.

    let videoX = 0.95*window.innerWidth;
    let videoY = 0.75*videoX;
    let canvas = document.getElementById("canvas");
    let ctx = canvas.getContext("2d", { 
    willReadFrequently: true });

The code below is for the detection and the drawing of rectangles around faces.

   const detectFaces = async () => {
   var prediction = await model.estimateFaces(video, false);

 // Using canvas to draw the video first

 ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

prediction.forEach((predictions) => {

// Drawing rectangle that'll detect the face
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "yellow";
ctx.rect(
  predictions.topLeft[0],
  predictions.topLeft[1],
  (predictions.bottomRight[0] - predictions.topLeft[0]),
  (predictions.bottomRight[1] - predictions.topLeft[1])
);

I have a resize method to handle window resizing

  const resize = () => {
  videoX = 0.95*window.innerWidth;
  videoY = 0.75*videoX;
  canvas.width = videoX;
  canvas.height = videoY;
  video.setAttribute('height', videoX);
  video.setAttribute('width', videoY);
  ctx = canvas.getContext("2d", { willReadFrequently: 
  true });
  };

Please let me know if you have any idea how to solve this!

minimax algorithm tic tac toedoes not draw the response of the ai

I’m trying to make an AI that looks for the best possible position to win the game using the minimax algorithm, but I don’t know what I’m doing wrong so that the AI move isn’t drawn

The code is separated into 3 functions, one when the player clicks and draws the x where he wants to then change it so that it is the turn of the AI, to then call bestScore that looks for which would be the best playing, calculating it from the minimax function

const boardAa = document.getElementById('board');
const cells = document.querySelectorAll('.cell');
const humanPlayer = "X";
const iaPlayer = "O";
let currentPlayer = humanPlayer;
const board = []


cells.forEach(cell => {
    cell.addEventListener('click', handleCellClick);
});


function handleCellClick(){
    if(this.textContent === "" && currentPlayer == humanPlayer){
        this.textContent = currentPlayer;
        board.push(Number(this.dataset.posicion));
        getBestMove();
    }
    
    console.log(board)
}


function getBestMove(){
    let bestScore = -Infinity;
    let bestMove;
    
    for(let i = 0; i < board.length ; i++){
        if(board[i] == ""){
            board[i] = iaPlayer;
            let score = minimax(board , 0 , false);
            board[i]= "";
           
        }
        if(score > bestScore){
            bestScore = score;
            bestMove = i;
        }
    }
    board[bestMove] = bestScore;

    return bestScore;

}


function minimax(board , depth , maximing){
    
    if(maximing){
        let bestScore = -Infinity;
        for(let i = 0; i < board.length; i++){
            if(board[i] === ""){
                board[i] = iaPlayer;
                let score = minmax(board, depth +1 , false);
                board[i]= "";
                bestScore = Math.max(score, bestScore);
            }
        }
        return bestScore
    }else{
        let bestScore = Infinity;
        for(let i = 0; i < board.length; i++){
        if(board[i] === ""){
        board[i] = currentPlayer;
        let score = minmax(board, depth +1, true);
        board[i] = "";
        bestScore = Math.min(bestScore, score);
      }
    }
    return bestScore;
    }
}


I’ve tried everything, but I don’t know what I’m doing wrong so that the ia play isn’t drawn
I even asked chatgpt but he can’t tell me where the code error is

Creating a canvas animation that covers the entire viewport without triggering overflow without using position: absolute

I want to make an HTML canvas animation that will span the entire viewport that does not cause horizontal overflow, but I do not want to use position: absolute because ideally, I would want to just be able to treat it like any other element and retain natural flow in my HTML.

The tricky part about using is that CSS width and height just scales it without changing the internal width / height. Also, trying to change it with Javascript by using document.body.clientWidth / clientHeight, window.innerWidth / innerHeight, or canvas.parentElement.getBoundingClientRect().width / height all do not work because they do not account for the vertical scrollbar (for the rest of the page).

By this I mean that on my 1920×1080 monitor, the width will be set to 1920 even though my viewport width is only 1903 (17px from scrollbar), causing horizontal overflow. The strange behavior about this is that when I use devtools to check the width of the canvas’s parent element’s height, it says 1903. So I would think that saying set the canvas's width to the parent's width (1903) would set it to 1903, but it instead sets it to 1920. And, I do not want to just subtract 17 from that width because that is not reliable across all browsers.

See this code for an example:

<html>
    <body>
        <canvas class="splash-canvas" />
        <!-- rest of site -->
    </body>
</html>
html, body
{
    width: 100%;
    height: 100%;
}

.splash-canvas
{
    background-color: #090909;
}
const canvas: HTMLCanvasElement = document.querySelector(".splash-canvas");

canvas.width = canvas.parentElement.getBoundingClientRect().width;
// devTools says body's width is 1903, but this function returns 1920
// since no(?) methods return the viewport size excluding the amount covered by the scrollbar

canvas.height = canvas.parentElement.getBoundingClientRect().height;

// canvas's width and height is now 1920x929 (for me)

I think using position: absolute might just be necessary here, but I really think there should be a better solution here. Either way, I appreciate any help, thank you!

Contact Form on website not working (Vercel and Sendgrid)

I have a website hosted on Vercel and am trying to use Sendgrid to send emails from my contact form on the site to my gmail address. I keep getting a 405 error. From what I gather, Vercel recommends using a 3rd party to send emails, that is why I’m trying to work with sendgrid. This code was an example from Twilio but I’m not using Twilio, so I tried to edit it to be a regular JS function.

I’ve tried editing the code, but nothing seems to work. Here is my HTML code on my contact page with JS script. I’ve listed the function below that is called in the onsubmit attribute

<script>
  import sendMail from 'send-mail.js'
  const form = document.getElementById("contact-form");
const fromInput = document.getElementById("from");
const subjectInput = document.getElementById("subject");
const contentInput = document.getElementById("content");
const sendButton = document.getElementById("submit-button");
const status = document.getElementById("status");

function setStatus(message, class) {
  status.textContent = message;
  status.classList.add(class);
  status.removeAttribute("hidden");
}
function hideStatus() {
  status.setAttribute("hidden", "hidden");
  status.className = "status";
  status.textContent = "";
}
  // Listen for the submit event of the form and handle it
form.addEventListener("submit", async (event) => {
// Stop the form from actually submitting
event.preventDefault();
// Disable the submit button to avoid double submissions
sendButton.setAttribute("disabled", "disabled");
// Hide any status message as we are now dealing with a new submission
hideStatus();
try {
  // Submit the data to our function, using the action and method from the form element itself.
  const response = await fetch(form.getAttribute("action"), {
    method: form.getAttribute("method"),
    // Collect the data from the form inputs and serialize the data as JSON
    body: JSON.stringify({
      from: fromInput.value,
      subject: subjectInput.value,
      content: contentInput.value,
    }),
    // Set the content type of our request to application/json so the function knows how to parse the data
    headers: {
      "Content-Type": "application/json",
    },
  });
  if (response.ok) {
    // If the response was a success, clear the form inputs and set a success message in the status
    fromInput.value = "";
    subjectInput.value = "";
    contentInput.value = "";
    setStatus("Message sent successfully. Thank you!", "success");
    // After 5 seconds, hide the success message.
    setTimeout(hideStatus, 5000);
  } else {
    // If the request returns an error response, read the error message from the response and set it as a failure message in the status
    const data = await response.json();
    console.log(data);
    setStatus(data.error, "error");
  }
  // The request is over, so enable the submit button again
  sendButton.removeAttribute("disabled");
} catch (error) {
  // If the request failed, set a generic error message in the status
  setStatus(
    "There was an error and the message could not be sent. Sorry.",
    "error"
  );
  console.log(error);
  // The request is over, so enable the submit button again
  sendButton.removeAttribute("disabled");
}
});

</script>
const sg = require("@sendgrid/mail");

export const sendMail = async function(context, event, callback) {
  sg.setApiKey(context.SENDGRID_API_KEY);
  const msg = {
    to: "******MY EMAIL WAS HERE******",
    from: { email: context.FROM_EMAIL_ADDRESS, name: "Your contact form" },
    replyTo: event.from,
    subject: `[contactform] ${event.subject}`,
    text: `New email from ${event.from}.nn${event.content}`,
  };
  try {
    await sg.send(msg);
    response.setStatusCode(200);
    response.setBody({ success: true });
    return callback(null, response);
  } catch (error) {
    console.error(error);
    let { message } = error;
    if (error.response) {
      console.error(error.response.body);
      message = error.response.body.errors[0];
    }

    response.setStatusCode(400);
    response.setBody({ success: false, error: message });
    return callback(null, errorResponse(response, message));
  }
}

Toggle Multiple Drop Down Menus with Vanilla JS

The code I currently have supports one menu. I would like to use the JS code more than once to toggle two other menus in different sections of the site. I need help to achieve this without copying the JS code 3 times. How do I do it?
<!--- https://jsfiddle.net/tn7d2hb4/ -->

Convert spreadsheet into a pdf with apps script – getting html result

I need to make a function to convert my spreadsheet into pdf file.
I followed the steps described in this website : https://xfanatical.com/blog/print-google-sheet-as-pdf-using-apps-script/

When i run the script, i have an html result instead of a .pdf as i wish.

Html result instead of .pdf file

I spent some hours to understand how its work but can’t find a solution for this.

Here is the part of code I used :

function exportAsPDF() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  var sheetId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId()
  var blob = _getAsBlob(spreadsheet.getUrl() + '#gid=' + sheetId) 
  _exportBlob(blob, spreadsheet.getName(), spreadsheet)
}
function _getAsBlob(url, sheet, range) {
  var rangeParam = ''
  var sheetParam = ''
  if (range) {
    rangeParam =
      '&r1=' + (range.getRow() - 1)
      + '&r2=' + range.getLastRow()
      + '&c1=' + (range.getColumn() - 1)
      + '&c2=' + range.getLastColumn()
  }
  spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(),
  pivotSourceDataSheetId=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId()
  if (sheet) {
    sheetParam = '&gid=' + sheet.getSheetId()
  }
  // A credit to https://gist.github.com/Spencer-Easton/78f9867a691e549c9c70
  // these parameters are reverse-engineered (not officially documented by Google)
  // they may break overtime.
  var exportUrl = url.replace(//edit.*$/, '')
      + '/export?exportFormat=pdf&format=pdf'
      + '&size=LETTER'
      + '&portrait=true'
      + '&fitw=true'       
      + '&top_margin=0.75'              
      + '&bottom_margin=0.75'          
      + '&left_margin=0.7'             
      + '&right_margin=0.7'           
      + '&sheetnames=false&printtitle=false'
      + '&pagenum=UNDEFINED' // change it to CENTER to print page numbers
      + '&gridlines=true'
      + '&fzr=FALSE'
      + sheetParam
      + rangeParam
  console.log('URL = ' + exportUrl)
  Logger.log('exportUrl=' + exportUrl)
  var response
  var i = 0
  for (; i < 5; i += 1) {
    response = UrlFetchApp.fetch(exportUrl, {
      muteHttpExceptions: true,
      headers: { 
        Authorization: 'Bearer ' +  ScriptApp.getOAuthToken(),
      },
    })
    console.log('response = ' + response)
    if (response.getResponseCode() === 429) {
      // printing too fast, retrying
      Utilities.sleep(3000)
    } else {
      console.log('test')
      break
    }
  }
  
  if (i === 5) {
    throw new Error('Printing failed. Too many sheets to print.')
  }
  
  return response.getBlob()
}

I tried to change my url variable with adding the GID after the KEY but got the same result.
I tried to change the url variable with keep off the Replace() function and changing the format but got the same result aswell.

Also, I tried to add some logs in my execution to explore some variables, I don’t know what it means but I found that my html result is in fact my “response” variable :
My “response” variable in log

I hope someone met this problem already and succeed to solve it to help me ! Thanks a lot

Pass a value from react component to scss

I have the following code in .jsx component,

<div className={type === "travellist" ? "headerContainer listmode" : "headerContainer"}>

In .scss how do I use the listmode for the class headerContainer?
For example:

.headerContainer.listmode{

            margin: 20px 0px 40px 0px;
            }
or 
    .headerContainer{

            margin: 20px 0px 100px 0px;
            }

Open CookieBot link with click event

I’m having a hard time figuring how to add a CookieBot link to a site hosted on HubSpot.

<a href="javascript: Cookiebot.renew()">Renew or change your cookie consent</a>

HubSpot strips out the link ‘javascript: Cookiebot.renew()’ for security resons, so I am testing ways to open it with JavaScript.

<script>
  var cookiebotRenewLink = document.getElementById('cookiebot-renew-link');
  cookiebotRenewLink.addEventListener('click', function(event) {
    event.preventDefault();
    var cookiebotScript = document.createElement('script');
    cookiebotScript.src = 'https://consent.cookiebot.com/uc.js';
    cookiebotScript.setAttribute('data-cbid', 'ID');
    cookiebotScript.onload = function() {
      Cookiebot.renew();
    };
    document.body.appendChild(cookiebotScript);
  });
</script>

And added this link in the Footer:

<a id="cookiebot-renew-link" href="">Change Cookie Consent</a>

but it’s not working for me.

Any ideas how I can fix that?

I also tried:

<script>
        function simulateClick() {
            // Get the anchor element
            var link = document.getElementById('cookiebot-renew-link');

            // Create a new click event
            var clickEvent = new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            });

            // Trigger the click event on the anchor element
            if (link) {
                link.dispatchEvent(clickEvent);
            }
        }
    </script>

Unable to display the spamProbabilityChart in HTML using Chart.js

I’m working on a web application that performs email analysis and displays various visualizations, including a chart to represent the spam probability. However, I’m encountering an issue where the spamProbabilityChart is not being displayed on the page.

Here’s my relevant HTML code:

     <div id="result-box-section" class="result box">
         <!-- Content exists here -->
         <h5 id="spam-probability">Spam Probability: {{ percentage }} %</h5>
         <h5>Word Count: {{ result }}</h5>
         <br />
         <h5>Emotional Analysis:</h5>
         <canvas id="emotionAnalysisChart"></canvas>
     </div>

And here’s the JavaScript code that should create and populate the chart –

analyzeEmail Function:

function analyzeEmail() {
            var email = document.getElementById("email").value;
            var analyzeBtn = document.getElementById("analyze-btn");
            // Add the loading animation class
            analyzeBtn.value = 'Loading...';
            analyzeBtn.disabled = true;
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/predict", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    var resultBoxSection = document.getElementById("result-box-section");
                    var predictionText =
                        response.prediction[0] === 1
                            ? '<span style="color: red;">Spam</span>'
                            : '<span style="color: green;">Not Spam</span>';
                    var spamProbability = response.percentage;
                    var wordCount = response.result;
                    var emoData = response.emo_data;
                    // Update the HTML content
                    resultBoxSection.innerHTML =
                        "<h5>Prediction: " +
                        predictionText +
                        "</h5>" +
                        "<h5>Spam Probability: " + spamProbability + "%</h5>" +
                        "<h5>Word Count: " + wordCount + "</h5>" +
                        "<br>" +
                        "<h5>Emotional Analysis:</h5>" +
                        "<canvas id='emoChart'></canvas>";
                    // Remove the loading animation class
                    analyzeBtn.value = 'Analyze';
                    analyzeBtn.disabled = false;
                    // Create the chart
                    createEmoChart(emoData);
                }
            };
            xhr.send(JSON.stringify({ email: email }));
        }

Graph function:

function createSpamProbabilityChart(spamProbability) {
            var ctx = document.getElementById("spamProbabilityChart").getContext("2d");
            var chart = new Chart(ctx, {
                type: "horizontalBar",
                data: {
                    labels: ["Spam Probability"],
                    datasets: [{
                        label: "Probability",
                        data: [spamProbability],
                        backgroundColor: "#21c9d4",
                        barThickness: 10,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    legend: {
                        display: false
                    },
                    scales: {
                        xAxes: [{
                            ticks: {
                                beginAtZero: true,
                                min: 0,
                                max: 100,
                                callback: function (value) {
                                    return value + "%";
                                }
                            },
                            scaleLabel: {
                                display: true,
                                labelString: "Probability",
                                fontColor: "#000",
                                fontSize: 12,
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                display: false
                            },
                            gridLines: {
                                display: false
                            }
                        }]
                    }
                }
            });
        }

emoGraph: (This is being displayed)

function createEmoChart(emoData) {
            var labels = emoData.map(function (data) {
                return data[0];
            });
            var scores = emoData.map(function (data) {
                return data[1];
            });
            // Define an array of colors for each emotion label
            var colors = ['#FF9AFF', '#CCFF99', '#FFA954', '#FF7878', '#A2CDFF', '#7DFF7D', '#5DA5A5', '#724BA3'];
            var ctx = document.getElementById("emoChart").getContext("2d");
            var chart = new Chart(ctx, {
                type: "pie",
                data: {
                    labels: labels,
                    datasets: [{
                        label: "Score",
                        data: scores,
                        backgroundColor: colors.slice(0, labels.length)
                    }]
                },
                options: {
                    responsive: true
                }
            });
        }

The createSpamProbabilityChart function is not being executed, and as a result, the chart is not displayed. I’ve verified that the analyzeEmail function is successfully invoked and the spamProbability value is available. (FYI – The other graph is being displayed)

I’ve already ensured that I have included the necessary Chart.js library in my project.

I would appreciate any insights or suggestions on why the createSpamProbabilityChart function is not being called and how to resolve this issue. Thank you!

Image:

Graph not being shown

Handling streaming response has inconsitent result across pages and browsers

I’m having issues handling StreamingResponse from FastAPI, specifically, i need to append every response from StreamingResponse into a modal (or any other HTML element) body.
However, for whatever reason – result is inconsitent.

I have an endpoint /watcher and once action that serves StreamingResponse from FastAPI endpoint is triggered by javascript below, i get the expected result and modal body is populated each time response is sent. And it’s handled on Chrome (Windows 114.0.5735.199), Firefox (Windows 114.0.2) and Firefox (Linux Fedora 107.0) just fine.

function tailLog(servername) {
        try {
            document.getElementsByClassName("modal-dialog modal-dialog-centered modal-xl")[0].classList = "modal-dialog modal-dialog-centered modal-fullscreen"
        } catch {
            // none
        }

        var last_response_len = false;

        tg = document.getElementById("wfDebugger-body")
        tg.innerHTML = "<p>Info msg.</p>"

        btnholder = document.getElementById("wfDebugger-btn-holder")
        btnholder.innerHTML = ""

        modalHeader = document.getElementById("wfDebugger-header")
        modalHeader.innerHTML = ""
        modalHeaderTitle = document.createElement("h5")
        modalHeaderTitle.setAttribute("class", "modal-title")
        modalHeaderTitle.innerHTML = "Live Log Viewer"
        modalHeader.appendChild(modalHeaderTitle)

        rholder = document.createElement("code")
        rholder.id = "responseHolder"
        rholder.style.whiteSpace = "pre"
        tg.appendChild(rholder)

        btn = document.createElement("button")
        btn.setAttribute("type", "button")
        btn.setAttribute("class", "btn btn-secondary ms-3")
        btn.setAttribute("onclick", "stopTailLog(this)")
        btn.setAttribute("data-servername", servername)
        btn.innerHTML = "Stop View"

        closebtn = document.createElement("button")
        closebtn.setAttribute("id", "wfDebugger-close-btn")
        closebtn.setAttribute("type", "button")
        closebtn.setAttribute("class", "btn btn-info ms-3")
        closebtn.setAttribute("data-bs-dismiss", "modal")
        closebtn.setAttribute("data-bs-target", "wfDebugger")
        closebtn.setAttribute("onclick", "stopTailLog(this)")
        closebtn.setAttribute("data-servername", servername)
        closebtn.innerHTML = "Close"

        modalCloseDiv = document.createElement("div")
        modalCloseDiv.setAttribute("class", "modal-title")
        modalCloseDiv.appendChild(btn)
        modalCloseDiv.appendChild(closebtn)
        modalHeader.appendChild(modalCloseDiv)

        $.ajax({
            url: "/watcher/" + servername + "?action=wildfly_getlogid",
            success: function(data) {
                btn.setAttribute("data-logid", data)
                closebtn.setAttribute("data-logid", data)
                $.ajax({
                    url: "/watcher/" + servername + "/wildfly_getlog?data=" + data,
                    method: "POST",
                    complete: function() {
                        $.ajax({ url: "/watcher/" + servername + "/wildfly_killlog?data=" + data, method: "POST" })
                    },
                    xhrFields: {
                        onprogress: function(e) {
                            var this_response, response = e.currentTarget.response;
                            if(last_response_len === false)
                            {
                                this_response = response;
                                last_response_len = response.length;
                            }
                            else
                            {
                                this_response = response.substring(last_response_len);
                                last_response_len = response.length;
                            }
                            ccontent = rholder.innerHTML
                            modalBody = document.getElementById("wfDebugger-body")
                            if (modalBody.scrollTop == (modalBody.scrollHeight - modalBody.clientHeight)) {
                                rholder.innerHTML = ccontent + "<br>n" + this_response.replaceAll("<", "&lt;")
                                modalBody.scrollTo({
                                    top: (modalBody.scrollHeight - modalBody.clientHeight),
                                    left: 0,
                                    behavior: 'instant'
                                })
                            } else {
                                rholder.innerHTML = ccontent + "<br>n" + this_response.replaceAll("<", "&lt;")
                            }
                        }
                    }
                })
            }
        })
    }

However, when i try the same on another page that calls another endpoint, with similar javascript code, i only get the response in full on Chrome (Windows 114.0.5735.199) once it’s completed, but works fine on both Firefox in Windows and Linux. I have no idea why.
This is the code that is causing issues on Chrome.

function startStopInstance(action, instanceId, instanceName, btn, refreshBtn) {
            modal = initModal()

            var last_response_len = false;

            rholder = document.createElement("code")
            rholder.id = "responseHolder"
            rholder.style.whiteSpace = "pre"
            DevOpsModalBody.appendChild(rholder)

            var title
            if (action == 'start') {
                title = `Starting instance: '${instanceName}'...`
            }
            else if (action == 'stop') {
                title = `Stopping instance: '${instanceName}'...`
            }
            else if (action == 'restart') {
                title = `Restarting instance: '${instanceName}'...`
            }
            else if (action == "increase_volume_by_") {
                title = `Increasing volume size for instance: '${instanceName}'...`
                const _size = document.getElementById(`size_${instanceId}`).value
                action = `increase_volume_by_${_size}`
            }
            const spinner = createSpinner()
            const modalSpinner = createSpinner()

            // Disable btn while request is running
            btn.disabled = true
            btn.appendChild(spinner)

            DevOpsModalTitle.textContent = title
            DevOpsModalTitle.appendChild(modalSpinner)
            DevOpsModalCloseBtn.hidden = true
            DevOpsModalSaveBtn.hidden = true
            modal.show()
            $.ajax({
                url: `/instance-action/${instanceId}/${action}`,
                method: "POST",
                complete: function() {
                    btn.disabled = false;
                    spinner.remove();
                    modalSpinner.remove();
                    DevOpsModalCloseBtn.hidden = false;
                },
                xhrFields: {
                    onprogress: function(e) {
                        console.log(e)
                        var this_response, response = e.currentTarget.response;
                        if(last_response_len === false)
                        {
                            this_response = response;
                            last_response_len = response.length;
                        }
                        else
                        {
                            this_response = response.substring(last_response_len);
                            last_response_len = response.length;
                        }
                        ccontent = rholder.innerHTML
                        rholder.innerHTML = ccontent + "<br>n" + this_response.replaceAll("<", "&lt;")
                    }
                }
            })
        }

Above you’ll see createElement and createSpinner but those functions are nothing more but a shortcut of couple of document.createElement with specific attributes to get the element i need.
xhrFields callback is changed to not check if user is already viewing last line in order to scroll, instead just appends the data – so quite simpler but still not working on Chrome.

Both endpoints have similar return statement in FastAPI:

return StreamingResponse(getwflogs(serverip, data), media_type="text/plain") # The one that works on all three browsers

return StreamingResponse(func(instance_id), media_type='text/plain') # The one that works only in firefox

async def getwflogs(serverip, logid):
    async with AsyncClient(headers=api_auth, timeout=None) as client:
        req = client.build_request("POST", f"http://{serverip}:3322/api/service/getlog/{logid}")
        r = await client.send(req, stream=True)
        if r.status_code == 200:
            async for i in r.aiter_text():
                yield i


async def func(instance_id: str, size: int):
    cfg = load_settings()
    session  = aioboto3.Session(aws_access_key_id=cfg.aws.key, aws_secret_access_key=cfg.aws.secret_key, region_name=cfg.aws.region)
    partition_number = 0

    async with session.resource('ec2') as res, session.client('ec2') as client:
        yield "Loading instance informationn"
        instance = await res.Instance(instance_id)
        async for v in instance.volumes.all():
            partition_number += 1
            yield f"Processing volume id: {v.id}. Increasing size from {await v.size} to {await v.size + size}...n"
            _res = await client.modify_volume(DryRun=False, VolumeId=v.id, Size=await v.size + size)
            if jpsearch("VolumeModification.ModificationState", _res) == 'modifying':
                _res = await client.describe_volumes_modifications(VolumeIds=[v.id])
                while not jpsearch("VolumesModifications[].ModificationState", _res) == ['completed']:
                    _res = await client.describe_volumes_modifications(VolumeIds=[v.id])
            yield f"Size of volume id: {v.id} successfully increased. Please go to server and execute:nsudo growpart /dev/nvme0n1 {partition_number}nsudo resize2fs /dev/nvme0n1p{partition_number}n"

Any idea what could be causing this behaviour.
Why Chrome gets streamingresponse in full after it’s completed entirely for 1 of two pages/endpoints but firefox works fine every time ?

Add skeleton while getting a url

I have a function to get a URL,
1.This takes a few seconds
2.In the meantime I want to show a skeleton

3.This is my function to get the data and display it

const myURL = "https://myurl/id&seg=6";
async function getUrl() {
try {
    let res = await fetch(myURL, {
        method: 'GET',
        headers: {
            'Content-type': 'application/json; charset=UTF-8'
        }
    });
    if (res.ok) {
        return await res.json();
    } else {
        return 400;
    }
} catch (error) {
}
}

//show the data from the url after getting it
async function renderResponse() {
    datalink = await getUrl();
    urlFrame = datalink.url;
    Shopify.Checkout.OrderStatus.addContentBox(
        '<object style="width:100%; height:550px; overflow: auto;" data="' + urlFrame + '"> </object>'
    );


}

renderResponse();

4.How can i insert my skeleton

<div class="container">
  <template id="card-template">
    <a class="card" id="card-link" target="_blank">
      <div class="card__header">
        <h3 class="card__header header__title" id="card-title">
          <div class="skeleton skeleton-text"></div>
          <div class="skeleton skeleton-text"></div>
          <div class="skeleton skeleton-text"></div>
        </h3>
      </div>

      <div class="card__body">
        <div class="card__body body__img">
          <img class="skeleton" alt="" id="cover-img" />
        </div>
      </div>
    </a>
  </template>
</div>

5.I was trying something like that, but it doesn’t work for me, I can’t figure out how to merge my script to get the data with the skeleton

const container = document.querySelector(".container");
const cardTemplate = document.getElementById("card-template");
container.append(cardTemplate.content.cloneNode(true));

fetch(myURL)
    .then((response) => response.json())
    .then((posts) => {
      container.innerHTML = "";
      posts.forEach((post) => {
        const div = cardTemplate.content.cloneNode(true);
        div.getElementById("card-link").href = post.link;
        div.getElementById("logo-img").src = post.logoImage;
        div.getElementById("card-title").textContent = post.title;
        div.getElementById("card-details").textContent = post.details;
        div.getElementById("cover-img").src = post.coverImage;
        container.append(div);
      });
    });

I appreciate your help.How can I solve this?

React hook function call render map

Is it possible to assign the hook return function to a render map in React? The following example includes the socialAuthMethodsMap map with the onClick parameter. I want to assign the signInWithApple function from useFirebaseAuth hook, but it breaks the essential React hook laws. Is there any alternatives?

import {FunctionComponent, MouseEventHandler} from 'react'
import { IconProps } from 'react-feather'

type TSocialAuthMethodData = {
    code: string
    logo?: string | FunctionComponent<IconProps>
    onClick: MouseEventHandler<HTMLButtonElement>
}

// const { signInWithApple } = useFirebaseAuth()

export const socialAuthMethodsMap: Array<TSocialAuthMethodData> = [
    {
        code: 'apple',
        logo: '/assets/icons/social/apple.svg',
        onClick: signInWithApple,
    },
    {
        code: 'google',
        logo: '/assets/icons/social/google.svg',
        onClick: () => null,
    },
    {
        code: 'github',
        logo: '/assets/icons/social/github.svg',
        onClick: () => null,
    },
]

Render function

<div>
            {socialAuthMethodsMap.map((socialAuthMethod) => (
                <SocialAuthButton
                    key={socialAuthMethod.code}
                    title={socialAuthMethod.code}
                    logo={socialAuthMethod.logo}
                    onClick={socialAuthMethod.onClick}
                />
            ))}
        </div>

Access to XMLHttpRequest at from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, d

Estoy intentando hacer una llamada ajax pero me salta este error: Access to XMLHttpRequest at file:///C:/xampp/htdocs/TFC/LaBiblioteca/DAO/Llamadas.php?funcion=Registrar&datosRegistro=LAM2-NDC4-31DV-LU73,sda,dasd,asd,3,,false,2023-07-17,,100 from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.`

No se que es lo que debo hacer. La funcion Registrar recoge los datos del formulario, los mete en un array y los pasa junto a la variable funcion. En el archivo Llamada.php recoge los datos y filtraria con el switch segun la variable funcion para que llame a una funcion dao u otra. Todo va bien en la funcion Registrar de js hasta que llega a :"if(this.readyState==XMLHttpRequest.DONE && this.status==200)" donde "this.readyState==XMLHttpRequest.DONE" es true pero "this.status==200" es false. No se que hacer, agradeceria mucho la ayuda.

[enter image description here](https://i.stack.imgur.com/npAi3.png)
[enter image description here](https://i.stack.imgur.com/0iMkB.png)
[enter image description here](https://i.stack.imgur.com/jCmyi.png)
[enter image description here](https://i.stack.imgur.com/eQUCm.png)
[enter image description here](https://i.stack.imgur.com/Yqm4o.png)`

How to generate Adobe Premiere Pro compatible XML from a video file in an Electron.js app?

I’m working on an Electron.js application where I need to automate the process of creating an Adobe Premiere Pro project from a video file. The goal is to take a video file, generate an XML file in a format that Premiere Pro can understand, and then when this XML file is imported into Premiere Pro, it would recreate the project with the same arrangement of clips, effects, etc.
I understand that this would require a detailed understanding of the XML format used by Premiere Pro. However, I’m not sure where to start and I haven’t been able to find any API or library provided by Adobe that could help with generating this XML file.
Has anyone done something similar or could point me to any resources that would help me understand the XML format used by Premiere Pro? Any guidance on how to achieve this within an Electron.js application would be greatly appreciated. Thank you.

I’ve tried to generate an XML file from the metadata of a video file using the ffprobe tool and then convert this metadata to XML format. However, when I import this XML file into Adobe Premiere Pro, it doesn’t recognize the file as a valid project file. I was expecting Adobe Premiere Pro to be able to import the XML file and recreate the project with the same arrangement of clips as in the original video file. However, it seems that the XML file generated from the ffprobe metadata doesn’t contain all the necessary information for Adobe Premiere Pro to recreate the project. I’m now looking for a way to generate an XML file that includes all the necessary information for Adobe Premiere Pro.

NextAuth expression is not callable error

So I was learning authentication in Next.js using next-auth. I followed the documentation and here is my app/api/auth/[...nextauth]/route.ts code

import NextAuth, { type NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions: NextAuthOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),

    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: {
          label: "Username",
          type: "text",
          placeholder: "John Smith",
        },
        password: {
          label: "Password",
          type: "password",
          placeholder: "*******",
        },
      },
      async authorize(credentials) {
        // here data should come from the database
        const user = { id: "1", name: "John", password: "pass" };
        if (
          credentials?.username === user.name &&
          credentials.password === user.password
        ) {
          return user;
        } else {
          return null;
        }
      },
    }),
  ],
};
const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

I am getting an error in this file that says

This expression is not callable.
  Type 'typeof import("e:/Javascript/learnauth2/node_modules/next-auth/next")' has no call signatures.ts(2349)

The version of next-auth I have is 4.22.2 and that of next is 13.4.10

Any help regarding this is appreciated