How can I load external data in React SSR

I’m new to React and I’m making React SSR page. Perfectly working (it’s almost stastic page yet but use JSON datas). Why I can’t here use in my compoment Suspense why I’ve load JSON data?

import React, { Suspense, useEffect, useState } from 'react';
import './interfaces/types';

interface ProductProperties {
    [key: string]: {
        title: string;
        comments: {
            comment1: string;
            comment2: string;
            comment3: string;
            comment4: string;
            comment5: string;
        };
    };
}

interface ProductPropertyProps {
    id: string;
    rating: number;
    comment?: string;
}

const ProductProperty: React.FC<ProductPropertyProps> = ({ id, rating, comment }) => {
    const [property, setProperty] = useState<ProductProperties | null>(null);

    useEffect(() => {
        import('../../data/productProperties.json')
            .then((json) => {
                setProperty(json.default);
            })
            .catch((error) => {
                console.error("Failed to load JSON file:", error);
            });
    }, []);

    if (property === undefined) {
        return null; // Or return a loading spinner or placeholder
    }

    if (!property) {
        return null; // Or return a loading spinner or placeholder
    }

    const propertyDefinition = property[id];

    // TODO: Handle the case when the property definition is not found
    if (!propertyDefinition) {
        console.error(`No property definition found for id ${id}`);
        return null; // Or return a default value or error message
    }

    const title = propertyDefinition.title;
    // Použitie vlastného komentára ak je k dispozícii, inak použitie predvoleného z definície
    const finalComment = comment || ((propertyDefinition.comments as unknown) as { [key: string]: string })[`comment${rating}`];

    return (
        <Suspense fallback={<div>Loading...</div>}>
            <div className="product-property">
                <div className="product-property-title">{title}</div>
                <div className="product-property-rating">
                    {[...Array(5)].map((_, index) => (
                        <i key={index} className={`star star-${index < rating ? 'filled' : 'outline'}`}></i>
                    ))}
                </div>
                <div className="product-property-comment">{finalComment}</div>
            </div>
        </Suspense>
    );
}

export default ProductProperty;

But in App.tsx I can use it

// App.tsx
import React, { Suspense } from 'react';
import Product from './components/product/Product';
import productData from './data/productData.json';

const App: React.FC = () => {

  // This will be used later if we want to update the product data
  //const [productDataState, setProductData] = useState<ProductData[]>(productData);

  return (
    <>
      {productData.map((product) => (
        // Title of product must be unique and therefore can be used as key
        <Suspense key={product.title} fallback={
          <div className='product-container-fallback'>
            <div>Nahrhráva sa produkt. Prosíme chvíľu strpenia</div>
          </div>
        }>
          <button style={{ border: 'none', background: 'none', padding: 0, margin: 0 }}>
            <Product productInfo={product} />
          </button>
        </Suspense >
      ))
      }
    </>
  );
};

export default App;

It’s some possible? I know that Vite SSR has some limitations yet, but code is so nice generated…

Or…. The page it’s working but I have error in browser console:

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Or

Warning: An error occurred during hydration. The server HTML was replaced with client content in .

Thanks for any advice

How do I prevent the use of mocks on certain tests but use it on others?

I have written three Jest unit tests and I am mocking a function. This mock is used for two unit tests but my third one fails since it needs to access the real code. If I comment out the mock, then the first two tests fail and third one passes. I tried using beforeAll and beforeEach methods where I disable the mock only for the third test but haven’t had any success. I’d appreciate any help!

ReactErrorBoundary.tsx:

import { render, act, fireEvent } from '@testing-library/react';
import ReactErrorBoundary from '../../components/ReactErrorBoundary';
import { ErrorBoundary } from 'react-error-boundary';
import { logger } from '../../services/logService';

jest.mock('../../services/logService', () => ({
  logger: jest.fn(),
}));

jest.mock('react-error-boundary', () => {
  const ErrorPage = require('../../components/ErrorPage').default;

  return {
    ...jest.requireActual('react-error-boundary'),
    ErrorBoundary: jest.fn(({ onError, onReset, FallbackComponent }) => {
      onError && onError(new Error());
      onReset && onReset();

      return {
        FallbackComponent: ErrorPage,
      };
    }),
  };
});

describe('ReactErrorBoundary with mocked ErrorBoundary', () => {
  beforeAll(() => {
    jest.mock('react-error-boundary', () => {
      const ErrorPage = require('../../components/ErrorPage').default;

      return {
        ...jest.requireActual('react-error-boundary'),
        ErrorBoundary: jest.fn(({ onError, onReset, FallbackComponent }) => {
          onError && onError(new Error());
          onReset && onReset();

          return {
            FallbackComponent: ErrorPage,
          };
        }),
      };
    });
  });

  test('renders ErrorBoundary with ErrorPage as FallbackComponent', () => {
    render(<ReactErrorBoundary />);
    expect(ErrorBoundary).toHaveBeenCalledWith({
        FallbackComponent: expect.any(Function),
        onError: expect.any(Function),
        onReset: expect.any(Function),
        children: undefined,
      }, {});            
  });

  test('passes children to ErrorBoundary', () => {
    const children = <div>Hello World</div>;

    render(<ReactErrorBoundary>{children}</ReactErrorBoundary>);
    expect(ErrorBoundary).toHaveBeenCalledWith({
      FallbackComponent: expect.any(Function),
      onError: expect.any(Function),
      onReset: expect.any(Function),
      children: <div>Hello World</div>,
    }, {});  
  });
});

describe('ReactErrorBoundary without mocked ErrorBoundary', () => {
  beforeAll(() => {
    jest.unmock('react-error-boundary');
  });

  test('logs error message when onError is triggered', () => {
    const spy = jest.spyOn(console, 'log').mockImplementation();

    render(
      <ReactErrorBoundary>
        <ChildComponentWithError />
      </ReactErrorBoundary>
    );

    expect(spy).toBeCalledTimes(1);
    expect(spy).toHaveBeenCalledWith('Error caught!');

    expect(logger).toBeCalledTimes(1);
    expect(logger).toHaveBeenCalledWith(expect.any(Error));

    spy.mockRestore();
  });
});

const ChildComponentWithError = () => {
  throw new Error('Test Error');
};

No response when using formidable in Next.js

What I am trying to do is upload a file from the front end to my GCP workflow, and it properly does this, however I keep encountering the API resolved without sending a response issue. I tried placing the form.parse() inside a Promise, however that also does not effectively return a response for me. The part that’s even more confusing for me is I console log the response on the front end, and it properly shows the response if it’s succesful. Below is my current code:

export const config = {
  api: {
    bodyParser: false
  }
}

export default async function handler(req, res) {
  const { query: { uuid } } = req
  const token = await getToken({ req })
  const key = JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS.toString())

  if (!token) {
    return res.status(401).json({ error: 'User must be logged in to perform this action' })
  }

  const storage = new Storage({
    projectId: process.env.PROJECT_ID,
    credentials: {
      client_email: key.client_email,
      private_key: key.private_key.replace(/\n/g, 'n')
    }
  })

  const form = formidable({
    keepExtensions: true,
  })

  form.parse(req, async (error, fields, files) => {
    if (error) {
      console.error(`Error parsing form: ${error}`);
      return res.status(500).json({ error: 'Error parsing form' });
    }

    const selectedFile = files.file[0];
    if (!selectedFile) {
      console.error('No file uploaded')
      return res.status(400).json({ error: 'No file uploaded' })
    }

    const salt = crypto.randomBytes(16).toString('hex')
    const hashedFilename = crypto.createHash('sha256').update(selectedFile.originalFilename + salt).digest('hex')

    const bucket = storage.bucket(process.env.CLOUD_STORAGE_BUCKET_NAME)
    const blob = bucket.file(hashedFilename)

    const blobStream = createReadStream(selectedFile.filepath)
      .pipe(blob.createWriteStream({
        resumable: false,
        contentType: selectedFile.mimetype
      }))

    blobStream.on('error', (error) => {
      console.error(`Error uploading files to cloud storage: ${error}`)
      cleanupStreams(blobStream, selectedFile.filepath)
      return res.status(500).json({ error: 'Error uploading files to cloud storage' })
    })

    blobStream.on('finish', async () => {
      try {
        await blob.setMetadata({
          metadata: {
            UUID: uuid,
            FILE_NAME: selectedFile.originalFilename,
            CREATION_DATE: getDate(),
          }
        })

        cleanupStreams(blobStream, selectedFile.filepath)
        return res.status(201).json({ message: `Uploaded the file successfully: ${selectedFile.newFilename}` })
      } catch (error) {
        console.error(`Error setting metadata: ${error}`)
        cleanupStreams(blobStream, selectedFile.filepath)
        return res.status(500).json({ error: 'Error setting metadata' })
      }
    })
  })

  form.on('error', (error) => {
    console.error(`Form parsing error: ${error}`)
    return res.status(500).json({ error: 'Error processing form data' })
  })
}

Javascript List, Select default Items

I am trying to modify some code to better work for my needs.

It’s a list prompt that takes a text list from Keyboard Maestro and presents it to the user. The user then clicks the options they want.

Sometimes I need certain items in the list to be ‘selected’ when the list is presented. If the text items in the list have a suffix with |0|1 at the end then the item SHOULD NOT be selected. If the text items in the list have a suffix with |1|0 then the item SHOULD be selected.

Ex.

Test One|1|0

Test Two|0|1

Only “Test One” and “Test Two” should be displayed, but the |1|0 or |0|1 will tell the script to pre-select the list item or not.

I’m just trying to figure out what specific Javascript For Loop I need to add to the function init().

Here is the just some of the code, it should be the relevant bits:

// Create a reference to KeyboardMaestro, this helps avoid unnecessary global scope pollution
var KeyboardMaestro = window.KeyboardMaestro;

// Initialize an array to keep track of indices of selected items
var selectedIndices = [];

// Initialize an array to hold the selected items themselves
var selectedItems = [];

// A flag to determine if an item is currently being dragged
var isDragging = false;

// A flag to determine if an item is being marked or selected
var marking = false;

/**
 * Toggle the selection of a given item.
 * @param {HTMLElement} item - The list item to select or unselect.
 * @param {boolean} shouldSelect - Explicit instruction to select (true) or unselect (false). If undefined, toggle.
 */
function selectItem(item, shouldSelect) {
    // Convert the NodeList of 'li' elements to an array and get the index of the provided item
    var itemIndex = Array.from(document.querySelectorAll('li')).indexOf(item);

    // Check if the item's index is already in the selectedIndices array
    var index = selectedIndices.indexOf(itemIndex);

    if (index > -1) {
        // If the item is already selected
        if (shouldSelect !== true) {
            // If the function was called with explicit instruction not to select, remove the item from selections
            selectedIndices.splice(index, 1);
            item.firstChild.checked = false; // Uncheck the checkbox associated with the item
        }
    } else {
        // If the item is not currently selected
        if (shouldSelect !== false) {
            // If the function was called without explicit instruction to unselect, add the item to selections
            selectedIndices.push(itemIndex);
            item.firstChild.checked = true; // Check the checkbox associated with the item
        }
    }
    
    // Focus on the input element of type text, likely for further user input or interactions
    document.querySelector('input[type="text"]').focus();

    // Highlight the clicked item for visual feedback
    var selectedItem = document.querySelector('li.selected');
    if (selectedItem) {
        // If an item is already highlighted, remove the 'selected' class
        selectedItem.classList.remove('selected');
    }
    // Add the 'selected' class to the current item
    item.classList.add('selected');
}

/**
 * Initializes the application, sets up the list based on the KeyboardMaestro variables, and attaches event listeners.
 */
function init() {
    // Start with no initial selected item.
    window.selectedItemStart = null;

    // Process each line from the KeyboardMaestro prompt list variable.
    var promptList = KeyboardMaestro.GetVariable('Local__Prompt List').split('n');
    for (var i = 0; i < promptList.length; i++) {
        var parts = promptList[i].split('__'); // Split each line at '__'
        
        // Create new list item and checkbox elements.
        var li = document.createElement('li');
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.disabled = true; // Make sure checkbox is not interactive.
        li.appendChild(checkbox);

        // Add a space after the checkbox.
        var space = document.createTextNode(' '); 
        li.appendChild(space);

        // If '__' is present in the line, use the part after for display and store the part before in a data attribute.
        // If not, use the whole line for both display and output.
        var text;
        if (parts[1]) {
            text = document.createTextNode(parts[1]);
            li.dataset.fullText = parts[0];
        } else {
            text = document.createTextNode(parts[0]);
            li.dataset.fullText = parts[0];
        }
        li.appendChild(text);

        // Add the created list item to the list.
        list.appendChild(li);
    }

    // Mark the first item in the list as selected.
    list.firstChild.classList.add('selected');
    
}

So far it looks like I need something like:

selectItem(li, true);

Any help is much appreciated.

ESlint Plugin That Enforces Function Parameter Names

I am looking for an ESlint plugin that can enforce function parameter names with a regex in javascript. e.g: ^my[A-Z].

e.g:

const doSomething = (myUserInput) => {} // Ok 

const doSomethingWrong = (userInput) => {} // Wrong, param should has a prefix "my"

I saw that typescript-eslint has an option to do it. However, my project is mainly in JS and only use eslint. https://typescript-eslint.io/rules/naming-convention/. The other option would be to write a custom elsint which would be my last resource.

Table input values to DB

So I have a JS script that adds a and it’s relevant which also adds name depending on how many table data there are.

var newRowHtml = '<tr>' +
'<td><input type="text" name="pds_4_input_'+count[0]+'" class="underline_input"></td>' +
'<td><input type="text" name="pds_4_input_'+count[1]+'" class="underline_input"></td>' +
'<td><input type="date" name="pds_4_input_'+count[2]+'" class="underline_input"></td>' +
'</tr>';

table.append(newRowHtml);

Resulting in something like this (these ones however are default, so adding one would result in pds_4_input_4 and so on…):

<tr>
   <td><input type="text" name="pds_4_input_1" placeholder="Apple"></td>
   <td><input type="text" name="pds_4_input_2" placeholder="Banana"></td>
   <td><input type="text" name="pds_4_input_3" placeholder="Cranberry"></td>
</tr>

And I have already built the simple php code to bind those input values into my db and it works.

<?php
    session_start();
    require 'connection.php';

    function dataToPDS4($mysqli) {
        $input0 = $_SESSION['pds_id'];
        $input1 = $_POST['pds_4_input_1'];
        $input2 = $_POST['pds_4_input_2'];
        $input3 = $_POST['pds_4_input_3'];

        $sql = "INSERT INTO pds_4 (accID, Apple, Banana, Cranberry)
                VALUES (?, ?, ?, ?)";
        $stmt= $mysqli->prepare($sql);
        $stmt->bind_param("isss", $input0, $input1, $input2, $input3);
        $stmt->execute();
        $stmt->close();
    }
?>

Now, I have to figure out a way to bind the new parameters after pds_4_input_3 brought unto by JS script.

I tried using arrays to bind them in PHP however it seems it doesn’t quite work (?) and stupid little me didn’t save the code so I can’t post it here so; sorry about that.

I’m expecting to just get a link to a video/tutorial or thread that would allow me to save the added table rows and table data. If someone is willing to share part of a code for me to solve as well that’d be swell as well.

That said, thank you in advance and have a good day!

Edit: Forgot to edit bind_param types.
Edit 2: Edited the values placeholders in $sql.

Is Observable’s “viewof” really an operator?

I’m confused by Observable’s use of the word “operator” in their documentation, and wondering whether they have misused it, or I’m simply not understanding.

Observable has a special viewof operator which lets you define interactive values. A view is a cell with two faces: its user interface, and its programmatic value.

viewof text = html.html`<input value="edit me">

The viewof operator named text renders a text field. The value of that field can be accessed elsewhere by calling text.

https://observablehq.com/documentation/cells/observable-javascript

In this context, the bit to the right of = is JavaScript, and the bit to the left is special Observable syntax. text = is what they call a variable assignment (similar-ish to a JS variable declaration).

Adding viewof beforehand changes the semantics of the declaration, similar (to me) to how one might add public or static before declarations in other contexts.

(Observable has another such “operator”, mutable).

Is it reasonable to describe this as an “operator”? And if not, what would a better term be?

ServiceNow sys_ui_action client enabled, perform save and redirect

I’m trying to perform a save and revert on a sys_ui_action in Service Now

function proceedWithUpdateFromForm() {

    g_form.save();

    if (dlg != null) {
        dlg.destroy();
    }

    if (returnUrl != 'null') {
        window.location.href = window.location.protocol + '//' + window.location.host + '/' + returnURL;
    } else {
        window.location.href = window.location.protocol + '//' + window.location.host + '/' + tblName + '_list.do?sysparm_userpref_module=' + module + '&sysparm_query=' + listQuery + '&sysparm_cancelable=true';
    }
}

I can not use “current.update()” as I have enabled “Client” option and “current” is ServerSide.

Issue is that with above code, only redirect happens, save doesn’t happen. And if I remove returnURL part, then save happens, and redirect does not happen.

I want to save and then redirect.

Please advice.

I tried following things: In both of these cases, after save() is successfull, rest code doesn’t get executed.

function proceedWithUpdateFromForm_No() {
    // Save the form data
    g_form.save().then(function() {
        alert("Form saved successfully!");
    }).catch(function(error) {
        alert('Error saving form: ' + error);
    });
}

function proceedWithUpdateFromForm() {
    g_form.save({
        onComplete: function() {
            alert("Form saved successfully!");
        },
        onError: function(error) {
            alert('Error saving form: ' + error);
        }
    });
}

Filter all products in Java [closed]

Help give the user the ability to select sorting, cost limits (from “price” to “price”), rating limits (from “rating” to “rating”)

import java.util.ArrayList;
import java.util.Scanner;

class Product {
    String name;
    double price;
    int rating;

    public Product(String name, double price, int rating) {
        this.name = name;
        this.price = price;
        this.rating = rating;
    }
}

class Category {
    String name;
    ArrayList<Product> products;

    public Category(String name) {
        this.name = name;
        this.products = new ArrayList<>();
    }

    public void addProduct(Product product) {
        products.add(product);
    }
}

class Basket {
    ArrayList<Product> items;

    public Basket() {
        this.items = new ArrayList<>();
    }

    public void addProduct(Product product) {
        items.add(product);
    }

    public void removeProduct(Product product) {
        items.remove(product);
    }

    public double totalCost() {
        double total = 0;
        for (Product product : items) {
            total += product.price;
        }
        return total;
    }
}

class User {
    String username;
    String password;
    Basket basket;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
        this.basket = new Basket();
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        User admin = new User("admin", "admin");
        User user = new User("user", "user");

        while (true) {
            System.out.println("Введите логин:");
            String login = scanner.nextLine();
            System.out.println("Введите пароль:");
            String password = scanner.nextLine();
            if (login.equals(admin.username) && password.equals(admin.password)) {
                System.out.println("Вы вошли как администратор.");
                System.out.println("Что вы хотите сделать? (добавить товар / добавить категорию / выйти)");
                String adminChoice = scanner.nextLine();
                if (adminChoice.equalsIgnoreCase("добавить товар")) {
                    System.out.println("Как называется товар?");
                    String productName = scanner.nextLine();
                    System.out.println("Сколько оно стоит?");
                    double productPrice = Double.parseDouble(scanner.nextLine());
                    System.out.println("Какой рейтинг у товара?");
                    int productRating = Integer.parseInt(scanner.nextLine());
                    Product newProduct = new Product(productName, productPrice, productRating);
                    System.out.println("Спасибо вам за добавление товара!");
                    return;
                } else if (adminChoice.equalsIgnoreCase("добавить категорию")) {
                    System.out.println("Как называется категория?");
                    String categoryName = scanner.nextLine();
                    Category newCategory = new Category(categoryName);
                    System.out.println("Спасибо вам за добавление категории!");
                    return;
                } else if (adminChoice.equalsIgnoreCase("выйти")) {
                    System.out.println("До свидания!");
                    return;
                } else {
                    System.out.println("Неверный выбор.");
                }
            } else if (login.equals(user.username) && password.equals(user.password)) {
                System.out.println("Вы вошли как пользователь.");
                System.out.println("Хотите добавить фильтр? (да/нет)");
                String filterChoice = scanner.nextLine();
                if (filterChoice.equalsIgnoreCase("да")) {
                return;
                }
                break;
            } else {
                System.out.println("Неправильный логин или пароль. Попробуйте еще раз.");
            }
        }

        Product reebokTShirt = new Product("Reebok футболка", 100, 7);
        Product pumaTShirt = new Product("Puma футболка", 80, 8);
        Product newBalanceTShirt = new Product("New Balance футболка", 90, 6);
        Product calvinkleinTShirt = new Product("Calvin Klein футболка", 120, 9);
        Product vansTShirt = new Product("Vans футболка", 110, 8);

        Product reebokJacket = new Product("Reebok кофта", 150, 7);
        Product pumaJacket = new Product("Puma кофта", 130, 8);
        Product newBalanceJacket = new Product("New Balance кофта", 140, 6);
        Product calvinkleinJacket = new Product("Calvin Klein кофта", 170, 9);
        Product vansJacket = new Product("Vans кофта", 160, 5);

        Product reebokPants = new Product("Reebok штаны", 120, 7);
        Product pumaPants = new Product("Puma штаны", 100, 8);
        Product newBalancePants = new Product("New Balance штаны", 110, 6);
        Product calvinkleinPants = new Product("Calvin Klein штаны", 140, 9);
        Product vansPants = new Product("Vans штаны", 130, 5);

        Product nikeShoes = new Product("Nike кроссовки", 200, 8);
        Product adidasShoes = new Product("Adidas кроссовки", 180, 7);
        Product converseShoes = new Product("Converse кроссовки", 150, 6);
        Product vansShoes = new Product("Vans кроссовки", 170, 9);
        Product pumaShoes = new Product("Puma кроссовки", 160, 5);

        Product calvinKleinUnderwear = new Product("Calvin Klein трусы", 30, 8);
        Product armaniUnderwear = new Product("Armani трусы", 35, 7);
        Product tommyHilfigerUnderwear = new Product("Tommy Hilfiger трусы", 25, 9);
        Product hugoBossUnderwear = new Product("Hugo Boss трусы", 40, 6);
        Product vansUnderwear = new Product("Vans трусы", 30, 5);

        Product nikesweater = new Product("Nike куртка", 180, 8);
        Product adidassweater = new Product("Adidas куртка", 160, 7);
        Product pumasweater = new Product("Puma куртка", 140, 6);
        Product theNorthFacesweater = new Product("The North Face куртка", 200, 9);
        Product vanssweater = new Product("Vans куртка", 190, 5);

        Category shoes = new Category("Обувь");
        shoes.addProduct(nikeShoes);
        shoes.addProduct(adidasShoes);
        shoes.addProduct(converseShoes);
        shoes.addProduct(vansShoes);
        shoes.addProduct(pumaShoes);

        Category underwear = new Category("Трусы");
        underwear.addProduct(calvinKleinUnderwear);
        underwear.addProduct(armaniUnderwear);
        underwear.addProduct(tommyHilfigerUnderwear);
        underwear.addProduct(hugoBossUnderwear);
        underwear.addProduct(vansUnderwear);

        Category sweater = new Category("Куртки");
        sweater.addProduct(nikesweater);
        sweater.addProduct(adidassweater);
        sweater.addProduct(pumasweater);
        sweater.addProduct(theNorthFacesweater);
        sweater.addProduct(vanssweater);

        Category tShirts = new Category("Футболки");
        tShirts.addProduct(reebokTShirt);
        tShirts.addProduct(pumaTShirt);
        tShirts.addProduct(newBalanceTShirt);
        tShirts.addProduct(calvinkleinTShirt);
        tShirts.addProduct(vansTShirt);

        Category jackets = new Category("Кофты");
        jackets.addProduct(reebokJacket);
        jackets.addProduct(pumaJacket);
        jackets.addProduct(newBalanceJacket);
        jackets.addProduct(calvinkleinJacket);
        jackets.addProduct(vansJacket);

        Category pants = new Category("Штаны");
        pants.addProduct(reebokPants);
        pants.addProduct(pumaPants);
        pants.addProduct(newBalancePants);
        pants.addProduct(calvinkleinPants);
        pants.addProduct(vansPants);


        System.out.println("Выберите товары:");
        int counter = 1;
        System.out.println(tShirts.name.toUpperCase());
        for (Product product : tShirts.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }
        System.out.
                println(jackets.name.toUpperCase());
        for (Product product : jackets.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }
        System.out.println(pants.name.toUpperCase());
        for (Product product : pants.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }
        System.out.println(sweater.name.toUpperCase());
        for (Product product : sweater.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }
        System.out.println(underwear.name.toUpperCase());
        for (Product product : underwear.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }
        System.out.println(shoes.name.toUpperCase());
        for (Product product : shoes.products) {
            System.out.println(counter + ". " + product.name + " - Рейтинг: " + product.rating);
            counter++;
        }

        System.out.println("Введите номера выбранных товаров через пробел:");
        String[] choices = scanner.nextLine().split(" ");
        for (String choice : choices) {
            int productChoice = Integer.parseInt(choice);
            if (productChoice < 1 || productChoice > counter) {
                System.out.println("Неверный выбор товара.");
                return;
            }
            if (productChoice <= tShirts.products.size()) {
                Product chosenProduct = tShirts.products.get(productChoice - 1);
                user.basket.addProduct(chosenProduct);
            } else if (productChoice <= tShirts.products.size() + jackets.products.size()) {
                Product chosenProduct = jackets.products.get(productChoice - tShirts.products.size() - 1);
                user.basket.addProduct(chosenProduct);
            } else if (productChoice <= tShirts.products.size() + jackets.products.size() + pants.products.size()) {
                Product chosenProduct = pants.products.get(productChoice - tShirts.products.size() - jackets.products.size() - 1);
                user.basket.addProduct(chosenProduct);
            } else if (productChoice <= tShirts.products.size() + jackets.products.size() + pants.products.size() + sweater.products.size()) {
                Product chosenProduct = sweater.products.get(productChoice - tShirts.products.size() - jackets.products.size() - pants.products.size() - 1);
                user.basket.addProduct(chosenProduct);
            } else if (productChoice <= tShirts.products.size() + jackets.products.size() + pants.products.size() + sweater.products.size() + underwear.products.size()) {
                Product chosenProduct = underwear.products.get(productChoice - tShirts.products.size() - jackets.products.size() - pants.products.size() - sweater.products.size() - 1);
                user.basket.addProduct(chosenProduct);
            } else {
                Product chosenProduct = shoes.products.get(productChoice - tShirts.products.size() - jackets.products.size() - pants.products.size() - sweater.products.size() - underwear.products.size() - 1);
                user.basket.addProduct(chosenProduct);

            }
        }

        System.out.println("Корзина пользователя " + user.username + ":");
        for (Product item : user.basket.items) {
            System.out.println("- " + item.name + " - $" + item.price);
        }
        System.out.println("Общая стоимость: $" + user.basket.totalCost());
        System.out.println("Вы хотите купить эти товары? (да/нет)");
        String choice = scanner.nextLine();
        if (choice.equalsIgnoreCase("да")) {
            System.out.println("Спасибо что купили наш товар!");
        } else {
            System.out.println("Вы хотите удалить эти товары из корзины? (да/нет)");
            String removeChoice = scanner.nextLine();
            if (removeChoice.equalsIgnoreCase("да")) {
                user.basket.items.clear();
                System.out.println("Товары удалены из корзины.");
            } else {
                System.out.println("Общая стоимость: $" + user.basket.totalCost());
            }
        }

        scanner.close();
    }
}


I tried to add this code but it didn't work

public static ArrayList<Product> filter And Sort(User user, double minPrice, double maxPrice, int minRating, int maxRating) {
        ArrayList<Product> filtered Products = new ArrayList<>();
        for (Category category : categories) {
            filtered Products.add All(category.filter By Price(minPrice, maxPrice));
            filtered Products.add All(category.filter By Rating(minRating, maxRating));
        }
        return filtered Products;
    }

    public static void show All Products(User user) {
        // Display of all products
    }

    public static void show Filtered Products(ArrayList<Product> filtered Products) {
        // Displaying filtered products
    }
}

gggggggggggggggfhfhghfhfhghfhfhfghfhghfghghhhhh/enr;gjlsnrg;uzergnfiPWRJN;gjnzrwsgluidfkh;sjdfngydrsihlu;dozfihndlyfixzfu;oihvdgntuyfisuzfsipjcsuinhop,immgjuARGFVBYNHJ,;L’.KMNJHBYUGTFVCRDESXEDCFGVYBHNJKM,L;.’/.,LKMNHJUBYGTVFCDfvgbhnjmk,l;.’/.onhyjugtfvrdcftvgybhunjimok,l;.’/
;.,lkimnhjuygtvfrdexcfvgybhunjimko,l;.’/.,lnhjuygtfvrdcfvgbyhunjimko,l;.’/
?;.l,okimnjuhybgtvfrc

How can i get this theme toggle code working?

I’m having issues with getting light/dark theme toggle working. The source html, css, Javascript code is below, the html is correct and the button is on the page. Just when i toggle it does nothing: the background page colour doesn’t go from white to black and vice versa. What is missing/wrong. I suspect its the Javascript and/or CSS.
Here’s javascript:

document.addEventListener('DOMContentLoaded', function () {
    const themeToggle = document.getElementById('theme');

    // Function to toggle theme
    function toggleTheme() {
        if (themeToggle.checked) {
            document.documentElement.setAttribute('data-theme', 'dark');
        } else {
            document.documentElement.setAttribute('data-theme', 'light');
        }
    }

    // Event listener for theme toggle change
    themeToggle.addEventListener('change', toggleTheme);
});

Html:

 <label for="theme" class="theme">
   <span class="theme__toggle-wrap">
    <input id="theme"
     class="theme__toggle"
     type="checkbox" role="switch"
     name="theme" value="dark">
    <span class="theme__fill"></span>
    <span class="theme__icon">
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
     <span
      class="theme__icon-part"></span>
    </span>
   </span>
  </label>

Here is the CSS of toggle:

.theme__toggle:checked ~ body {
  background-color: black; /* Dark mode background color */
  color: #fff; /* Text color for dark mode */
}

/* Light mode */
.theme__toggle:not(:checked) ~ body {
  background-color: white; /* Light mode background color */
  color: #000; /* Text color for light mode */
}

i tried simplifying the javascript and css but hasn’t worked. The page by default should be white then turn black when toggle is well toggled and vice versa.

Text not in the center of the webpage

I have a div named calculator-frame that contains a frame for a calculator website I’m making in a webpage, I’m using CSS Right now, I already have everything in the html file.

The problem is that I can’t make the text align in the center of the page, also, the buttons of the calculator are not in the center same as the title text. (not the document title)

This is the code I tried to align the text to the center of the webpage.

#calcTitle {

    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif ;
    position: relative;
    color: darkblue;
    align-content: center;
    padding: 10px;
    float: left;
}

I used Align-content to make the title in the center of the webpage, I used that same keyword for the buttons.
The result is that the Title in the screen is not in the center of the webpage.

I appreciate any tip/help,

Error graph.versions is undefined Tensorflow.js and React

I tried to load a model (converted with tensorflowjs) that is in a cloud storage from IBM, but when i start the project with “npm start” this error appears:

ERROR

graph.versions is undefined
loadWithWeightMap@http://localhost:3000/static/js/bundle.js:47800:23
loadSync@http://localhost:3000/static/js/bundle.js:47777:17
./node_modules/@tensorflow/tfjs-converter/dist/executor/graph_model.js/load/<@http://localhost:3000/static/js/bundle.js:47762:23

I dont really know how to solve this error, hope you can help me with this one. Thanks¡

import React, { useRef, useState, useEffect } from "react";
import Webcam from "react-webcam";
import * as tf from '@tensorflow/tfjs';
import './App.css';

function App() {

  const webcamRef = useRef(null);
  const canvasRef = useRef(null);

  // Main function
  const runCoco = async () => {
    // 3. TODO - Load network 
    // e.g. const net = await cocossd.load();
    // https://traductorlsch.s3.us-south.cloud-object-storage.appdomain.cloud/model.json
    const net = await tf.loadGraphModel('https://traductorlsch.s3.us-south.cloud-object-storage.appdomain.cloud/model.json')
    
    
    //  Loop and detect hands
    setInterval(() => {
      detect(net);
    }, 16.7);
  };
 
  const detect = async (net) => {
    // Check data is available
    if (
      typeof webcamRef.current !== "undefined" &&
      webcamRef.current !== null &&
      webcamRef.current.video.readyState === 4
    ) {
      // Get Video Properties
      const video = webcamRef.current.video;
      const videoWidth = webcamRef.current.video.videoWidth;
      const videoHeight = webcamRef.current.video.videoHeight;

      // Set video width
      webcamRef.current.video.width = videoWidth;
      webcamRef.current.video.height = videoHeight;

      // Set canvas height and width
      canvasRef.current.width = videoWidth;
      canvasRef.current.height = videoHeight;

      // 4. TODO - Make Detections
      const img = tf.browser.fromPixels(video)
      const resized = tf.image.resizeBilinear(img, [640,480])
      const casted = resized.cast('int32')
      const expanded = casted.expandDims(0)
      const obj = await net.executeAsync(expanded)
      console.log(obj)

      // const boxes = await obj[1].array()
      // const classes = await obj[2].array()
      // const scores = await obj[4].array()
      
      // Draw mesh
      // const ctx = canvasRef.current.getContext("2d");

      // 5. TODO - Update drawing utility
      // drawSomething(obj, ctx)  
      // requestAnimationFrame(()=>{drawRect(boxes[0], classes[0], scores[0], 0.8, videoWidth, videoHeight, ctx)}); 

      tf.dispose(img)
      tf.dispose(resized)
      tf.dispose(casted)
      tf.dispose(expanded)
      tf.dispose(obj)

    }
  };

  useEffect(()=>{runCoco()},[]);

  return (
    <div className="App">
      <header className="App-header">
        <Webcam
          ref={webcamRef}
          muted={true} 
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 9,
            width: 640,
            height: 480,
          }}
        />

        <canvas
          ref={canvasRef}
          style={{
            position: "absolute",
            marginLeft: "auto",
            marginRight: "auto",
            left: 0,
            right: 0,
            textAlign: "center",
            zindex: 8,
            width: 640,
            height: 480,
          }}
        />
      </header>
    </div>
  );
}

export default App;

my search function is not working. Help me out

/*My search method isn't working. You have to type the exact name the search is looking for in order 
for it to work else, It goes false*/ function find(){
            let inputField = document.getElementById("search"); 
            let value = inputField.value; 
       let getDeriva = value.search("Deriva")
       if(getDeriva == 0){
           
       }else{
           let getRagno = value.search(" Ragno ")
           if(getRagno == 0){
               document.getElementById("matches").innerHTML = "4 Matches found";
               document.getElementById("demoTwo").innerHTML = "1. Ragno seat skeleton 20¢ No.1";
               document.getElementById("demoThree").innerHTML = "2. Ragno seat trim pcs 50¢ No.3";
               document.getElementById("demoFour").innerHTML = "3. Ragno headrest top skeleton and connection bar 5¢ No.58";
               document.getElementById("demoFive").innerHTML = "4. Ragno luxury sport trim whole seat and Spyder headrest 80¢ No.101";
           }else{
              let getAkalotos = value.search("Akalotos")
              if(getAkalotos == 0){
                  
              }else{
                  let getVentoor = value.search("Ventoor")
                  if(getVentoor==0){
                      
                  }else{
                      let getBentaar = value.search("Bentaar")
                      if(getBentaar == 0){
                          
                      }else{
                          document.getElementById("matches").innerHTML = "Nothing Found";
                      }
                  }
              }
           }
       }
    }

/*I was expecting that I could type in Fillis Ragno and javascript would search Ragno for me. But it did not work and showed No Matches found*/


so basicaly I wanted to let the people know what they wanted so I used the search method
however when I made it go in It didn’t count as my search and all it did was false it up.
SO somehow instead of 0(when the value is found) it still showed -1(when the value isn’t found)

Unable to load text from textarea to docx

Need to load outputTextElem text from textarea as a docx document on button click. But the existing method will not work:

const downloadBtn = document.querySelector("#download-btn");
downloadBtn.addEventListener("click", async (e) => {
  const outputText = outputTextElem.value;
  const outputLanguage =
      outputLanguageDropdown.querySelector(".selected").dataset.value;

  if (outputText) {
    try {
      const result = await mammoth.convertText({ arrayBuffer: outputText }, {
        ignoreEmptyParagraphs: true
      });

      const blob = new Blob([result.value], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.download = `translated-to-${outputLanguage}.docx`;
      a.href = url;
      a.click();
    } catch (error) {
      console.error("Error converting text to DOCX:", error);
    }
  }
});

……

<script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.2/mammoth.browser.min.js"></script>

An error occurs that the type cannot find mammoth.convertText, although everything is connected in index.html as indicated above:

script.js:216 Error converting text to DOCX: TypeError: mammoth.convertText is not a function
    at HTMLButtonElement.<anonymous> (script.js:205:36)

What is the problem?

How to design a monthly status chart in react using typescript

I’m trying to create a monthly status chart like the following, which the props should take a list of monthly data(consecutive data for each month, if no data for this month, it should be 0 or null) for different categories. And a date range exactly match the monthly data list.
enter image description here
I looked for several several library, like MUI, but they don’t have any thing similiar to what I want to accomplish, so I’, thinking to build from scratch, but I have difficult on how to design this chart.
I’m thinking use HStack for each category’s monthly data, and align them vertically with VStack, however, the grid underneath would be difficult to construct this way, is there any better suggestion now how to design this kind of chart?