How to host HTML page with CDN in Gradio?

I am building an Gradio that visualises the data using Google charts CDN.

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

The HTML I use:

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
            ['competitor', 'count'],
            ['appeared', 9],
            ['not appeared', 6]
        ]);

        var options = {
          title: 'Netflix vs Prime'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

And hosted it using the gradio:


import gradio as gr

with gr.Blocks(
    theme=gr.themes.Soft()
    ) as demo:
    template1 = open("templates/sample2.html").read()
    insights = gr.HTML(template1)
    insights.render()

demo.launch()

I could only see:

{
  "detail": "Not Found"
}

Kindly, let me know if you have faced any of these issues and solved earlier?

NeoLoad- How to implement VTS or similar utility?

We have a requirement in NeoLoad where we are using consumable data. It is time consuming to open each of the files and change the data.
Can we achieve VTS in NeoLoad or something similar to that?
While figuring out this, I got to know about TOSCA (another product of Neotys) which may help. Can someone share some light on this issue?

change date format to dd-mm-yyyy

the current date is showing in dd-mm-yyyy format but when i select the pop up showing in mm-dd-yyyy,after selecting also same thing

i want to change that to dd-mm-yyyy

const today = new Date();
    var journeyDate = new Date(),
        returnDate = new Date();

    journeyDate.setDate(today.getDate() );
    returnDate.setDate(today.getDate() );

    $(".journey-date").val(journeyDate.toLocaleDateString());
    $(".return-date").val(returnDate.toLocaleDateString());

    $(".journey-day-name").html(journeyDate.toLocaleString('en-us', { weekday: 'long' }));
    $(".return-day-name").html(returnDate.toLocaleString('en-us', { weekday: 'long' }));

    $(".journey-date").change(function () {
        var ojd = $(this).closest(".search-form-date").find(".journey-date").val();
        const journeyDayName = new Date(ojd).toLocaleString('en-us', { weekday: 'long' });
        $(this).closest(".search-form-date").find(".journey-day-name").html(journeyDayName);
    });

    $(".return-date").change(function () {
        var rd = $(this).closest(".search-form-date").find(".return-date").val();
        const returnDayName = new Date(rd).toLocaleString('en-us', { weekday: 'long' });
        $(this).closest(".search-form-date").find(".return-day-name").html(returnDayName);
    });

How to fetch and display the labels from this js file

I want to fetch the labels such as ASHOKLEY and display the percentage. Not sure how to do it.

modelDataAvailable({"groups":[{"label":"ASHOKLEY 2.8%","weight":2.8,"id":"1"},{"label":"BHARATFORG 3.5%","weight":3.5,"id":"2"},{"label":"BAJAJ-AUTO 9.61%","weight":9.61,"id":"3"},{"label":"BALKRISIND 2.16%","weight":2.16,"id":"4"},{"label":"BOSCHLTD 2.23%","weight":2.23,"id":"5"},{"label":"EICHERMOT 5.82%","weight":5.82,"id":"6"},{"label":"HEROMOTOCO 6.65%","weight":6.65,"id":"7"},{"label":"M&M 16.38%","weight":16.38,"id":"8"},{"label":"MARUTI 14.9%","weight":14.9,"id":"9"},{"label":"MOTHERSON 2.98%","weight":2.98,"id":"10"},{"label":"MRF 3.22%","weight":3.22,"id":"11"},{"label":"SONACOMS 2.81%","weight":2.81,"id":"12"},{"label":"TATAMOTORS 17.25%","weight":17.25,"id":"13"},{"label":"TIINDIA 4.51%","weight":4.51,"id":"14"},{"label":"TVSMOTOR 5.16%","weight":5.16,"id":"15"},]},{ label:  "NIFTY AUTO ",file: "SectorialIndexDataNIFTY AUTO.jsonp "});

Is there a way to embed a PDF document on a webpage and at the same time disabling download

We have a website where there are multiple PDF’s available for the user. We have to restrict the user from downloading the PDF’s. I Would prefer solution in Javascript/HTML

We tried multiple ways to Disable PDF download with javascript, But seems with update in chrome browser disabling dowload of PDF is not working. Chrome is using inbuild plugin pdf-viewer to display PDF in browser window. pdf-viewer is not supporting the disable download feature.

Determining the Entry Point for Incoming Requests in Express.js Server

In my Node.js Express server, I’m trying to pinpoint the exact location where incoming requests are initially processed. I’ve attempted to log the request object, but I’m struggling to identify the precise entry point within my codebase where requests are first handled upon arrival from the client. Could someone provide insight into which part of the code or which specific line is executed first when a request is received by the Express server?

I’ve explored logging the request object but haven’t been able to trace it back to the initial entry point.
My goal is to better understand the request lifecycle within Express.js and locate the primary handler for incoming requests.
Any tips, code snippets, or explanations clarifying the request processing flow would be greatly appreciated.

Struggling to Resolve JavaScript Error in Backend Implementation: Need Assistance

I’m encountering an issue with the JavaScript code on my website, and I’m seeking assistance in resolving it. The problem arises when attempting to implement a dynamic dropdown menu for selecting gold rates based on different locations. Despite following tutorials and debugging extensively, the dropdown menu fails to populate with the expected data, leaving it blank. I suspect there might be an issue with the AJAX request or the data parsing process, but I’m having trouble pinpointing the exact cause. Can anyone provide guidance or suggest potential solutions to troubleshoot and fix this issue? I’m open to any insights or recommendations. Thank you in advance for your help!

` // JavaScript code for dynamic dropdown menu on findgoldrate.com

 // Function to fetch gold rates based on location
 function fetchGoldRates(location) {
 // AJAX request to fetch gold rates data
 $.ajax({
 rl: '/api/gold-rates',
 method: 'GET',
 data: { location: location },
 success: function(response) {
 // Parse response and populate dropdown menu
 var dropdownMenu = document.getElementById('gold-rates-dropdown');
 dropdownMenu.innerHTML = ''; // Clear existing options

 // Loop through response data and create option elements
 response.forEach(function(rate) {
 var option = document.createElement('option');
 option.value = rate.value;
 option.text = rate.location + ': $' + rate.value;
 dropdownMenu.appendChild(option);});},
 error: function(xhr, status, error) {
 console.error('Error fetching gold rates:', error);
 }
 });
 }
 // Function to initialize dropdown menu
 function initDropdownMenu() {
 // Event listener for location change
 var locationInput = document.getElementById('location-input');
 locationInput.addEventListener('change', function() {
 var selectedLocation = locationInput.value;
 fetchGoldRates(selectedLocation);
 });
 }
 // Initialize dropdown menu when DOM is ready
 document.addEventListener('DOMContentLoaded', function() {
 initDropdownMenu();
 });

`

What I’ve tried so far:

Ensured that the AJAX request is correctly configured and reaching the server at the specified endpoint (/api/gold-rates).
Verified that the response data is properly formatted and accessible.
Checked for any errors in the browser console, but no specific errors are being reported.

i have createed flask and result should shown on ui

from flask import Flask, request, jsonify
from flask_cors import CORS
import os
from profilevalidation import Myclass

app = Flask(name)
CORS(app)

@app.route(‘/run-script’, methods=[‘POST’])
def run_script():
try:
uploaded_file = request.files[‘file’]

    desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')

    temp_folder = os.path.join(desktop_path, 'Cat')
    os.makedirs(temp_folder, exist_ok=True)

    temp_path = os.path.join(temp_folder, uploaded_file.filename)
    uploaded_file.save(temp_path)

    
    print("File saved at:", temp_path)

    my_instance = Myclass()
    

    result = my_instance.profile(temp_path)
    print(result)
    
    print("Validation result:", result)

    return jsonify({'result': result})
except Exception as e:
    print("An error occurred:", e)  
    return jsonify({'error': str(e)})

if name == “main“:

print("Flask application is running...")
app.run(debug=True)

flask part

import React, { useState } from ‘react’;

function FileUpload() {
const [file, setFile] = useState(null);

function handleFile(event) {
    setFile(event.target.files[0]);
    console.log(event.target.files[0]);
}

function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData();
    formData.append('file', file);

    // Send the file to the backend
    fetch('http://127.0.0.1:5000/run-script', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {console.log(data);
        // Handle the result as needed
    })
    .catch(error => console.error('Error:', error));
}

return (
    <div>
        <h2>Profile Validation Tool</h2>
        <form onSubmit={handleSubmit}>
            <input type="file" name="file" onChange={handleFile} />
            <button type="submit">Submit</button>
        </form>
    </div>
);

}

export default FileUpload;
respone should be validation result

HTML async load image is still very slow

Im using html’s built in lazy loading and async decoding however the page still takes a full minute to load. how could I make the images load asynchronously to the page so the page will load faster?

{% if limiteds is not none %}
    {% for limited in limiteds %}
    <div class="card">
        <img class="card-img-top" src="{{ limited[3] }}" loading="lazy" decoding="async" style="width:60px; height:60px">
        <h5 class="card-title">{{ limited[0] }}</h5>
        <p class="card-text">R$ {{ limited[1] }}</p>
        <p class="card-text">$ {{ limited[2] }}</p>
    </div>
{% endfor %}
{% endif %}

Thanks in advance,

  • JoshMann15

asset size limit: How to skip this warning to run vue project on production?

I am trying to use this dashboard template https://github.com/PanJiaChen/vue-admin-template.
First, i faced with ‘openssl-legacy-provider’ error and i fixed it with changing package.json (export NODE_OPTIONS=–openssl-legacy-provider && vue-cli-service build).
Then there is another warning ‘asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).This can impact web performance.’, which is not letting me to start the project.

https://github.com/PanJiaChen/vue-admin-template/blob/master/vue.config.js how should i change vue.config.js file so that it will start?

tried optimization.splitChunks({...}) module.exports = { performance: { hints: false, }, }; }. did not work

Chrome gives me the “Cannot read properties of null (reading ‘addEventListener’)”

I am pretty new to javascript, and honestly have no idea what i’m doing. I was writing an html page in which i wanted to put a runaway button. But the script does not run at all.

<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>My question</title>
                <style>
                    body {
                        background-color: #ffcc00;
                        color: #333;
                        font-family: Arial, sans-serif;
                        text-align: center;
                        padding: 50px;
                        overflow: hidden; 
                    }
                    h1 {
                        font-size: 48px;
                        margin-bottom: 30px;
                        color: #ffcc00;
                    }
                    p {
                        font-size: 24px;
                        margin-bottom: 20px;
                        color: #ffcc00;
                    }
                    button {
                        padding: 15px 30px;
                        margin: 10px;
                        border: none;
                        border-radius: 25px;
                        cursor: pointer;
                        font-size: 18px;
                        transition: background-color 0.3s ease;
                    }
                    button.yes-button {
                        background-color: #ffcc00; 
                        color: #333;
                    }
                    button.yes-button:hover {
                        background-color: #ffdb4d; /* Lighter yellow on hover */
                    }
                    button.no-button {
                        background-color: #ff6666; /* Red button color */
                        color: #fff; /* White button text color */
                    }
                    
                    #nobutton {
                        position: absolute;
                        white-space: nowrap;
                    }
                    body::before {
                        content: "";
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-image: url('https://i.pinimg.com/564x/bd/3e/f6/bd3ef69efdacbe1c6d2a0db99e5c8dae.jpg');
                        background-size: auto 120%;
                        background-position: center;
                        background-repeat: no-repeat;
                        z-index: -1;
                    }
                </style>
            </head>
            <body>
                <h1>My question</h1>
                <button class="yes-button">yes</button>
                <button class="no-button" id="noButton">no</button>
                <script>
                const evilbutton = document.getElementById('nobutton');
                const OFFSET = 100
                evilbutton.addEventListener('mousemove', (e) => {
                    const x = e.pageX
                    const y = e.pageY
                    const btnbox = evilbutton.getBoundingClientRect()
                    const horizontaldist = distancefromcenter(btnbox.x, x, btnbox.width)
                    const verticaldist = distancefromcenter(btnbox.y, y, btnbox.height)
                    const horizontaloffset = btnbox.width/2 + OFFSET
                    const verticaloffset = btnbox.height/2 + OFFSET
                    if (Math.abs(horizontaldist) <= horizontaloffset && Math.abs(verticaldist) <= verticaloffset) {
                        setbtnpos(
                            btnbox.x + horizontaloffset / horizontaldist * 10,
                            btnbox.y + verticaloffest / verticaldist * 10
                        )
                    }
                })
                function setbtnpos(left, top) {
                    const windowbox = document.body.getBoundingClientRect()
                    const buttonbox = evilbutton.getBoundingClientRect()

                    if(distancefromecenter(left, windowbox.left, buttonbox.width) < 0) {
                        left = windowbox.right - buttonbox.width - OFFSET
                    }
                    if(distancefromecenter(left, windowbox.right, buttonbox.width) > 0) {
                        left = windowbox.left + OFFSET
                    }
                    if(distancefromecenter(left, windowbox.bottom, buttonbox.width) > 0) {
                        left = windowbox.top + OFFSET
                    }
                    if(distancefromecenter(top, windowbox.top, buttonbox.height) < 0) {
                        top = windowbox.bottom - buttonbox.height - OFFSET
                    }
                    evilbutton.style.top = top + 'px'
                    evilbutton.style.left = left + 'px'
                }


                function distancefromcenter(boxpos, mousepos, boxsize) {
                    return boxpos - mousepos + boxsize/2
                }
                  
            </script>
            </body>
            </html>

I Know this exact question has been asked by countless people already, but I’ve already tried all the solutions were discussed in those threads. I have placed the script at the bottom of the tag, I have made sure (i think) of there being no typos, but i just can’t figure out why EventListener is not able to find this. Most of the code in the below snippet isnt written by and me just taken from tutorials and youtube videos. Can anyone point out to me why this is not working?

Subtraction in HTML

My goal is to subtract the gross from the bca total/balance. But the problem with my code, it doesn’t subtract properly. Just like what happen in the picture. The beginning balance is 1000, and if I input 500, the new balance should be 500. However, in my code, it is showing as -500.](https://i.stack.imgur.com/unLm1.png)](https://i.stack.imgur.com/unLm1.png)

This is my code

function addData() {
    // Get input values
    let dv = document.getElementById("dvInput").value;
    let date = document.getElementById("dateInput").value;
    let number = document.getElementById("numberInput").value;
    let check = document.getElementById("checkInput").value;
    let payee = document.getElementById("payeeInput").value;
    let uacs = document.getElementById("uacsInput").value;
    let particulars = document.getElementById("particularsInput").value;
    let project = document.getElementById("projectInput").value;
    let period = document.getElementById("periodInput").value;
    let gross = parseFloat(document.getElementById("grossInput").value) || 0;
    let bir = parseFloat(document.getElementById("birInput").value) || 0;
    let net = parseFloat(document.getElementById("netInput").value) || 0;
    let receipts = document.getElementById("receiptsInput").value;
    let total = parseFloat(document.getElementById("totalInput").value) || 0;

    // Subtract Gross from the previous BCA Total/Balance
    let newBcaTotalBalance = total - gross;
         
    // Get the table and insert a new row at the end
    let table = document.getElementById("outputTable");
    let newRow = table.insertRow(table.rows.length);

    // Insert data into cells of the new row
    newRow.insertCell(0).innerHTML = dv;
    newRow.insertCell(1).innerHTML = date;
    newRow.insertCell(2).innerHTML = number;
    newRow.insertCell(3).innerHTML = check;
    newRow.insertCell(4).innerHTML = payee;
    newRow.insertCell(5).innerHTML = uacs;
    newRow.insertCell(6).innerHTML = particulars;
    newRow.insertCell(7).innerHTML = project;
    newRow.insertCell(8).innerHTML = period;
    newRow.insertCell(9).innerHTML = gross.toFixed(2);
    newRow.insertCell(10).innerHTML = bir.toFixed(2);
    newRow.insertCell(11).innerHTML = net.toFixed(2);
    newRow.insertCell(12).innerHTML = receipts;
    newRow.insertCell(13).innerHTML = newBcaTotalBalance.toFixed(2);
    newRow.insertCell(14).innerHTML =
        '<button onclick="editData(this)">Edit</button>' +
        '<button onclick="deleteData(this)">Delete</button>';

    // Clear input fields
    clearInputs();
}

Function not defined in ejs [duplicate]

The function is not defined, I want to get the jobtitle and show it in the ejs file without the hyphen and capitalize the first letter
When i remove the function the job title is shown
I tried to change the received jobtitle in the route
example – (software-engineer) to (Software Engineer)

router.get('/job/:jobTitle',(req,res) => {
  const { jobTitle } = req.params;
  res.render('job',{ jobTitle });
});
<p class="job-title"><%= formatJobTitle(jobTitle) %></p>
    <script>
        function formatJobTitle(jobTitle) {
            const words = jobTitle.split('-');
            
            const formattedTitle = words.map(word => {
                return word.charAt(0).toUpperCase() + word.slice(1);
            }).join(' ');

            return formattedTitle;
        }
    </script>
router.get('/job/:jobTitle', (req, res) => {
  const { jobTitle } = req.params;
  const formattedJobTitle = formatJobTitle(jobTitle);

  res.render('job', { jobTitle: formattedJobTitle });
});

function formatJobTitle(jobTitle) {
  const words = jobTitle.split('-');
  const formattedTitle = words.map(word => {
      return word.charAt(0).toUpperCase() + word.slice(1);
  }).join(' ');

  return formattedTitle;
}

Is there a way to determine when a DOM element’s geometry can be accurately queried?

I’m trying to add content to a textarea based on user action, and size the textarea height to be its scrollHeight such that it can be scrolled inside another container.

It works, but in some cases it fails because it seems to need a bit more time to figure out the scrollHeight before it is queried. If I put a setTimeout of about 10ms, then it works fine again.

There is not a lot of content being added when this happens (far less than in the snippet, but the DOM itself is much more complex).

My question is, Is there a way (apart from setTimeout) to know when the textarea element’s geometry can be accurately queried? I don’t want to pick a delay and hope it works on most machines and find it is too quick for some older equipment.

I could not get the snippet to fail but I think it is because the browser “waits” until it is ready to add the vertical scroll bar, and my UI uses custom scroll bars such that the browser may not wait since its overflow is hidden. I’m just guessing. The delay between the click and the display of the content is not due to building the content because that is performed only once.

Thank you for considering my question and for any guidance you may be able to provide.

let
   btn = document.querySelectorAll('button'),
   ta = document.querySelectorAll('textarea'),
   prnt = document.querySelector('div'),
   arr = [],
   data
;
for (let i=0; i < 100000; i++) arr.push("Paragraph number " + i + ".n");
data = arr.join('');

ta[1].value = "Textarea 2";

btn[0].addEventListener( 'mousedown', AddToTextarea, true);
btn[1].addEventListener( 'mousedown', RemoveText, true);
function AddToTextarea(event) {
  ta[0].value = data;  
  prnt.classList.replace( prnt.classList.item(1), 'ta_0');
  ta[0].style.height = ta[0].scrollHeight + 'px';
  //setTimeout( () => {ta[0].style.height = ta[0].scrollHeight + 'px';}, 500);
}

function RemoveText() {
  ta[0].value = "";
  ta[0].style.height = ta[0].scrollHeight + 'px';
  prnt.classList.replace( prnt.classList.item(1), 'ta_1');
}
textarea {
 display: none;
 border-color: blue;
}

div.ta_0 textarea.ta_0 {
  display: block;
}

div.ta_1 textarea.ta_1 {
  display: block;
}

.parent {
  display: flex;
  flex-flow: column;
  height: 200px;
  width: 200px;
  overflow-y: scroll;
  border: 1px solid black;
}

.parent > div {
  flex: 1 1;
}
<div class="parent ta_1">
 <div>
    <button>Add Text</button>
    <button>Clear Text</button>
    <textarea class="ta_0"></textarea>
    <textarea class="ta_1"></textarea>
  </div>
</div>

How can I manipulate a TXT file generator so that it gives me the right values?

I created a family tree generator for characters.
When I add a character, I can add a relationship to the other registered characters.
My problem is that when I generate a txt of the selected character, I can’t get it to show me just the name of the relative and their relationship.
I needed him to return to me, for example, the list of Elliot’s relatives:
Jonh (Brother)
Kyle (Grandfather)
Joe (Father)
enter image description here
But this is my result
enter image description here

That’s my function

gerarArquivoBtn.addEventListener('click', function () {
        const selectPersonagem = document.getElementById('selecionarPersonagem');
        const personagemSelecionado = selectPersonagem.value;
    
        let dados;
        if (personagemSelecionado) {
            dados = pessoas
                .filter(p => p.parentesco.includes(personagemSelecionado))
                .map(p => {
                    const parentescoIndex = p.parentesco.indexOf('(');
                    const parentesco = parentescoIndex !== -1 ? p.parentesco.slice(parentescoIndex + 1, -1).trim() : ''; // Verifica se existe o caractere ( na string parentesco, se existir, pega a substring entre ( e ), remove os espaços em branco extras
                    return `${p.nome} (${parentesco})`;
                })
                .join('n');
        } else {
            dados = pessoas
                .map(p => {
                    const parentescoIndex = p.parentesco.indexOf('(');
                    const parentesco = parentescoIndex !== -1 ? p.parentesco.slice(parentescoIndex + 1, -1).trim() : ''; // Verifica se existe o caractere ( na string parentesco, se existir, pega a substring entre ( e ), remove os espaços em branco extras
                    return `${p.nome} (${parentesco})`;
                })
                .join('n');
        }
    
        const blob = new Blob([dados], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'arvore_genealogica.txt';
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(url);
        document.body.removeChild(a);
    });

I know it’s wrong… but I can’t fix it.

I tried to separate the information and tried to get just the relationship, but I couldn’t. I was probably going about it the wrong way, but I’d rather take the relationship type than cut a cord.
Some family relationships in Portuguese are compound words, so I believe that dealing with these words is very complicated.