How to change CSS classes and style for nav tabs after bslib nav_insert?

Currently for the bslib package, a nav_insert() into a page_navbar does not pass along the same CSS classes as it does for a regular tab-pane, as noted in this issue posted to the bslib Github repo.

The reprex provided by the OP is the following:

library(shiny)
library(bslib)

ui <- page_navbar(
  id = 'nav',
  nav_panel('Page 1',
            card("Content 1")))

server <- function(input, output, session) {
  nav_insert(id = "nav",
             nav = nav_panel('Page 2',
                             card("Content 2")))
}

shinyApp(ui, server)

The newly inserted tab “Page 2” does not have the same css classes as the “Page 1” tab, namely html-fill-item html-fill-container bslib-gap-spacing.

Is there a way, perhaps, to add those classes after the insert? I tried using runjs($('[data-value=Page 1]').addClass('html-fill-item')) (and several iterations of it) in the server but that did not work.

A very trivial JSFiddle demo shows the idea of the basic working syntax.

Any ideas would be very much appreciated! Thanks.

how to fix the error that show index.html:1 Uncaught SyntaxError: Unexpected token ‘%’

index.html:1 Uncaught SyntaxError: Unexpected token ‘%’ (at index.html:1:14)

this error show when i change this code

function templateComment(item, postInfo, conditionComment) {
  console.log(conditionComment)
  const comm = `
    <div class="comment pb-1" onclick=${!conditionComment ? `showUserInfo(${encodeURIComponent(JSON.stringify(postInfo))})` : 'showUserInfo(null)'}>
          <div class="pt-1 flex align-items-center justify-content-center gap-3 pb-1">
          ${typeof item.author.profile_image === "string" ?
      `<img src="${item.author.profile_image}" alt="Avatar1" class="img-fluid my-1" style="width: 30px; height: 30px; border-radius: 50% !important;" />`
      :
      `<img src="images/icons8-user-48.png" alt="Avatar2" class="img-fluid my-1" style="width: 30px; height: 30px; border-radius: 50% !important;" />`
    }                     
          <span><strong>@${item.author.username}</strong></span>
          </div>
          <h5>${item.body}</h5>
        </div>
      `;
  return comm;
}
export default templateComment;
 <div class="comment pb-1" onclick=${!conditionComment ? `showUserInfo(${encodeURIComponent(JSON.stringify(postInfo))})` : 'showUserInfo(null)'}>

the error come when i change this line

so what this error mean and how to slove this error ??

How to call Delphi Procedure from JavaScript code in TMS WEB Core?

I want to call/execute a Delphi procedure via my JavaScript code, but I’m not sure how.

I have my procedure declared as a public procedure within my form’s class declaration like this:

TfrmMain = class(TWebForm)
  ...
private
  { Private declarations }
public
  { Public declarations }
  procedure MyDelphiProcedure(MyParam: UInt64);
end;

And then somewhere on my web page, I have an HTML Image with an onClick event attached to it. I’d like to call my Delphi function from that onClick event, but how? This HTML image is not linked to any Delphi component. It’s just a standalone HTML image that is dynamically created using JavaScript.

Just simply doing MyDelphiProcedure(1); fails. Doing this.MyDelphiProcedure(1); also fails.

How can I access my form and call the Delphi function from JavaScript?

generateStaticParams unexpected returns

I’m trying to generate slugs using generateStaticParams in Next but it somehow “chooses” diferent data to return that I want it to.

function generateSlugs(params) return array of slug objects each containing slug and id.

My problem is that generateStaticParams uses id as slug in returned values instead of slug. What could be wrong?

import Gallery from "@/app/components/Gallery";
import ProductDescription from "@/app/components/ProductDescription";
import Navbar from "@/app/layout/Navbar";
import ProductSection from "@/app/layout/ProductSection";
import Products from "@/app/layout/Products";
import { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { Slug } from "@/app/types/types";
import { ProductPage } from "@/app/types/types";
import { getData } from "@/app/utils/getData";
import generateSlugs from "@/app/utils/generateSlugs";

export const preferredRegion = ["fra1"];
export const dynamic = "force-dynamic";

export async function generateStaticParams() {
  const params = await fetch(`${process.env.API_URL}/api/auctions`).then(
    (res) => res.json()
  );

  const slugs = generateSlugs(params);

  return slugs.map((slug: Slug) => ({
    slug: slug.slug,
  }));
}

export async function generateMetadata(
  { params }: { params: Slug },
  parent: ResolvingMetadata
): Promise<Metadata> {
  console.log(params);

  const product = await getData(params);
  const url = "https://noanzo.pl";
  return {
    title: `${product[0]?.title} - noanzo.pl`,
    description: product[0]?.description,
    robots: "index, follow",
    alternates: {
      canonical: `${url}/produkt/${params.slug}`,
    },
    openGraph: {
      title: `${product[0]?.title} - noanzo.pl`,
      description: product[0]?.description,
      locale: "pl",
      images: [
        {
          url: (() => {
            const link = product[0]?.image.filter(
              (item: any) => item.thumbnail === true
            );
            if (!product[0]) {
              notFound();
            }
            if (link[0]?.url) {
              return link[0].url;
            } else {
              return product[0].image[0].url;
            }
          })(),
          alt: product[0]?.title,
        },
      ],
    },
  };
}

export default async function Page({ params }: { params: Slug }) {
  const data = await getData(params);
  if (!data || data[0] === null) {
    notFound();
  }
  const product: ProductPage = {
    title: data[0].title,
    description: data[0].description,
    price: data[0].price,
    image: data[0].image,
    imageLarge: data[0].imageLarge,
  };

  return (
    <main>
      <Navbar />
      <div className='container mx-auto sm:w-4/5 lg:w-11/12 xl:sm:w-4/5 p-2'>
        <ProductSection>
          <Gallery product={product} />
          <ProductDescription product={product} />
        </ProductSection>
      </div>
      <Products />
    </main>
  );
}

When i try something like this:

export async function generateStaticParams() {
  const params = await fetch(`${process.env.API_URL}/api/auctions`).then(
    (res) => res.json()
  );

  return params.map((slug: Slug) => ({
    slug: slug.slug,
  }));
}

Above code works and returns id’s of each item returned from api as slug. How does it “decide” to choose “id” instead of eg. “title” which is also in my data:

Here’s link to my data: api link

How to capture audio realtime in browser?

I’m interested in capturing audio from Google Meet calls and performing real-time transcription using an API within my browser extension app. While I’m aware of WebRTC as a potential solution, I’m still don’t understand how to implement it. Could someone provide guidance on how to utilize WebRTC for this purpose or something similar.

Please, bear with me and thanks in advance!!

Javascript base64 image url replaces all “” for spaces?

I am loosing my mind! Why is the browser stripping all of the in my base64 data?

I log the data and it has them before I put the url into the element but, then it looks like this (with spaces instead of ‘s)

enter image description here

        $('#content').append(`
          <div id="pool_${cc}" class="pool" style="position:relative;top:0px;left:0px;width:100%;right:0px;margin-top:${n == 0 ? '15' : '25'}px;">
            <div class="black win" style="position:relative;top:0px;left:0px;width:100%;right:0px;height:100px;background:#000000a6;">
              <div class="coin" id="cc_${cc}" style="position:absolute;top:25px;left:-25px;width:50px;height:50px;background-image:url(${r.cc[cc]});background-repeat:no-repeat;background-size:50px auto;background-position:center;"></div>
              <div style="position:absolute;top:8px;left:40px;line-height:28px;width:calc(100% - 155px);">
                <b>
                  ${(cc == r.coin ? `<b style="color:#00a2e3;font-family:black;font-style:italic;margin-right:4px;"><i class="fas fa-caret-right" style="font-style:italic;"></i><i class="fas fa-caret-right" style="font-style:italic;"></i> ${cc.toUpperCase()}</b>` : cc.toUpperCase())}
                </b>
                <div style="font-size:10px;">
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">version:</span> 0.0.1</div> 
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">Date:</span> Thu Mar 07 2024 15:11:48</div>
                  <div style="display:inline-block;margin-right:10px;"><span style="opacity:0.5;">Proven:</span> ${!undetermined}</div>
                </div>
              </div>
              <div class="switchCoin btn1" style="color:#cccccc;background:#00000038;right:15px;">SWITCH</div>
              ${undetermined && `<div class="deleteCoin btn1" style="color:#cccccc;background:#00000038;right:65px;">DELETE</div>`}
            </div>
          </div>`
        );

This Works fine: $('#cc_' + cc).css('backgroundImage', 'url(' + r.cc[cc] + ')'); so do the special quotes mess it up?

Programming Basics – JavaScript [closed]

I am trying to solve this task:

Movie Stars

The accountant of the “Star City” cinema center hires you to write a program that calculates the salaries of the actors. Each production has a budget for actors. Until the “ACTION” command is given, you will receive the name of the actor and their salary. If the actor’s name is longer than 15 characters, their salary will be 20% of the remaining budget at that point. If the budget runs out at any point, the program should stop.

Input

First, read one line from the console:

  • Budget for actors – a floating-point number in the range [1000.0… 2 100 000.0]

Then one or two lines are read repeatedly until the command “ACTION” or until the budget runs out:

  • Actor’s name – a string

If the actor name contains less than or equal to 15 characters:

  • Salary – a floating-point number in the range [250.0… 1 000 000.0]

Output

Print one line on the console:

  • If the budget is enough:

    "We are left with {budget left} USD."
    
  • If the budget is NOT enough:

    "We need {budget needed} USD for our actors."
    

The result must be formatted to the second digit after the decimal point!

This is the code I wrote:

function solve(input) {
  let budget = Number(input.shift());
  let totalSalary = 0;

  while (input.length > 0 && input[0] !== "ACTION") {
    let actorName = input.shift();
    let actorSalary = Number(input.shift());

    if (actorName.length > 15) {
      actorSalary = budget * 0.2;
    }

    if (budget >= actorSalary) {
      budget -= actorSalary;
      totalSalary += actorSalary;
    } else {
      let budgetNeeded = actorSalary - budget;
      console.log(`We need ${budgetNeeded.toFixed(2)} USD for our actors.`);
      return;
    }
  }

  console.log(`We are left with ${budget.toFixed(2)} USD.`);
}

It only passes 60/100 tests. What is my mistake?

javascript function changes when used with jakarta ee

I am starting my long and bumpy road to move website from shit i made 20 years ago to Jakarta ee backend, mysql and html javascript frontend. Have some success with java, but problems in javascript.

In my JSP I have javascript function to make thumbnails (chatgpt helped me):

// Generate thumbnails and add click event listeners
                imageData.forEach((data, index) => {
                    const thumbnail = document.createElement('div');
                    thumbnail.classList.add('thumbnail');
                    thumbnail.innerHTML = `<img src="${data.url}" alt="Thumbnail ${index + 1}">`;
                    thumbnail.addEventListener('click', () => displayImage(index));
                    galleryContainer.appendChild(thumbnail);
                });

Localy it works fine, but when it comes back from tomcat fifth line is truncated:

                // Generate thumbnails and add click event listeners
                imageData.forEach((data, index) => {
                    const thumbnail = document.createElement('div');
                    thumbnail.classList.add('thumbnail');
                    thumbnail.innerHTML = `<img src="" alt="Thumbnail 1">`;
                    thumbnail.addEventListener('click', () => displayImage(index));
                    galleryContainer.appendChild(thumbnail);
                });

what could be wrong and how to avoid it?

I expected that jsp content would be the same, only with added image list (which works fine).

JavaScript: Object.keys() as part of a function

I´ve searched for a solution all afternoon. First I was enthusiastic but now I´m just annoid.
Maybe you can help me. Maybe there is no solution.

If you want to get the “name” of a variable you simply can use Object.keys().

const myFirstName = 'John';
console.log(myFirstName);
console.log(Object.keys({myFirstName})[0]);

BUT if you want to write a function and use the variable as the parameter,
this solution does not work anymore.

function hfr_log(variable)
{
    let tmp_variable = variable;
    let tmp_s_variable_name = Object.keys({variable})[0];
    let tmp_variable_content = variable;

    console.log(`tmp_variable = '${tmp_variable}'`);
    console.log(`tmp_s_variable_name = '${tmp_s_variable_name}'`);
    console.log(`tmp_variable_content = ${tmp_variable_content}`);
}

I’ve tried several approaches on how to pass the variable, but I’m running out of ideas.
Is it even possible?

Sorry for the beginner question, but I’m afraid I’m a beginner. :/

In any case, thank you very much for your time and your suggestions! 🙂

How to use react router?

Hi i am building web page in react and i need to add onclick function to my button that have simpel if else statment that in the en will open main.js. But i dont understand how react router is working can someone helt?

App.js

import { useState } from "react"
import { BrowserRouter, Link, Routes, useNavigate } from "react-router-dom";
import Main from "./main.js";

export default function App() {
  const navigate = useNavigate();
  const [inpty, setFull] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (inpty.trim().length === 0) {
      alert("Please input your name to continue");
    } else {
      <Routes>
        <Link to={<Main/>}/>
      </Routes>
    }
  }
  return (
    <section className="grid grid-cols-1">
      <div className=" h-screen w-screen fixed bg-gradient-to-r from-violet-500 to-blue-500 bg-cover">
        <h1 className="text-center bg-black text-white">Hi! If you want to support me you can allways check out my <a href="https://www.buymeacoffee.com/HTNR" className="text-[#FFDD00]">"Buy me some coffe"</a>. Thank you!</h1>
        <h1 className="font-customFont1 text-white text-xl mt-3 ml-3 smallP:text-lg mP:text-2xl tP:text-2xl tL:text-2xl sL:text-3xl mL:text-3xl lP:text-3xl">ZenZone</h1>
        <div className="h-screen flex items-center justify-center">
          <div className="grid-cols-1 grid bg-neutral-500 w-[40%] h-[30%] text-center bg-opacity-25 absolute rounded-2xl smallP:w-[60%] smallP:h-[40%] mP:w-[50%] mP:h-[40%] tP:w-[40%] tP:h-[40%] tL:w-[40%] tL:h-[40%] sL:w-[30%] sL:h-[40%] mL:w-[25%] mL:h-[40%] lP:w-[25%] lP:h-[40%]">
            <h1 className="font-roboto text-[#F8F7F4] smallP:mt-7 smallP:text-lg smallP:font-bold mP:text-xl mP:font-bold mP:mt-5 tP:text-2xl tP:font-bold tP:mt-7 tL:text-3xl tL:font-bold tL:mt-6 sL:text-3xl sL:font-bold sL:mt-4 mL:text-3xl mL:font-bold mL:mt-4 lP:text-3xl lP:font-bold lP:mt-4">Feel home</h1>
            <h1 className="font-robot text-[#F8F7F4] smallP:mt-5 smallP:font-bold smallP:text-lg mP:text-xl mP:font-bold mP:mt-3 tP:text-xl tP:font-bold tL:text-2xl tL:font-bold tL:-mt-2 sL:text-2xl sL:font-bold sL:-mt-4 mL:text-2xl mL:font-bold mL:-mt-3 lP:text-2xl lP:font-bold lP:-mt-3">Let's start with your name</h1>
            <div className="flex items-center justify-center">
              <div className="relative">
                <input
                  type="text"
                  value={inpty}
                  onChange={e => setFull(e.target.value)}
                  placeholder="Carlos Hill"
                  className="border-b border-gray-300 py-1 focus:border-b-2 focus:border-blue-700 transition-colors focus:outline-none peer bg-inherit smallP:w-32 smallP:text-lg text-white smallP:mt-5 mP:w-44 mP:text-xl mP:mt-5 tP:w-52 tP:text-xl tL:w-60 tL:text-xl sL:w-64 sL:text-xl sL:-mt-4 mL:w-60 mL:text-xl lP:w-60 lP:text-xl lP:-mt-4"
                />
              </div>
            </div>
            <div className="justify-center items-center place-content-center place-items-center">
              <button onClick={handleSubmit} className="w-40 h-12 bg-white cursor-pointer rounded-3xl border-2 border-[#9748FF] shadow-[inset_0px_-2px_0px_1px_#9748FF] group hover:bg-[#9748FF] transition duration-300 ease-in-out
                        smallP:mt-5 smallP:w-28 smallP:h-9 mP:mt-5 mP:w-40 mP:h-12 mP:text-base tP:mt-5">
                <span className="font-medium text-[#333] group-hover:text-white">Continue</span>
              </button>
            </div>
            <button className="smallP:text-base smallP:mt-20 smallP:text-white mP:mt-24 mP:text-white mP:text-base tP:text-white tL:text-white sL:text-white mL:text-white lP:text-white">Continue as Friende</button>
          </div>
        </div>
      </div>
    </section>
  )
}

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';

import './index.css';
import App from './App';
import Main from './main';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
    </BrowserRouter>
);

I have tried to find information everywhere and trie it out but it doest work i even tried chatGpt, blackbox and Tabnin but nothing works

Issue deploying to Render

I have been struggling to deploy to render.

Error: ENOENT: no such file or directory, stat ‘/opt/render/project/src/client/dist/index.html’

My client/dist/index.html does exist but I believe it is not being built properly on Render as it works fine locally.

root package.json =

“scripts”: {
“start”: “node server/server.js”,
“develop”: “concurrently “cd server && npm run watch” “cd client && npm run dev””,
“install”: “cd server && npm i && cd ../client && npm i”,
“build”: “cd client && npm run build”,
“render-build”:”npm install && npm run build”
},

server.js =

if (process.env.NODE_ENV === ‘production’) {
app.use(express.static(path.join(__dirname, ‘../client/dist’)));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../client/dist/index.html'));
});

}

Error: Unsupported schema version (v4 only)

I installed “json-schema-faker” (and then grunt and grunt-cli)

and I took a default schema from this site: https://jsonschema.net/ ; and put in the following file:

`var jsf = require("json-schema-faker");

const schema = {
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "http://example.com/example.json",
    "title": "Root Schema",
    "type": "object",
    "default": {},
    "required": [
        "checked",
        "dimensions",
        "id",
        "name",
        "price",
        "tags"
    ],
    "properties": {
        "checked": {
            "title": "The checked Schema",
            "type": "boolean",
            "default": false
        },
        "dimensions": {
            "title": "The dimensions Schema",
            "type": "object",
            "default": {},
            "required": [
                "width",
                "height"
            ],
            "properties": {
                "width": {
                    "title": "The width Schema",
                    "type": "integer",
                    "default": 0
                },
                "height": {
                    "title": "The height Schema",
                    "type": "integer",
                    "default": 0
                }
            }
        },
        "id": {
            "title": "The id Schema",
            "type": "integer",
            "default": 0
        },
        "name": {
            "title": "The name Schema",
            "type": "string",
            "default": ""
        },
        "price": {
            "title": "The price Schema",
            "type": "number",
            "default": 0.0
        },
        "tags": {
            "title": "The tags Schema",
            "type": "array",
            "default": [],
            "items": {
                "title": "A Schema",
                "type": "string"
            }
        }
    }
}
  

var sample = jsf(schema);
console.log(sample);`

However when I execute it (node filename.js), I get an error:
Error: Unsupported schema version (v4 only)
at Object.module.exports [as normalizeSchema] (C:UsersnillaDesktopjson-fakernode_modulesdereflibutilnormalize-schema.js:53:11)

Generally it works and I guess even worked. But after I installed grunt or grunt-cli or grunt-init, it stopped working and I don’t know how to change it to v4. On the web-site mentioned above it’s possible to change version to “draft 4” or “draft 7”, but I did not help.

Do you know how to change json schema to v4?

I executed the file with “node filename.js” and a json should have been printed to the console, but now it gives me the error.

Making a regexp to retrieve href/src of html tags

Im trying to get the href from links and src from script tags.
Since it’s my first time using regex, im isuing quite not enough understand on how groups, negation and conditional selection works.

This is what i’ve got so far

(/|./)((^([http|https]://))*.*?w+)([a-zA-Z]w+)(?=.(js|css|ts)b)(.*?w+)

Working in this cases:

<script src="./script.js"/>
<script src="/script.js"/>
<script src="/my/custom/dir/script.js"/>
<!--Theme same for links-->

Non functioning cases:

<script src="https://my.cdn.fav/script.js"/>
<script src="http://my.cdn.fav/script.js"/>

Or well it does consider the starting http and https but doesnt select them.
It’s this part that is doing something wrong (/|./)((^([http|https]://))

Issue with Fetch Request in a TypeScript react app

I am developing a react app and encountering an issue with a fetch request in my TypeScript file. The app is supposed to send a POST request to a Flask server running on localhost:5000. However, when I include the fetch request within a try-catch block inside a method of a class, the extension’s webpage fails to render any elements, and there are no errors logged in the console.

Here is the relevant code snippet, showing the location of the method within the class:



import fetch from 'node-fetch';

class InfoProvider implements Disposable {
  // Other class properties and methods...

  private async sendProofState(proofState: string) {
    try {
      const response = await fetch('http://localhost:5000/api/generate_tactics', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ proof_state: proofState })
      });
      const data = await response.json();
      console.log("Response from Flask server:", data);
    } catch (error) {
      console.error("Error sending data to Flask server:", error);
    }
  }
//other methods
}

The issue seems to be specifically related to the fetch request, as commenting out this block allows the webpage to render correctly. I have confirmed that CORS is enabled on the server, and the server is running without issues.I even commented the line where the function is called and the issue persisted.