Get file address with ASP.NET

I have a C# application with ASP.NET MVC and Framework 4.8, and CSHTML pages. I also have the DevExpress MVC version 21.2 libraries, although I don’t think it’s important. I need to put a button on my Index screen that, when pressed, launches an OpenFileDialog or similar dialog box, but not embedded in the screen. I need to save the file address in a string variable in the controller when I select a file and press “OK.” I don’t want to do anything with the file.
I’ve tried doing it with JavaScript, with DevExpress components, and I’m getting too many errors.

setState function not recognized as function

In my React Native app, I’m having a problem where the setState function is not being recognized as a function.

I already inserted the context provider on the App root page and exported the context properties, and it still doesn’t work.

I’m trying to call it on a component, and still getting the “setAppCompany is not a function”

App.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import AppProviders from './mobile/src/providers/AppProviders';
import Route from './mobile/src/navigations/Route';
import Layout from './mobile/src/layout/Layout';

export default function App() {
  return (
    <AppProviders>
      <NavigationContainer>
        <Layout>
          <Route />
        </Layout>
      </NavigationContainer>
    </AppProviders>
  );
}

AppProviders.js

import React from 'react';
import CompanyProvider from '../contexts/CompanyContext';
import UserProvider from '../contexts/UserContext';

const AppProviders = ({ children }) => {
  return (
    <CompanyProvider>
      <UserProvider>{children}</UserProvider>
    </CompanyProvider>
  );
};

export default AppProviders;

CompanyContext.js

import React, { createContext, useState, useContext } from 'react';
export const CompanyContext = createContext();

export default function CompanyProvider({ children }) {
  const [appCompanyId, setAppCompany] = useState(null);

  return (
    <CompanyContext.Provider value={(appCompanyId, setAppCompany)}>
      {children}
    </CompanyContext.Provider>
  );
}

export const useCompany = () => {
  const context = useContext(CompanyContext);
  const { appCompanyId, setAppCompany } = context;
  return { appCompanyId, setAppCompany };
}

UserContext.js

import React, { createContext, useState, useContext } from 'react';
export const UserContext = createContext();

export default function UserProvider({ children }) {
  const [logged, setLogged] = useState(false);
  const [userId, setUserId] = useState(null);
  const [token, setToken] = useState('');
  const [admin, setAdmin] = useState(false);

  return (
    <UserContext.Provider
      value={
        (logged, setLogged, userId, setUserId, token, setToken, admin, setAdmin)
      }>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  const context = useContext(UserContext);
  const {
    logged,
    setLogged,
    userId,
    setUserId,
    token,
    setToken,
    admin,
    setAdmin,
  } = context;
  return {
    logged,
    setLogged,
    userId,
    setUserId,
    token,
    setToken,
    admin,
    setAdmin,
  };
}

TopBar.js (Component using context properties)

import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Picker } from '@react-native-picker/picker';
import { getCompaniesByUserId } from '../services/api/company.services';
import { useUser } from '../contexts/UserContext';
import { useCompany } from '../contexts/CompanyContext';

const TopBar = () => {
  // Hooks ------------------------------------->
  const { userId } = useUser();
  const { setAppCompany } = useCompany();

  const [selectedCompany, setSelectedCompany] = useState(null);
  const [avaliableCompanies, setAvailableCompanies] = useState([
    { idEmpresa: 1, nomeEmpresa: 'Rooftop Bar' },
    { idEmpresa: 2, nomeEmpresa: 'Restaurante Brilhante' },
  ]);

  useEffect(() => {
    if (avaliableCompanies == null)
      setAvailableCompanies(getCompaniesByUserId(userId));

    if (avaliableCompanies != null && selectedCompany == null)
      setSelectedCompany(avaliableCompanies[0]);
  }, [avaliableCompanies, selectedCompany, userId]);

  useEffect(() => {
    if (selectedCompany != null) setAppCompany(selectedCompany);
  }, [selectedCompany, setAppCompany]);

  // JSX ------------------------------------->
  return (
    <View style={styles.topBar}>
      <Text style={styles.title}>RoofStock</Text>
      <View style={styles.selectorContainer}>
        <Text style={styles.label}>Company:</Text>
        <Picker
          selectedValue={selectedCompany}
          onValueChange={setSelectedCompany}
          style={styles.picker}
          dropdownIconColor="#fff">
          {avaliableCompanies.map((company) => (
            <Picker.Item
              label={company.nomeEmpresa}
              value={company.idEmpresa}
            />
          ))}
        </Picker>
      </View>
    </View>
  );
};

I tried to use the setState function in the context created and couldn’t. I was expecting to use the setState function to control and manage state based on this data around the app.

p5.js Cannot convert undefined or null to object

I am trying to make a grid for a game, and I set up the grid, but when I use a for loop to display all of the cells it gives me an error – Uncaught TypeError: Cannot convert undefined or null to object. I think that there is something undefined in the grid array but there shouldn’t be. Another theory is that the grid is empty, although it should have 16 cells in it.

let bgCol = '#A6A6A6';
let rows = 4;
let cols = 4;
let grid = [];
let size = 50;


function setup() {
    createCanvas(windowWidth, windowHeight);
    background(bgCol);
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            grid.push(new Cell({x: r * size, y: c * size}, 0));
        }
    }
}

function draw() {
    background(bgCol);
    for (let g of grid) {
        grid[g].dis();
    }
}

class Cell {
    constructor(pos, num, col = '#FFFFFF') {
        this.pos = pos;
        this.num = num;
        this.col = col; // White as placeholder until later
    }
    dis() {
        stroke('#000000');
        strokeWeight(2);
        fill(this.col);
        square(this.pos.x, this.pos.y, size, 5);
        if (this.num) {
            textSize(size - 5);
            text(this.num, this.pos.x + 5, this.pos.y + 5);
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.11.0/p5.js"></script>

Video capture/analysis on simple static snack (hot fries) site

Alright, so we’ve got this pretty basic, mostly static marketing website – you know, the kind that just shows off the product, here it is andycappshotfries.com. Nothing fancy on the backend, just simple HTML/CSS/JS and maybe a tiny script for a contact form.

But we’ve got this wild idea we wanna slap onto it: a “Spiciness Challenge” feature! The plan is users can record a quick video right in their browser, chowing down on the product, upload it, and then our server (somehow!) runs computer vision magic (think Python and OpenCV) to analyze their reaction and give ’em a “spiciness score.”

Here’s the rub – bolting this complex video capture and processing beast onto a super simple site? That’s got us scratching our heads. We need some solid technical game plan.

Specifically, we’re kinda lost on:

  1. Client-Side Video Fun: How do we even reliably capture video from a user’s webcam across different browsers without it being a total nightmare? Are there any slick JavaScript libraries beyond just wrestling with navigator.mediaDevices.getUserMedia() directly? And resizing or formatting that video on the fly before uploading – what’s the play there?
  2. The Upload Beast: Video files can get chunky fast, right? What’s the smoothest, most robust way to pump potentially big files up to our server? Should we mess with chunked uploads, try WebSockets, or can a standard form post actually cut it? We definitely need real-time progress feedback for the user, and bonus points if it can resume uploads if the connection flakes out.
  3. Backend Black Magic (Video Processing): This is where it gets really spicy. What kind of server-side setup are we even talking about to handle incoming video files? How do we trigger our Python/OpenCV script once a video lands? And the big one: how do we handle a bunch of users uploading and needing processing at the same time without melting the server? Do we need message queues (like RabbitMQ or Kafka)? Or maybe serverless functions (AWS Lambda, Google Cloud Functions) are the way to go for scaling this processing? We definitely need it to be async – take the video, tell the user “got it!”, and do the heavy lifting in the background.
  4. Keeping Users Happy (UX): Nobody likes staring at a frozen screen. How do we keep users in the loop – “Recording…”, “Uploading…”, “Processing…”? And how do we handle errors gracefully so they don’t just see a broken page? A little preview of their video before they send it off would be sweet too.
  5. The Not-So-Fun Stuff (Security/Privacy): This involves user videos, so obviously, privacy and security are massive. What absolutely essential steps do we need to take to keep that video data safe? Any specific privacy considerations we might be missing?

Basically, we’re looking for architectural pointers and technology ideas that can handle this kind of media processing horsepower and bolt onto our existing simple site structure without us having to rebuild the whole darn thing from scratch (unless we totally have to, then tell us!).

–“What did I try?–
I’ve been researching the different components needed: looking into client-side video capture APIs (like getUserMedia), various file upload strategies suitable for large files (e.g., chunked uploads), and potential backend architectures for running Python/OpenCV video analysis scripts (considering options like serverless functions, message queues, or dedicated processing services).
–What I`m expecting?–
I was hoping to find a more established, standard pattern or set of technologies specifically recommended for adding this kind of complex media processing and interaction feature onto a web presence that starts from a very simple/static site structure.
–What actually resulted?–
My research showed that while individual pieces exist, integrating them cohesively and efficiently for performance and scalability (especially with large video files and processing queues) onto a minimal backend infrastructure is a complex architectural challenge with multiple potential approaches, none of which seem straightforward without significant changes. This uncertainty and need for high-level architectural guidance is why I’m asking the question.”

Fill circle area with text input

I’ve a circle of gratitude section on a page.

See here – https://prnt.sc/ut6a7MbqUIoS

The idea is the page will have a input box where user can input there name and when press submit button, the name will be in the box on the right side.

I’ve tried with this –

const canvas = document.getElementById('gratitude-circle');
const ctx = canvas.getContext('2d');
const form = document.getElementById('gratitude-form');
const input = document.getElementById('name-input');

const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const circleRadius = 250;
const minTextGap = 10; // Minimum gap between texts
const names = [];

function clearCircle() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw decorative wreath (stylized circle with leaves)
  ctx.save();
  ctx.beginPath();
  ctx.arc(centerX, centerY, circleRadius, 0, 2 * Math.PI);
  ctx.strokeStyle = '#7bbf8e';
  ctx.lineWidth = 4;
  ctx.shadowColor = '#b8e2c8';
  ctx.shadowBlur = 8;
  ctx.stroke();
  ctx.restore();
  // Draw simple leaf accents (simulate wreath)
  for (let i = 0; i < 24; i++) {
    const angle = (i / 24) * 2 * Math.PI;
    const leafX = centerX + (circleRadius - 18) * Math.cos(angle);
    const leafY = centerY + (circleRadius - 18) * Math.sin(angle);
    ctx.save();
    ctx.translate(leafX, leafY);
    ctx.rotate(angle + Math.PI / 2);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.quadraticCurveTo(6, 8, 0, 18);
    ctx.quadraticCurveTo(-6, 8, 0, 0);
    ctx.fillStyle = '#b8e2c8';
    ctx.globalAlpha = 0.7;
    ctx.fill();
    ctx.globalAlpha = 1;
    ctx.restore();
  }
  // Draw central message
  ctx.save();
  ctx.font = '28px Segoe UI, Arial';
  ctx.fillStyle = '#7bbf8e';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('Thank you', centerX, centerY - 28);
  ctx.font = 'bold 32px Segoe UI, Arial';
  ctx.fillStyle = '#4a8c6b';
  ctx.fillText('for being part', centerX, centerY + 4);
  ctx.font = '28px Segoe UI, Arial';
  ctx.fillStyle = '#7bbf8e';
  ctx.fillText('of our story.', centerX, centerY + 36);
  ctx.restore();
}

function drawNames() {
  clearCircle();
  if (names.length === 0) return;
  // Place names along the circumference
  const totalNames = names.length;
  const fontSize = 22;
  ctx.font = 'bold 22px Segoe UI, Arial';
  let totalArcLength = 0;
  let nameArcLengths = [];
  // First, measure arc length for each name
  for (let i = 0; i < totalNames; i++) {
    const name = names[i];
    const textWidth = ctx.measureText(name).width;
    // Arc length = width / radius
    const arc = textWidth / circleRadius;
    nameArcLengths.push(arc);
    totalArcLength += arc;
  }
  // Calculate starting angle so names are centered
  let gap = minTextGap / circleRadius;
  let totalGap = gap * totalNames;
  let startAngle = -totalArcLength / 2 - totalGap / 2;
  let angle = startAngle;
  for (let i = 0; i < totalNames; i++) {
    const name = names[i];
    const arc = nameArcLengths[i];
    const theta = angle + arc / 2;
    const x = centerX + circleRadius * Math.cos(theta);
    const y = centerY + circleRadius * Math.sin(theta);
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(theta + Math.PI / 2);
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = '#333';
    ctx.fillText(name, 0, 0);
    ctx.restore();
    angle += arc + gap;
  }
}

form.addEventListener('submit', function(e) {
  e.preventDefault();
  const name = input.value.trim();
  if (name && names.length < 100) { // Limit to avoid overfilling
    names.push(name);
    drawNames();
    input.value = '';
  }
});

clearCircle();
body {
  background: #fff7f3;
  font-family: 'Segoe UI', Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

#gratitude-form {
  margin-bottom: 32px;
  display: flex;
  gap: 12px;
}

#name-input {
  padding: 10px 16px;
  border-radius: 20px;
  border: 1px solid #b2b2b2;
  font-size: 1.1rem;
  outline: none;
}

#gratitude-form button {
  padding: 10px 20px;
  border-radius: 20px;
  border: none;
  background: #7bbf8e;
  color: #fff;
  font-size: 1.1rem;
  cursor: pointer;
  transition: background 0.2s;
}

#gratitude-form button:hover {
  background: #5fa06e;
}

.circle-area {
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

#gratitude-circle {
  background: transparent;
  display: block;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #e0e0e0;
}
<div class="container">
  <form id="gratitude-form">
    <input type="text" id="name-input" placeholder="Enter your name" autocomplete="off" required />
    <button type="submit">Add Name</button>
  </form>
  <div class="circle-area">
    <canvas id="gratitude-circle" width="600" height="600"></canvas>
  </div>
</div>

It looks like this – https://prnt.sc/ktSamLH1dpOr

Is there any way to develop a dynamic area like this?

How to patch a custom resource in kubernetes using the javascript client

I created a custom resource definition and also added the status subresource:

subresources:
        status: {}

I’m trying to update it with the following code but I’m getting all sorts of errors:

async function setLastSyncedImage(jobsetName, image) {
  let patch = {
    status: {
      lastSyncedImage: image
    }
  }

  await k8sApi.patchNamespacedCustomObjectStatus(
    {
      group: GROUP,
      version: VERSION,
      namespace: NAMESPACE,
      plural: PLURAL,
      name: jobsetName,
      body: patch
    },
    {
      headers: {
        'Content-Type': 'application/merge-patch+json'
      }
    }
  )
}

With that, I’m getting the following error:

'{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp","reason":"BadRequest","code":400}n'

it seems to ignore the Content-Type header I give it. so if instead I give it the patch like so:

let patch = [{
    "op": "replace",
    "path": "/status/lastSyncedImage",
    "value": image
  }]

That’s the error message I’m getting:

{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"the server rejected our request due to an error in our request","reason":"Invalid","details":{},"code":422}n'

I can’t find any example online that will allow me to patch the status of the resource

Printing a Local Report without Preview

I using visual studio 2022 with MVC NET 8 and C# language and Microsoft reporting service 2016.

I Want to print invoice without preview report using java script.
I have too ID for too type invoice. The first invoice data for cash money
And there’d to delivery invoice it deferent data.
So I need to print invoice by click button depend on invoice type …. Cash or delivery using java script

How to store a light and dark theme with HTML/JS using a dropdown box?

I am currently working on a light and dark theme for a website that several others and I are designing. Currently, I have an html dropdown box that allows you to select a color theme option, and upon selecting it, it automatically changes the theme, which is done through a CSS class being activated or deactivated. However, when you refresh the page it doesn’t remember what was selected.

How would I go about changing this? I’d like to use this “Apply Button” that another person designed if possible. Here’s what I have currently:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Settings</title>
        <link rel="stylesheet" href="/html/css/settings.css">
        <script type="text/javascript" src="/html/js/darkmode.js" defer></script>
    </head>
    <body class="">
        <%include file="navbar.html"/>
        <div class="settings-container">
            <h1>Settings</h1>
    
            <div class="setting">
                <div class="special-text">
                    <label for="dark-mode-select">Color Theme:</label>
                    </div>
                    <select id="dark-mode-select" onchange="changeColor()">
                        <option value="light" id="light">Light</option>
                        <option value="dark" id="dark">Dark</option>
                    </select>
            </div>
    
            <div class="setting">
                <label for="font-size-slider">Font Size:</label>
                <input type="range" id="font-size-slider" min="1" max="100" value="50">
                <span id="font-size-value">50</span>
            </div>
    
            <div class="setting">
                <div class="special-text">
                <label for="profanity-filter">Profanity Filter:</label>
                <input type="checkbox" id="profanity-filter">
            </div>
            </div>
    
            <div class="button-container">
                <button id="apply-settings">Apply</button>
            </div>
        </div>

Color Change JS:

function changeColor(){
    //alert("colorchange")
    let theme = localStorage.getItem('theme')
    //const themeChange = document.getElementById('dark-mode-select')
    const themeChangeDark = document.getElementById('dark').selected
    const themeChangeLight = document.getElementById('light').selected


    const enableDarkmode = () => {
        document.body.classList.add('darkmode')
        localStorage.setItem('theme', 'dark')
    }

    const enableLightmode = () => {
        document.body.classList.remove('darkmode')
        localStorage.setItem('theme', 'light')
    }

    if(theme === "dark") enableDarkmode()



    if(themeChangeDark == true){
        theme = localStorage.getItem('theme')
        enableDarkmode()
    } else if(themeChangeLight == true){
        theme = localStorage.getItem('theme')
        enableLightmode()
    }
}

Apply Button JS:

document.addEventListener("DOMContentLoaded", function () {
    const fontSizeSlider = document.getElementById("font-size-slider");
    const fontSizeValue = document.getElementById("font-size-value");
    const darkModeSelect = document.getElementById("dark-mode-select");
    const profanityFilterCheckbox = document.getElementById("profanity-filter");
    const applyButton = document.getElementById("apply-settings");
    const body = document.body;
    const baseFontSize = 16;



    darkModeSelect.addEventListener("change", function() {
        const colorTheme = this.value;
      });

    function applyStoredSettings() {
        const storedFontSize = localStorage.getItem("fontSize");
        if (storedFontSize) {
            applyFontSize(storedFontSize);
            fontSizeSlider.value = storedFontSize;
            fontSizeValue.textContent = storedFontSize;
        }
        darkModeSelect.value = colorTheme;
        
    }

    function applyFontSize(value) {
        const scaleFactor = value / 50;
        const newFontSize = baseFontSize * scaleFactor;
        fontSizeValue.textContent = value;
        body.style.fontSize = newFontSize + "px";
    }

    fontSizeSlider.addEventListener("input", () => applyFontSize(fontSizeSlider.value));

    applyButton.addEventListener("click", function () {
        localStorage.setItem("fontSize", fontSizeSlider.value);
        localStorage.setItem("theme", colorTheme);
        localStorage.setItem("profanityFilter", profanityFilterCheckbox.checked);
        alert("Settings applied globally!");
    });

    applyStoredSettings();

In the code you can see I’ve tried using local storage to set “theme” as the color chosen in both of the JS files, but it doesn’t seem to actually remember the chosen value.

How to pass a parameter to php file

I want to create an app in which you can drag-and-drop your local file and upload it to a web server.
I made it.
My next challenge is you can upload your file into a different folder depending on who you are.
For example if you are ‘Mr.A’, you upload your file into ‘image/A’ in the server,
on the other hand if you are ‘Mr.B’, you upload your file into ‘image/B’, something like that.
My question is how can you pass a parameter (which indicates who you are) to the PHP file(from index.html to upload.php).
My codes are below.
I mean I want to add a select who you are in ‘index.html’ and pass that parameter to ‘upload.php’.
Is it possible?
If so, can you tell me how?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D&D upload</title>
    <link rel="stylesheet" href="style.css">
    <script src="upload.js"></script>
</head>
<body>
  <h1>D&D upload</h1>
    <p id="text_message"></p>
    <section id="dropzone">
      <p>drop your file here</p>
    </section>
</body>
</html>

upload.php


<?php
if( isset($_FILES['uploadFile']) ) {
  if( move_uploaded_file( $_FILES['uploadFile']['tmp_name'], './image/'.$_FILES['uploadFile']['name']) ){
    echo 'true';
  } else {
    echo 'false';
  }
  return;
}
?>

upload.js


function uploadFile(file) {
  const upload_uri = "./upload.php";
  const xhr = new XMLHttpRequest();
  const fd = new FormData();
  let p_element = document.getElementById("text_message");

  xhr.open("post", upload_uri, true);
  xhr.onreadystatechange = function() {
    if( xhr.readyState === 4 && xhr.status === 200) {

      if( xhr.responseText === 'true' ) {
        p_element.textContent = 'success';
      } else {
        p_element.textContent = 'failed';
      }
    }
  };
  fd.append('uploadFile', file);
  xhr.send(fd);
}

window.addEventListener('DOMContentLoaded', function(){

  let dropzone = document.getElementById('dropzone');

  dropzone.addEventListener("dragenter", function(e){
    e.stopPropagation();
    e.preventDefault();
  });

  dropzone.addEventListener("dragover", function(e){
    e.stopPropagation();
    e.preventDefault();
  });

  dropzone.addEventListener("drop", function(e){
    e.stopPropagation();
    e.preventDefault();

    const upload_files = e.dataTransfer.files;

    for(let i=0; i<upload_files.length; i++) {
      uploadFile(upload_files[i]);
    }
  });
});

OS of my web server is Ubuntu 22.04.4 LTS and my php version is PHP 8.3.9
I am waiting for your support.

Issue on iPhone: “Can’t open this page” Error — Triggered During Navigation Menu Events [closed]

Issue Summary: I’ve implemented a three-layer navigation menu on my site. The issue arises after repeated interactions with the menu — the page eventually reloads unexpectedly, and just before the reload, a JavaScript error appears.

Navigation Flow:-

  1. Tap the hamburger menu → Opens Section 1
  2. Click an item in Section 1 → Opens Section 3
  3. Click “Back” → Returns to Section 2
  4. Click an item in Section 2 → Opens Section 3

After repeating this process a few times, when I click on the hamburger/back/close icon, the page reloads unexpectedly (the first time) and throws an error right before reloading (the second time, getting “can’t open this page”).

What I Need: I need help identifying and resolving the issue causing this reload and error. It’s urgent.

Error minting NFT in React with ethers.js: “no matching fragment

I’m encountering an error when trying to mint an NFT using a React frontend and the ethers.js library. The specific error I’m getting is:

Error minting NFT: no matching fragment (operation="fragment", info={ "args": [ "ipfs://bafkreiekiirqbrda7nwlrivh62425gspa3mtag6s7oinfh42vletw7wgmi" ], "key": "mintNFT" }, code=UNSUPPORTED_OPERATION, version=6.13.7)

My React component for minting looks like this:

import React, { useState } from 'react';
import { ethers } from 'ethers';
import PhilosophyNFT from '../abis/PhilosophyNFT.json';

const MintPage = () => {
  const [minting, setMinting] = useState(false);
  const [minted, setMinted] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");

  const mintNFT = async () => {
    if (minting) return;
    setMinting(true);
    setSuccessMessage("");
    setErrorMessage("");

    try {
      if (window.ethereum) {
        await window.ethereum.request({ method: 'eth_requestAccounts' });
      } else {
        alert("Please install MetaMask!");
        return;
      }

      const provider = new ethers.BrowserProvider(window.ethereum);
      const signer = await provider.getSigner();

      const contract = new ethers.Contract(
        "0x2020Ac5bCE11e66796aA025a88a6d8E27559Da4E", // Deployed contract address
        PhilosophyNFT.abi,
        signer
      );

      const tx = await contract.mintNFT(`ipfs://bafkreiekiirqbrda7nwlrivh62425gspa3mtag6s7oinfh42vletw7wgmi`);
      await tx.wait();
      setMinted(true);
      setSuccessMessage("Minting successful! Your NFT is now minted.");
    } catch (error) {
      setMinted(false);
      setErrorMessage("Error minting NFT: " + error.message);
    } finally {
      setMinting(false);
    }
  };

  return (
    <div className="mint-container">
      <h1>Mint Your Philosophy NFT</h1>
      {errorMessage && <div className="error-message">{errorMessage}</div>}
      {successMessage && <div className="success-message">{successMessage}</div>}
      <button onClick={mintNFT} disabled={minting} className="mint-button">
        {minting ? "Minting..." : minted ? "Minted!" : "Mint NFT"}
      </button>
    </div>
  );
};

export default MintPage;

The error message suggests that the ethers.js library cannot find a matching function signature (mintNFT) in the provided ABI (PhilosophyNFT.json) that accepts the arguments I’m passing (in this case, a single IPFS URI string).

  • I have already tried:

  • Verifying that the contract address in my React code is correct.

Any help in resolving this error would be greatly appreciated!

Make images scale within a div element [closed]

I have a [div] that contains a list of paragraphs and a single [img]. I’d like the image to scale itself so that the total content doesn’t overflow the [div]. That is, if there’s more text, then make the image smaller. If the aspect ratio changes, and the text gains vertical height: scale the image.

I know HTML is reflowable; however, this is picture set with a story. So I’m “fighting” the nature of HTML. I don’t want it to overflow.

Is there a way to do this without arcane javascript hacking?

Tree view containing editbox, checkbox controls [closed]

Can anybody help me find a suitable JS framework for tree view and GUI components?
I want to use it inside an HTML host, so it can support mouse events, allow dynamic content updates, and enable easy expansion or collapsing of nodes.
Specifically, I need support for various GUI controls within the tree, such as text boxes, checkboxes, etc. These controls should be updateable via JavaScript, and user interactions (e.g., clicking a checkbox or editing a field) should trigger corresponding JavaScript event notifications.
While I’ve come across some examples on the internet, they lack the simplicity and ease of use inside HTML hosts. The type of tree view I’m referring to is illustrated in the following image.enter image description here

DataTables loses selected checkboxes across pages when generating custom PDF with jQuery

I’m using DataTables with pagination and checkboxes to allow users to select multiple banners. Upon clicking “Generate Proposal”, I collect all checked rows, generate HTML, and convert it to a PDF using html2pdf.

Issue:
If I select 2 banners on Page 1 and 1 banner on Page 2, only the banner from the current page (Page 2) gets exported in the PDF. The previously selected ones on Page 1 are lost.

    <script>
    jQuery(document).ready(function($) {
        const table = $('#bannerTable').DataTable({
     dom: 'Blfrtip', 
              paging: true,          // Enable pagination
    pageLength: 10,         // Default number of rows per page
             lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ],
            buttons: [{
                    extend: 'excelHtml5',
                    title: 'Banner Data',
                    text: '<i class="dashicons dashicons-media-spreadsheet"></i> Excel',
                    className: 'button button-secondary'
                },
                {
                    extend: 'pdfHtml5',
                    title: 'Banner Data',
                    text: '<i class="dashicons dashicons-pdf"></i> PDF',
                    orientation: 'landscape',
                    pageSize: 'A4',
                    className: 'button button-secondary'
                }
            ]
        });
        function populateFilters(columnIndex, selector) {
    const column = table.column(columnIndex);
    const values = new Set();

    column.data().each(function(d) {
        d.split(',').forEach(item => values.add(item.trim()));
    });

    Array.from(values).sort().forEach(function (val) {
        if (val) {
            $(selector).append(`<option value="${val}">${val}</option>`);
        }
    });
}

// Column indices: Media(2), Type(3), Availability(6), District(7), Place(8)
populateFilters(2, '#filterMedia');
populateFilters(3, '#filterType');
populateFilters(6, '#filterAvailability');
populateFilters(7, '#filterDistrict');
// populateFilters(8, '#filterPlace');

$('#filterMedia, #filterType, #filterAvailability, #filterDistrict, #filterPlace').on('change', function () {
    table.draw(); // <-- very important
});

$.fn.dataTable.ext.search.push(function(settings, data) {
    const media = $('#filterMedia').val();
    const type = $('#filterType').val();
    const availability = $('#filterAvailability').val();
    const district = $('#filterDistrict').val();
//     const place = $('#filterPlace').val();

    return (!media || data[2].includes(media)) &&
           (!type || data[3].includes(type)) &&
           (!availability || data[6].includes(availability)) &&
           (!district || data[7].includes(district)) 
//            (!place || data[8].includes(place));
});

        $('#selectAll').on('click', function() {
            $('.selectBanner').prop('checked', this.checked);
        });

        $('#generateProposal').on('click', function() {
            const selectedRows = $('.selectBanner:checked').closest('tr');
            if (selectedRows.length === 0) {
                alert("Please select at least one banner.");
                return;
            }
//             if (selectedRows.length > 4) {
//                 alert("You can only generate proposals for up to 4 banners at a time.");
//                 return;
//             }

            const $button = $(this).prop('disabled', true).text('Generating...');
            const $pdfContainer = $('#pdfContainer').empty().css('display', 'block');
            let page = 1;

            const coverHTML = `
    <div class="pdf-cover-page">
        <img src="/wp-content/plugins/bannerplugin/cover.png" alt="Cover" />
    </div>
`;
            $pdfContainer.append(coverHTML);

            selectedRows.each(function() {
                const row = $(this);
                const title = row.find('td:eq(1)').text();
                const media = row.find('td:eq(2)').text();
                const type = row.find('td:eq(3)').text();
                const size = row.find('td:eq(4)').text();
                const district = row.find('td:eq(7)').text();
                const place = row.find('td:eq(8)').text();
                const imagesArray = row.find('.banner-images img');
                const faciav=row.find('td:eq(9)').text();
//              console.log(faciav,'Hi')
                let images = '';
                imagesArray.each(function() {
                    const src = $(this).attr('src');
                    if (src) {
                        images += `<div class="image-box"><img src="${src}" crossorigin="anonymous" /></div>`;
                    }
                });

                if (images.trim() === '' && !title.trim() && !media.trim() && !type.trim() && !size.trim()) return; // Skip if no content

                const html = `
                <div class="proposal-page">
                    <div class="proposal-header">
                        <h2>${title}, ${district}</h2>
                        <img class="logo" src="/wp-content/plugins/bannerplugin/logo.png" />
                    </div>
                    <div class="proposal-images-row">
                        ${images}
                    </div>
                    <div class="proposal-details">
                        <p><strong>Facia:</strong> ${faciav}</p>
                        <p><strong>Size:</strong> ${size}</p>
                        <p><strong>Type:</strong> ${type}</p>
                    </div>
                    <div class="page-number">Page ${page++}</div>
                </div>
            `;
                $pdfContainer.append(html);
            });

            // Ensure last page doesn't have page break
            $pdfContainer.find('.proposal-page').last().css('page-break-after', 'auto');

            // Remove empty proposal pages if any
            $pdfContainer.find('.proposal-page').each(function() {
                if (!$(this).text().trim()) {
                    $(this).remove(); // Remove empty page
                }
            });

            setTimeout(() => {

                html2pdf().set({
                    margin: [0, 0, 0, 0],
                    filename: `banner-proposal-${Date.now()}.pdf`,
                    image: {
                        type: 'jpeg',
                        quality: 0.98
                    },
                    html2canvas: {
                        scale: 2,
                        useCORS: true,
                        allowTaint: false,
                        logging: true,
                        scrollX: 0,
                        scrollY: 0
                    },
                    jsPDF: {
                        unit: 'mm',
                        format: 'a4',
                        orientation: 'portrait',
                        putOnlyUsedFonts: true
                    }
                }).from($pdfContainer[0]).save().then(() => {
                    $pdfContainer.css('display', 'none');
                    $button.prop('disabled', false).text('Create Proposal PDF');
                });
            }, 500);
        });
    });
</script>