get xlsx from quart page with javascript

I have a problem. I want to get xlsx made from this route, the problem is open other page but this take a lot of time then I do a button with javascript to do fetch and get the file but it isn’t working.

¿What I do wrong? or ¿What I can try?

I’ve saw some solutions with chunks but I don’t know, ¿someone can help me?

<!-- after I try this -->
{% if total_records > 0 %}
    <button class="btn btn-success" id="button_download_xslx" type="button">Convertir a
                xlsx</button>
    <a class="btn btn-primary mx-5" id="anchor-download-xlsx">Descargar</a>
    
<!-- original idea -->
<a
                href="{{ next_page_or_download_xlsx(page='transport_cash_blueprint.download_xlsx', query_params=query_params) }}"
                target="_blank"
                class="btn btn-primary mx-5">Descargar</a>
{% endif %}

from quart import Blueprint
from quart import request
from quart import send_file, render_template, redirect, url_for

from quart_auth import login_required

from xlsxwriter import Workbook
from asyncio import TaskGroup
from wtforms import Form
from io import BytesIO

from math import ceil

from ..form import TransportCashForm
from ..contants import COLUMNS_TRANSPORT_CASH
from ..database import (
    transport_cash_all,
    transport_cash_limited_per_page,
    transport_cash_total_records,
    create_query_transport_cash,
)

transport_cash_blueprint = Blueprint(
    "transport_cash_blueprint",
    __name__,
    url_prefix="/transport_cash",
)


@transport_cash_blueprint.get("/download_xlsx", methods=["GET"])
async def download_xlsx():
    query_params = dict(request.args)

    output = BytesIO()
    workbook = Workbook(output, {"in_memory": True})

    worksheet = workbook.add_worksheet()

    query = create_query_transport_cash(query_params)
    data = await transport_cash_all(query)

    for col_num, title_data in enumerate(COLUMNS_TRANSPORT_CASH):
        worksheet.write(0, col_num, title_data)

    for row_num, row_data in enumerate(data):
        for col_num, col_data in enumerate(row_data):
            worksheet.write(row_num + 1, col_num, col_data)

    workbook.close()
    output.seek(0)
    return await send_file(output, download_name="test.xlsx", as_attachment=True)
document.getElementById('button_download_xslx').addEventListener('click',
    async (event) => {
        event.preventDefault();
        let descargarEnlace = document.getElementById("anchor-download-xlsx")
        let newUrl = query_params()

        const response = await fetch(newUrl, {method: "GET"});
        const data = await response.blob();
        const url = window.URL.createObjectURL(data);
        descargarEnlace.href = url;  // Asignar la URL al enlace
        descargarEnlace.click();

    }
)

query_params = () => {
    const params = new URLSearchParams(window.location.search);

    let url = new URL("http://127.0.0.1:5000/transport_cash/download_xlsx");

    let params_dictionary = {
        fecha_desde_cuando_value: params.get("fecha_desde_cuando_value"),
        fecha_hasta_cuando_value: params.get("fecha_hasta_cuando"),
        numero_identificacion_value: params.get("numero_identificacion"),
        nombre_razon_social_value: params.get("nombre_razon_social"),
    }

    // Si el largo del objecto filtrado es mayor a 0 añade las llaves y valores
    if (Object.keys(params_dictionary).length > 0) {
        // filtramos los valores si es nulo

        let filtered_params = Object.fromEntries(
            Object.entries(params_dictionary).filter(
                ([key, value]) => value != null)
        )

        Object.keys(filtered_params).forEach(
            key => url.searchParams.append(key, filtered_params[key])
        );
        return url
    }
    return url
}

Why is my Website navigation working on live server but not when deployed

For my school project we are adding navigation to simple websites with javascript. I’m using Visual Studio Code and live server extension. When I run the website through live server extension it works fine.Here

However when i deploy to github and visit the site, the navigation does not appear and i get a 404 errorhere

This is my folder structure

this is my menu.js file that sits in the scripts folder

const root = "/WSOA3028A_2583750"

const menuItems = [
    {name: "Home", href: root + "/index.html"},
    {name: "Blog", href: `${root}/Blogs/index.html`},
    {name: "Essays", href: `${root}/Essays/index.html`},
    {name: "Portfolio", href: `${root}/Portfolio/index.html`},
    {name: "Design", href: `${root}/Design/index.html`},
    {name: "About", href: `${root}/About/index.html`},
];
export function initialise(currentPage){

    console.log("worked")
    const nav = document.querySelector("header > nav")
    const ul = document.createElement("ul")
    for(let menuItem of menuItems)
    {
        const li = document.createElement("li")
        if(currentPage != menuItem.name)
        {
            const a = document.createElement("a")
            a.innerText = menuItem.name
            a.setAttribute("href", menuItem.href)
            li.appendChild(a)

        }
        else{
            li.innerText = menuItem.name
        }
        ul.appendChild(li)
    }
    nav.appendChild(ul)

    
}

this is where i call the menu.js script in my index.html file that sits outside the folders

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="author" content="Cameron Morgan">
  <meta name="description" content="This is the index page of the website displaying the portfolio and blogs for Cameron Morgan in the course Interactive Media  ">
  <meta name="robots" content="index,follow">
  <meta name="keywords" content="Web Development, Game Development, Interactive, Blog, Portfolio, Essay, Design">

    <meta property="og:title" content="Cameron Morgan Portfolio Website">
    <meta property="og:description" content="Welcome to Cameron Morgan's Portfolio Website, here you can find his portfolio of work, including games, websites, blogs, analysis.">
    
    <meta property="og:url" content="https://wits-digital-arts-interactive-media.github.io/WSOA3028A_2583750/">

  <link rel="icon" type="image/png" href="Images/coffee.png">
  <script type="module">
    import { initialise } from "./Scripts/menu.js";
    initialise("Home"); // Call the initialise function with a test argument
</script>
  <title>Interactive Media Website</title>

  
  


</head>

Chrome throws up CORS errors

Access to script at ‘file:///C:/Users/camer/IM_GITHUB/WSOA3028A_2583750/Scripts/menu.js’ 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.

and

Failed to load resource: net::ERR_FAILED

JS Object Standard Prototype as a Symbols

Looks like it is not really feasible or very tricky still I’ll take a try.

How to describe a structure (Object/class) that ought to represent a fluent (non predefined) structure config node (i.e. could have properties whatever user might put here)

Still the Node representation should have under the hood custom functional implementation for standard Object handling i.e. toString, valueOf, toJSON.

So could these three (and maybe some other useful stuff would be needed earlier) be implemented on some Symbols level or other non publicly enumerable properties basis so that properties would be available for the data content it self?

E.g. config structure could be available for the user to input as

configRoot:
  fluentSubSection:
     somProp: 12
     valueOf: John Doe
     toString: whatever

so that the user shouldn’t be restricted with any reserver words for properties
Still the config representation structure it self would be as well in natural way as

const config = loadConfig('...')
console.log(config.configRoot.fluentSubSection.valueOf) 
// John Doe - plain content data access

Still the ConfigNode instance it self should have some custom functionality under the hood as

console.log(String(config.configRoot.fluentSubSection)) 
// Should switch to some functional level access for toString 
// E.g. [Custom ConfigNode - somProp: 12; valueOf: John Doe]

Digging both Symbols and Proxies looks isn’t of much help here to split functional and content representation here.

Anyway please any ideas are appreciated.
Thx

Fetch API Sends Form Data to Flask Backend, Resulting in 400 (Bad Request) Error

I’m developing a web application with Flask for the backend and JavaScript for the frontend. I’m encountering an issue where form data sent from the frontend using the Fetch API to my Flask backend is resulting in a 400 (Bad Request) error. Despite this error, nothing is being logged on the server side.

Here’s a simplified example of my code:

Backend (Flask):

@app.route('/join', methods=['POST'])
def join():
    username = request.form['username']
    password = request.form['password']
    # Process username and password

Frontend (JavaScript):

document.getElementById("join-button").addEventListener("click", function() {
    fetch('/join', {method: 'POST',headers: {'Content-Type': 'application/json'}})
});

Despite sending the form data correctly from the frontend, I’m consistently receiving a 400 (Bad Request) error. What could be causing this issue? Why is nothing being logged on the server side despite the error? How can I troubleshoot and resolve this problem?

navigator.serviceWorker.ready does not resolve

(Note: other issues here, and here, are not the same as this)

Hi folks,

I don’t seem to be able to get the ready property of the ServiceWorkerContainer to resolve:

const serviceWorkerScriptPath = new URL('./worker.js', import.meta.url);

const registration = await navigator.serviceWorker.register(serviceWorkerScriptPath, {
    scope: serviceWorkerScriptPath.pathname,
});

if(registration.active) {
  console.log("Service worker active"); // <== This is logged
}

console.log(`Waiting for service worker ready...`);

const readyReg = await navigator.serviceWorker.ready; // <== Never resolves

console.log(`Service worker ready`); // <== Never logged

(my worker.js is not in the root path, so I’m just using the URL to avoid hard coding the path)

Documentation seems to imply that this ready promise should resolve when “the current page has an active worker”

Is there some reason this ready promise would not resolve in this case? I’ve found this whole API to be pretty confusing, and I don’t even know if I need this promise to resolve, but I’m ultimately trying to use the periodicSync API, and all the examples there seem to want this ready promise to be resolved.

So i have been trying to create a clciker game and all of a sudden here is the error it shows me

So i have a problem, according to the developer console, I have a cors error and i don’t understand why and if anybody can help correct my code it will be a pleasure and here is the video tutorial i am watching text. If anybody has any clue what’s going on apparently everything’s working for him and i have the same code as him

index.html:1 Access to script at 'file:///C:/Users/PC/Downloads/clicker%20game/index.js' 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.
index.js:1 
        
        
       Failed to load resource: net::ERR_FAILED
3index.html:19 Uncaught ReferenceError: incrementGem is not defined
    at HTMLImageElement.onclick (index.html:19:112)
onclick @ index.html:19
index.html:46 Uncaught ReferenceError: buyupgrade is not defined
    at HTMLDivElement.onclick (index.html:46:70)
onclick @ index.html:46
index.html:133 Uncaught ReferenceError: save is not defined
    at HTMLButtonElement.onclick (index.html:133:58)
onclick @ index.html:133
index.html:136 Uncaught ReferenceError: load is not defined
    at HTMLButtonElement.onclick (index.html:136:57)
onclick @ index.html:136

here is my code
html:

 <!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clicker game</title>
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:[email protected]&display=swap" rel="stylesheet">
 </head>
 <body>
    <section>
        <div class="main">
            <div class="left">
                <h3>Oranges <br><span class="orange-cost pink-text">0</span></h3>
                <div class="orange-image-container">

                    <img src="orange.png" class="orange-image" onclick="incrementGem(event)" draggable="false">


                </div>
            </div>
            <script id="upgrade-template" type="text/template">
                 <div class="right">
                <div class="upgrade" onclick="buyupgrade('clicker')">
                    <div class="left-section">
                        <img src="clicker.png" class="upgradeimg">
                    </div>
                    <div class="mid-section">
                        <h4>Clicker</h4>
                        <div class="cost-info">
                            <p class="cost-text"><span class="clicker-cost">10</span></p>
                            <img src="orange.png" class="gemimg">
                        </div>
                    </div>
                    <div class="right-section">Level <span class="clickerlevel">0</span></div>
                    <div class="nextlevelinfo">
                        <p>
                            +<span class="cursor-increase">1 </span> oranges <br>  per click
                        </p>
                    </div>
                </div>
            </script>
            <div class="right">
                <div class="upgrade" onclick="buyupgrade('clicker')">
                    <div class="left-section">
                        <img src="clicker.png" class="upgradeimg">
                    </div>
                    <div class="mid-section">
                        <h4>Clicker</h4>
                        <div class="cost-info">
                            <p class="cost-text"><span class="clicker-cost">10</span></p>
                            <img src="orange.png" class="gemimg">
                        </div>
                    </div>
                    <div class="right-section">Level <span class="clickerlevel">0</span></div>
                    <div class="nextlevelinfo">
                        <p>
                            +<span class="cursor-increase">1 </span> oranges <br>  per click
                        </p>
                    </div>
                </div>
                <div class="right" id="upgrade-container">

                </div>

                <div class="upgrade" onclick="buyupgrade('crate')">
                    <div class="left-section">
                        <img src="crateorange.png" class="upgradeimg">
                    </div>
                    <div class="mid-section">
                        <h4>Crate</h4>
                        <div class="cost-info">
                            <p class="cost-text"><span class="crate-cost">130</span></p>
                            <img src="orange.png" class="gemimg">
                        </div>
                    </div>
                    <div class="right-section">Level <span class="cratelevel">0</span></div>
                    <div class="nextlevelinfo">
                        <p>
                            +<span class="crate-increase">4 </span> oranges <br>  per second
                        </p>
                    </div>
                </div>
                <div class="upgrade" onclick="buyupgrade('farmer')">
                    <div class="left-section">
                        <img src="farmer.png" class="upgradeimg">
                    </div>
                    <div class="mid-section">
                        <h4>Farmer</h4>
                        <div class="cost-info">
                            <p class="cost-text"><span class="farmer-cost">850</span></p>
                            <img src="orange.png" class="gemimg">
                        </div>
                    </div>
                    <div class="right-section">Level <span class="farmerlevel">0</span></div>
                    <div class="nextlevelinfo">
                        <p>
                            +<span class="farmer-increase">12 </span> oranges <br>  per second
                        </p>
                    </div>
                </div>
                <div class="upgrade" onclick="buyupgrade('factory')">
                    <div class="left-section">
                        <img src="factory.png" class="upgradeimg">
                    </div>
                    <div class="mid-section">
                        <h4>Factory</h4>
                        <div class="cost-info">
                            <p class="cost-text"><span class="factory-cost">4750</span></p>
                            <img src="orange.png" class="gemimg">
                        </div>
                    </div>
                    <div class="right-section">Level <span class="factorylevel">0</span></div>
                    <div class="nextlevelinfo">
                        <p>
                            +<span class="factory-increase">82 </span> oranges <br>  per second
                        </p>
                    </div>
                </div>
                
            </div>
        </div>
        <div class="statistics">
            <div class="texts">
                <p>OPC: <span id="gpc-text" class="pink-text">1</span></p>
                <p>OPS: <span id="gps-text" class="pink-text">0</span></p>
            </div>

        </div>
        <div class="util-buttons">
            <button class="util-button" onclick="save()">
                Save
            </button>
            <button class="util-button"onclick="load()">
                Load
            </button>
        </div>
    </section>
    <script src="index.js" type="module"></script>
 </body>
 </html>

javascript 1

import { defaultValues } from "./constants/defaultValues.js";

let gem = document.querySelector('.orange-cost');
let parsedgem = parseFloat(gem.innerHTML);
let clickerCost = document.querySelector('.clicker-cost');
let parsedclickerCost = parseFloat(clickerCost.innerHTML);
let clickerlevel = document.querySelector(".clickerlevel");
let clickerincrease = document.querySelector(".cursor-increase");
let parsedclickerincrease = parseFloat(clickerincrease.innerHTML);

let crateCost = document.querySelector('.crate-cost');
let parsedcrateCost = parseFloat(crateCost.innerHTML);
let cratelevel = document.querySelector(".cratelevel");
let crateincrease = document.querySelector(".crate-increase");
let parsedcrateincrease = parseFloat(crateincrease.innerHTML);

let farmerCost = document.querySelector('.farmer-cost');
let parsedfarmerCost = parseFloat(farmerCost.innerHTML);
let farmerlevel = document.querySelector(".farmerlevel");
let farmerincrease = document.querySelector(".farmer-increase");
let parsedfarmerincrease = parseFloat(farmerincrease.innerHTML);
let gpctext = document.getElementById("gpc-text")
let gpsText = document.getElementById("gps-text")
let gpc = 1;
let gps = 0;
const upgrades = [
    {
        name: "clicker",
        cost: document.querySelector(".clicker-cost"),
        parsedCost: parsedclickerCost = parseFloat(document.querySelector(".clicker-cost").innerHTML),
        increase: document.querySelector(".cursor-increase"),
        parsedincrease: parseFloat(document.querySelector(".cursor-increase").innerHTML),
        level: document.querySelector(".clickerlevel"),
        orangemultiplier: 1.025,
        costmultiplier: 1.12,

    },
    {
        name: "crate",
        cost: document.querySelector(".crate-cost"),
        parsedCost: parsedcrateCost = parseFloat(document.querySelector(".crate-cost").innerHTML),
        increase: document.querySelector(".crate-increase"),
        parsedincrease: parseFloat(document.querySelector(".crate-increase").innerHTML),
        level: document.querySelector(".cratelevel"),
        orangemultiplier: 1.03,
        costmultiplier: 1.115,

    },
     {
        name: "farmer",
        cost: document.querySelector(".farmer-cost"),
        parsedCost: parsedfarmerCost = parseFloat(document.querySelector(".farmer-cost").innerHTML),
        increase: document.querySelector(".farmer-increase"),
        parsedincrease: parseFloat(document.querySelector(".farmer-increase").innerHTML),
        level: document.querySelector(".farmerlevel"),
        orangemultiplier: 1.035,
        costmultiplier: 1.11,

    },
    {
        name: "factory",
        cost: document.querySelector(".factory-cost"),
        parsedCost: parsedfactoryCost = parseFloat(document.querySelector(".factory-cost").innerHTML),
        increase: document.querySelector(".factory-increase"),
        parsedincrease: parseFloat(document.querySelector(".factory-increase").innerHTML),
        level: document.querySelector(".factorylevel"),
        orangemultiplier: 1.04,
        costmultiplier: 1.10,

    },
];

let gemimgcontainer = document.querySelector('.orange-image-container')
function incrementGem(event) {
    gem.innerHTML = Math.round(parsedgem += gpc);
    const x = event.offsetX
    const y = event.offsetY

    const div = document.createElement('div')
    div.innerHTML =`+${Math.round(gpc)}`
    div.style.cssText = `color: white; position: absolute; top: ${y}px; left: ${x}px; font-size; 30px; pointer-events: none;`
    gemimgcontainer.appendChild(div)
    div.classList.add('fade-up')
    timeout(div)
}
const timeout = (div) => {
    setTimeout(() => {
        div.remove()
        
    },800);
}
function createUpgrade() {
    const upgradesContainer = document.getElementById('upgrade-container');
    const template = document.getElementById('upgrade-template').textContent;

    defaultValues.forEach((value) => {
    });
}
function buyupgrade(upgrade){
    const mu = upgrades.find((u) => u.name === upgrade);

    if (parsedgem >= mu.parsedCost){
        gem.innerHTML = Math.round(parsedgem -= mu.parsedCost);

        mu.level.innerHTML++;
        mu.parsedincrease = parseFloat((mu.parsedincrease * mu.orangemultiplier).toFixed(2));
        mu.increase.innerHTML = mu.parsedincrease;
        mu.parsedCost *= mu.costmultiplier;
        mu.cost.innerHTML = Math.round(mu.parsedCost);

        if (mu.name === 'clicker'){
            gpc += mu.parsedincrease;
        } else {
            gps += mu.parsedincrease;
        }
    }
}

function save(){
    localStorage.clear()
    upgrades.map((upgrade) => {
        const obj = JSON.stringify({
            parseLevel: parseFloat(upgrade.level.innerHTML),
            parsedCost: upgrade.parsedCost,
            parsedIncrease: upgrade.parsedincrease
        });

        localStorage.setItem(upgrade.name, obj);
    });
    localStorage.setItem('gpc', JSON.stringify(gpc));
    localStorage.setItem('gps', JSON.stringify(gps));
    localStorage.setItem('orange', JSON.stringify(parsedgem));
}

function load(){
    upgrades.map((upgrade) => {
        const savedvalues = JSON.parse(localStorage.getItem(upgrade.name));
        upgrade.parsedCost = savedvalues.parsedCost;
        upgrade.parsedincrease = savedvalues.parsedIncrease;
        upgrade.level.innerHTML = savedvalues.parseLevel;
        upgrade.cost.innerHTML = Math.round(upgrade.parsedCost);
        upgrade.increase.innerHTML = upgrade.parsedincrease;
    });
    gpc = JSON.parse(localStorage.getItem('gpc'));
    gps = JSON.parse(localStorage.getItem('gps'));
    parsedgem = JSON.parse(localStorage.getItem('orange'));

    gem.innerHTML = Math.round(parsedgem);
}

setInterval(() =>{
    parsedgem += gps / 10;
    gem.innerHTML = Math.round(parsedgem);
    gpctext.innerHTML = Math.round(gpc);
    gpsText.innerHTML = Math.round(gps);
},100);

window.incrementGem = incrementGem;
window.buyupgrade = buyupgrade;
window.save = save;
window.load = load;

javascript 2

export const defaultValues = [
    {name: 'clicker', image: 'clicker.png', cost: 10, increase: 1},
    {name: 'crate', image: 'crateorange.png', cost: 60, increase: 4},
    {name: 'farmer', image: 'farmer.png', cost: 380, increase: 16},
    {name: 'factory', image: 'factory.png', cost: 3105, increase: 82},
]

css

export const defaultValues = [
    {name: 'clicker', image: 'clicker.png', cost: 10, increase: 1},
    {name: 'crate', image: 'crateorange.png', cost: 60, increase: 4},
    {name: 'farmer', image: 'farmer.png', cost: 380, increase: 16},
    {name: 'factory', image: 'factory.png', cost: 3105, increase: 82},
]

picture of the files

Why this work only using setTimeout and not normally?

I created a REPL for a strange issue.

REPL: https://stackblitz.com/edit/sveltejs-kit-template-default-9zkjpt?file=src%2Froutes%2Fabout%2FCustomSelect.svelte

Steps to reproduce

  1. Open the REPL

  2. Open the browser console

  3. Go on the “About” page using the link

  4. No message in console

  5. Now comment the line:

    result = id;
    
  6. And comment out the line:

    // setTimeout(() => (result = id), 0);
    
  7. Go on Home page

  8. Go on About page

  9. Now in the console you can see the message: “handleInput”

Why is this happening?

Is setTimeout really needed?

Relevant code

  • CustomSelect.svelte:
<script>
    import Select from 'svelte-select';

    export let value = undefined;
    export let id = undefined;
    
    $: console.log('CustomSelect, id:', id);

    let result;

    let items = [
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' },
        { value: 'three', label: 'Three' },
    ];

    $: if (id !== undefined) {
        result = id;
        // setTimeout(() => (result = id), 0);
    }

    $: if (result != undefined) {
        value = { value: 'custom', label: 'Custom' }
    }
</script>

<Select {value} {items} on:change on:input />

OpenAI API in NextJS not giving a response

I’m followed a tutorial to T but unable to get a response from the API. I’m not sure if there was an update to OpenAI API or not.

Any help will be much appreciated.

/app/(main)/page.tsx

'use client'
import React from 'react';
import Navbar from './_components/navbar';

const HomePage = () => {
  return ( 
    <div className="w-full min-h-full">
      <Navbar />
      <div className="flex flex-col justify-center">
        <h1 className="text-4xl">Welcome to Mood Palette</h1>
        <button
          onClick={async () => {
            const response = await fetch('/api/chat-gpt', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                message: 'Hello, World!',
              }),
            });
            console.log("Response", response);
          }}
        >
          Create Palette
        </button>
      </div>

    </div>
   );
}
 
export default HomePage;

/api/route.ts

import { NextRequest, NextResponse } from "next/server";
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: `Bearer ${process.env.OPENAI_API_KEY}`,
    project: 'project_id',
});

export async function POST(request: Request) {


    const response = await openai.chat.completions.create({ 
        model: "gpt-3.5-turbo", 
        messages: [
            { role: "system", content: "You are Jarvis from Iron Manl" },
            { role: "user", content: "Who are you?"}
        ],
        temperature: 0,
        max_tokens: 1024,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    });

    return NextResponse.json(response);
}

I just followed a the Open AI doc’s ‘getting started’ and a tutorial but unable to progress after the API is not responding.

The dialog box is throwing an error when trying to open a dialog

trying to create a dialog box with iframe in it, i am getting an error

$("#dialogFrame").dialog({
    autoOpen: false, // Dialog is not shown on page load
    modal: true, // Make the dialog modal
    buttons: {
      "Close": function() {
        $(this).dialog("close");
      }
    }
 });

$(document).on('click', ".opendialog1", function(e) {
  e.preventDefault();
  var dialogHref = $(this).data('dialog-href');
  var cssFile = $(this).data('css');
  var dialogTitle = $(this).data('dialog-title') || 'View Details';
  var dialogWidth = $(this).data('dialog-width') || 600;
  var dialogHeight = $(this).data('dialog-height') || 600;

  // Set the dialog content
  $("#dialogFrame").html('<iframe id="myIframe" src="' + dialogHref + '" width="100%" height="100%" frameborder="0"></iframe>');

  // Update dialog options
  $("#dialogFrame").dialog("option", "width", dialogWidth);
  $("#dialogFrame").dialog("option", "height", dialogHeight);
  $("#dialogFrame").dialog("option", "title", dialogTitle);

  // Open the dialog
  $("#dialogFrame").dialog("open");

  // Handle the iframe's load event
  $("#myIframe").on("load", function() {
    if (cssFile) {
      var iframeDoc = this.contentDocument || this.contentWindow.document;
      var link = iframeDoc.createElement("link");
      link.rel = "stylesheet";
      link.href = cssFile;
      iframeDoc.head.appendChild(link);
    }
  });
});

with this code

<button name="updateGallery" id="updateGallery" data-load="iframe" data-dialog-href="uploadGallery.cfm?page=about&amp;ID=15" class="main-btn warning-btn btn-hover moss opendialog1" data-dialog-title="Upload Additional Images" data-dialog-width="800" data-dialog-height="800">Upload Gallery</button>

getting an error

Uncaught TypeError: i.getClientRects is not a function

which is pointing to this:
$(“#dialogFrame”).dialog(“option”, “width”, dialogWidth);

script.js:3:20 Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

I want to submit an HTML form and have a message read depending on the value in the input and text area. However, I’m getting this TypeError telling me the event listener is null even though it’s not. Can anyone see where I went wrong?

let recommendationForm = document.getElementById("recommendationForm");

recommendationForm.addEventListener("submit", (e) => {
    e.preventDefault();

    let name = document.getElementById("name");
    let recommendation = document.getElementById("recommendation");

    if (name.value == "" || recommendation.value == "") {
        alert("Input a value in both fields!");
    } else {
        alert("Recommendation submitted successfully!");
        console.log(`${name.value} submitted their recommendation`);
    };

    name.value = "";
    recommendation.value = "";
});
<form action="" id="recommendationForm" class="recommendationSubmission">
  <input type="text" id="name" name="name" placeholder="Name" autocapitalize="on"/>
  <textarea type="text" id="recommendation" placeholder="Recommendation" rows="5" cols="45" autocapitalize="on" wrap="hard"></textarea>
  <button type="submit" id="button">Submit</button>
</form>

Converting 2 columns text file to key/value pairs, JS, NodeJS, Express

I’ve been studying Javascript for about a year and currently learning nodeJS and Express. I’m trying to resolve a test question, which involves converting a text file into key value pairs.

The provided text file looks like this (with 300 lines):

provided text file

I want a conversion that creates an array or JSON that looks, more or less, like this:

{283: 'land'}
{45: 'sun'}
{149: 'too'}
{258: 'huge'}
{161: 'dont'}`

The first column items become the keys and the second column items become the values.
This result will become a constant where I can call on the number (key) and get the word (value).

I’ve succeeded at converting to JSON with headers at the top of the columns, then removing all of the unwanted info to result in just the number and the word.

I had to edit the text file to make perfectly spaced columns and add the headers:

json_num        json_word
283             land
45              sun
149             too
258             huge
161             dont...

Here is the code I’m using:

code from VScode

And the result is roughly this:

1 design
3 all
6 skill
10 whole
15 check
21 deal
28 wish
36 visit...

This solution does not strike me as elegant in any way. I’m particularly focused on a simpler way to convert the key/value pairs from the text file, but of course I will accept any critique on the entire plan of action for the staircase exercise if you have something to share.

I’ve searched every combination of criteria I could think of to find an answer, but the key/value pairs seem to always need headers. I’m probably not using the right terminology.

Please excuse my fledgeling use of terminology and do ask for more info if I left out something critical. Thanks!

How to fix TranslateX doesn’t work on slider?


  const slider = useRef();
  let tx = 0;

  const slideForward = () => {
    if (tx > -400) {
      tx -= 100;
    }
    slider.current.style.transform = `translateX(`${tx}%`)`;
  };
  const slideBackward = () => {};

  return (
    <div className="Customers">
      <img src={nextIcon} alt="" className="nextIcon" onClick={slideForward} />
      <img src={nextIcon} className="backIcon" alt="" onClick={slideBackward} />

      {customerData.map((record) => (
        <div key={record.id} className="slider">
          <ul ref={slider}>
            <li>
              <img src={record.logo} alt={`${record.company}-Logo`} />
            </li>
          </ul>
        </div>
      ))}
    </div>
  );
};

export default Customers;

Why the slider doesn’t move and somehow when I click the button next shows only last picture?

I want the slider to move 100% each time I press the next button

Can not write data to Amazon S3

I use very simple function to write file to AWS

function writeToS3(filePath, data) {
  try {
    let s3 = new AWS.S3();
    s3.config.update({ accessKeyId: process.env.AWSACCESSKEY, secretAccessKey: process.env.AWSSECRET });
   var params = {
     Body: String(data),
     Bucket: process.env.AWSBUCKET,
     Key: filePath,
   };
   s3.upload(params, async function (err, data) {
      if (err) {
       console.error(err, err.stack);
      } else {
       console.log(`Uploading ${data}succesfully`)
       return data;
      }
   });
 } catch (ex) {
   console.error(`S3 ${filePath} error ${ex.message}.`);
   return null;
  }
}
module.exports = { readFromS3, writeToS3 };

Function working, I see ‘data’ object on debugger, but really file on bucket missing, I call this function

let Aws = require('../util/s3service')
Aws.writeToS3("/file1", "hello world")

There is successful log

Uploading [object Object]succesfully

I check file present or now with WinSCP and file missing. There is no any error, all right present, but file in bucket missing, what going wrong?

How can I reload the HTML audio player cache every time I press a button?

I have a created wav file called in.wav that is made every time the user presses a button. However, the audio play does not recognize the new in.wav until after a random amount of time. I want the audio player to refresh and check if in.wav is different.

function display(textString,keyString,modeString,instrumentString, onSuccess) {
    // ajax allows the function to take place without having to refresh webpage
    $.ajax({
    // searches for string_return in app.py
    url: "string_return",
    data: {
        text_string: textString,
        key_string : keyString,
        mode_string : modeString,
        instrument_string : instrumentString
        },
        // allows function know to return json data type and look for GET method
    dataType: "json",
        type: "GET",
        // what this does is if the ajax request is successful, it executes the specified function in
        // the parameter (in the below case, that's specified as function(returnedString))
    success: function(response) {
        onSuccess(response);
    }
    });
}
// if button with id "convert-button" is clicked...
$("#convert-button").on("click", function() {
    // textString is set to the value the user inputted in the text box
    let textString = $("#text-input").val();
    let key = $("#key").val();
    let mode = $("#mode").val();
    let inst = $("#instrument").val();
    // display method from above is called
    display(textString, key, mode, inst,function(returnedString) {
        $("#returned_string").text(returnedString);
    });

    const audio_player = document.getElementById("player");
        audio_player.load();
});

I know the audio player has reloaded when I get
10.245.100.65 - - [27/Apr/2024 17:13:01] "GET /static/in.wav HTTP/1.1" 206 - in my flask app. So again, how can I trigger this audio player reload?

I tried to implement the .load() function but it dont think it works it would not reload the new audio file.

Creating a 1:1 ratio element, centered within another element

I am attempting to create some rectangular boxes with circular (not ovular) boxes inside those. Currently the behaviour I’m getting is this:three rectangle with ovals inside spanning the whole area of the rectangle they're inside of
Whereas the behaviour I was expecting was circles (i.e. 1:1 aspect ratio). My code for this is as follows:

#portals {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}

.portal {
    display: flex;
    justify-content: center;
    width: 30%;
    border-radius: 1rem;
    background-color: aqua;
    height:50rem;
    margin:1rem
}

.portal-icon {
    aspect-ratio: 1 / 1;
    width:90%;
    border-radius: 50%;
    background-color: white;
    margin:1rem
}
```
<div id="portals">
    <div class="portal" id="art" style="background-color: #ce87e8;">
        <div class="portal-icon" id="art"></div>
    </div>
    <div class="portal" id="code" style="background-color: #87c8e8;">
        <div class="portal-icon" id="code"></div>
    </div>
    <div class="portal" id="projects" style="background-color: #e89f87;">
        <div class="portal-icon" id="projects"></div>
    </div>
</div>

I was under the impression, looking at other similar questions, that aspect-ratio was the correct way of achieving this using modern browsers, but it doesn’t seem to function for me all the while I’m using flex boxes, as soon as I swap back to standard boxes the circles function, but I’m then unable to get the circles centered in the boxes.

I have also read about using the padding-bottom trick, but it doesn’t have any effect at all. On top of this, I have read some answers stating that using percentages in that property do not function and should not be used, or that it is antiquated and aspect ratio should be used instead.

Basically I’m at a loss for what to do because seemingly the only two available methods contradict each other (from what I can see) on which should be used, yet neither of them are working for me.

I have also seen some mentions of it being possible to achieve this behaviour using JS, however I have 0 experience with this, so if I could be pointed in the right direction on how I might go about writing a script to do that should CSS not be possible, that would be great.

Thank you in advance.