Supplied parameter is not a User nor a Role [closed]

So i tried multiple hours and threads about the problem but it nevere worked may someone help me.
I tried it with different structures and everything i also tried with the message way of permissionOverwrits but nothing works for me.
The only thing it should do is add a user to a channel and give the permissions to view and write.

Reconstruct an object [closed]

I have an array in the form of an object like :

[{"site_id": 1, "nom": "TOTO", "date": "2025-03-01"}, {"site_id": 2, "nom": "MOI", "date": "2025-03-22"}, {"site_id": 1, "nom": "TOTO", "date": "2025-03-30"}]

I am trying to reconstruct an object of this kind :

const tab = {"TOTO" : [2025-03-01, 2025-03-30], "MOI": [2025-03-22]}

I tried to combine the .map and .filter functions: I get a result but I can’t format it.

React slideshow prev next function issues

I’m trying to build a simple slideshow in React but I’m having some troubles with the prevNext function.

First some explanation:

I have some filters that selects the images from a file. Then, when i open the image, the slideshow appears and i can cycle through the images with prev and next buttons. The problem is with these prev and next buttons; they cycle through all the images instead of just the ones selected by the filters.

Here’s a link to codesandbox

The code for the function is:

const prevNext = (btn, id) => {
    const elems = document.querySelectorAll(".gallery-img");
    let img = "";
    let total = elems.length;
    let first = elems[0].id;
    let last = elems[total - 1].id;

    if (btn === "prev") {
      let prev = id === first ? elems[total - 1].id : id - 1;
      img = gallery.find((img) => img.id === prev);
    } else if (btn === "next") {
      let next = id === last ? elems[0].id : id + 1;
      img = gallery.find((img) => img.id === next);
    }

    setSrc(img.img);
    setAlt(img.title);
    setId(img.id);
  };

How to solve this issue?
Thanks in advance

Klipper Syntax Highlighter using Highlight.JS

I’m trying to create a syntax highlighter for the Klipper 3D printer firmware. The language consists of settings elements, comments and Jinja2 template elements. In the first place, I wanted to get a simple highlighting working but I’m hitting a road block.

Highlighter Code:

hljs.registerLanguage("klipper", function (hljs) {
  const COMMENT = {
    scope: "comment",
    variants: [
      { begin: /^s*[#;].*$/, end: /$/ }, // Standalone comments
      { begin: /(?!s)[#|;].*/, end: /$/ }, // Inline/trailing comments
    ],
    relevance: 10,
  }

  const KEY_PART = {
    scope: "symbol",
    begin: /^[^=s]+(?=s*[:=])/,
    //end: /^(?!s).+?s?[=:](?=(?:[^n]*$))/,
  }

  const VALUE_PART = {
    scope: "addition",
    begin: /[:=][s*|$]/,
    //end: /r?n$/, // Match until the end of the line
    end: /$/, // Match until the end of the line
    excludeBegin: true, // Ensure the separator is not included
    excludeEnd: true,
  }

  const SECTION = {
    scope: "addition",
    begin: /^s*[/,
    end: /]/,
    contains: [
      {
        scope: "title",
        match: /[^]]+/,
      },
    ],
  }

  const INDENTED_BLOCK = {
    scope: "deletion",
    begin: /^s+/,
    end: /$/,
    relevance: 10,
  }

  return {
    name: "Klipper Config",
    aliases: ["klipper", "cfg"],
    disableAutodetect: true,
    contains: [COMMENT, SECTION, KEY_PART, VALUE_PART, INDENTED_BLOCK],
  }
})

My issue is that I cannot get a regex or setting for properly matching the VALUE_PART, for example:

[idle_timeout]
gcode:
    {% if printer.pause_resume.is_paused %}

While a simple key/value pair, like step_pin: PC2, matches, the regex fails if the key is not directly followed by a value, but the statements are in an indented block below. The indented block should be formatted as INDENTED_BLOCK. See the following screenshot.

enter image description here

Basically, the VALUE_PART formatting is “bleeding into” this block, but only for the first line of such an indented block.

Fiddle with the code is here: https://jsfiddle.net/Sineos/54yz89e3/

Any pointer how to solve this would be really appreciated. Many thanks in advance.

When the second is added, the first marker’s info window remains stuck in place until I zoom out

I’m using the Google Maps JavaScript API with React and the @vis.gl/react-google-maps library. My implementation includes two components. The first marker has an InfoWindow that appears when clicked. The second marker is added dynamically when the user clicks on the map.

The issue is that when the second appears, the InfoWindow of the first marker gets stuck in the middle of the screen. The only way to get it to reposition correctly is by zooming out or panning the map to the first marker.

Here’s a simplified version of my implementation:

const [markerRef, marker] = useAdvancedMarkerRef();
const [markerRef2, marker2] = useAdvancedMarkerRef();
const [selectedCoords, setSelectedCoords] = useState({ lat: 18.220833, lng: -66.590149 });
const [infoWindowOpen, setInfoWindowOpen] = useState(false);
const [addCustomMarker, setAddCustomMarker] = useState<google.maps.LatLngLiteral | null>(null);

return (
  <APIProvider apiKey="YOUR_API_KEY">
  <Map
    clickableIcons={false}
    mapTypeControl={false}
    streetViewControl={false}
    mapId="map-client"
    className={styles.mapContainer}
    defaultCenter={selectedCoords}
    defaultZoom={16}
    id="map-client"
    gestureHandling="cooperative"
    key={mapKey}
    onClick={(event: MapMouseEvent) => {

        if (enableAddMarker)
            setAddCustomMarker(event.detail?.latLng);
    }}
>
    {selectedCoords && (
        <>
            <AdvancedMarker
                ref={markerRef}
                onClick={() => setInfoWindowOpen(true)}
                position={selectedCoords}
                title={'AdvancedMarker that opens an Infowindow when clicked.'}
            />
            {infoWindowOpen && (
                <InfoWindow
                    headerDisabled
                    anchor={marker}
                >
                    <label className="font-semibold text-xs">Current Location</label>
                </InfoWindow>
            )}
        </>
    )}

    {addCustomMarker !== null ? (
        <>
            <AdvancedMarker
                ref={markerRef2}
                draggable={true}
                position={addCustomMarker}
                onDragEnd={(e: google.maps.MapMouseEvent) => {
                    setAddCustomMarker(e.latLng?.toJSON());
                }}
            >
                <Pin
                    background={'#13294b'}
                    borderColor={'#13294b'}
                    glyphColor={'#D9FFFFFF '}
                />
            </AdvancedMarker>
            {infoWindowOpen2 && (
                <InfoWindow
                    anchor={marker2}
                    headerDisabled
                >
                    <label className="font-semibold text-xs">New Location</label>
                </InfoWindow>
            )}
        </>
    ) : null}
</Map>
</APIProvider>
);

Markers and Info windows after the search

Plotly not showing on GUI, however showing when writing to html

I am trying to build a GUI using html and javascript. The idea is to receive a file and then do some processing, resulting in a 2d plot and a 3d interactive plot. The 2d plot is displayed correctly, however, the 3d interactive plotly does not appear, instead a blank box appears in its place. I know the 3d plot is correct since when I write it to html using ”’fig_plotly.write_html(html_filename, auto_open=True)”’ it shows the correct interactive plot. Below is all my code, including python code, htlm, javascript and css. Additionally, you can find a screenshot of the webpage.screen shot

”’
#python code
app = Flask(name)

def process_dicom(file_path, net_path):
    V = # 3d image

    net = # my model
    
    slices = []
    fig, axes = plt.subplots(2, 2, figsize=(10, 10))
    
    axes[0, 0].imshow(B_2CH, cmap='gray', extent=extent_2CH, origin='lower')
    for line, plane_id in zip(intersections_2D_2CH, plane_ids_2CH):
        if len(line) == 0:  
            continue
        axes[0, 0].plot(line[:, 0], line[:, 1], plane_color[plane_id], linewidth=2, label = plane_id)
    axes[0, 0].set_title('2-chamber')
    axes[0,0].legend()

    # rest of plot

    plt.tight_layout()

    # saving figure into memory
    buf = io.BytesIO()
    plt.savefig(buf, format = 'png')
    buf.seek(0)
    img = Image.open(buf)

    img_byte_array = io.BytesIO()
    img.save(img_byte_array, format='PNG')
    img_byte_array.seek(0)
    plot_2D = "data:image/png;base64," + base64.b64encode(img_byte_array.read()).decode('utf-8')

    plt.close(fig)

    fig_plotly = go.Figure()

    fig_plotly.add_trace(go.Surface(
        x=coords_3D_2CH[0], y=coords_3D_2CH[1], z=coords_3D_2CH[2],
        surfacecolor=B_2CH, colorscale="gray", opacity=0.7, showscale=False
    ))

    for line in intersections_3D_2CH:
        fig_plotly.add_trace(go.Scatter3d(
            x=line[:, 0], y=line[:, 1], z=line[:, 2], mode="lines",
            line=dict(color="red", width=5)
        ))

    html_filename = 'first_figure.html'
    fig_plotly.write_html(html_filename, auto_open=True)

    with open(html_filename, 'r', encoding='utf-8') as f:
        plot_3D_html = f.read()

    return [plot_2D], plot_3D_html

@app.route('/')
def index():
    return render_template('index.html')

NET_PATH = "./models/model.pth"

# flask route to handle DICOM uploads
@app.route('/upload', methods=['POST'])
def upload_file():
    if 'dicom_file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    file = request.files['dicom_file']
    file_path = f"./uploads/{file.filename}"
    file.save(file_path)

    # Process the DICOM file
    plot_2D, plot_3D_html = process_dicom(file_path, NET_PATH)

    return jsonify({'plot_2D': plot_2D, 'plot_3D': plot_3D_html})


if __name__ == '__main__':
    app.run(debug=True)

”’

”’

html code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DICOM Image Viewer</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>

  <header>
    <h1> My Website </h1>
    <p> Upload a 3D image.</p>
  </header>

  <section id="upload-section">
    <form id="uploadForm" enctype="multipart/form-data">
      <input type="file" id="dicomFile" name="dicom_file" accept=".dcm">
      <button type="submit">Upload</button>
    </form>
    <div id="loading" class="hidden">
      <p>Processing...</p>
    </div>
  </section>

  <section id="plot2D-section">
    <h2>2D Slice</h2>
    <div id="plot2DContainer"></div>
  </section>

  <section id="plot3D-section">
    <h2>Interactive 3D Plot</h2>
    <div id="plot3DContainer" style="width: 100%; height: 600px;"></div>
  </section>

  <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>

”’

”’

javascript
document.getElementById('uploadForm').addEventListener('submit', async function (event) {
    event.preventDefault();

    const formData = new FormData();
    const dicomFile = document.getElementById('dicomFile').files[0];
    formData.append('dicom_file', dicomFile);

    document.getElementById('loading').style.display = 'block';

    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData,
        });

        document.getElementById('loading').style.display = 'none';

        const data = await response.json();

        // render 2D plot 
        if (data.plot_2D) {
            const container2D = document.getElementById('plot2DContainer');
            container2D.innerHTML = ''; 

            const img2D = document.createElement('img');
            img2D.src = data.plot_2D;
            img2D.style.width = "100%";
            container2D.appendChild(img2D);
        }

        // 3D plot, embed the returned HTML into an iframe
        if (data.plot_3D_html) {
            const container3D = document.getElementById('plot3DContainer');
            container3D.innerHTML = ''; 

            // iframe and set its srcdoc to the returned HTML content
            const iframe = document.createElement('iframe');
            iframe.style.width = "100%";
            iframe.style.height = "100%";
            iframe.style.border = "none";
            iframe.srcdoc = data.plot_3D_html;
            container3D.appendChild(iframe);
        }

    } catch (error) {
        document.getElementById('loading').style.display = 'none';
        alert('Error processing the file.');
        console.error(error);
    }
});

”’

”’

css file
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    text-align: center;
    background-color: #f8f9fa;
}

header {
    background-color: #007bff;
    color: white;
    padding: 20px;
}

#upload-section {
    margin: 20px;
}

#uploadForm input[type="file"] {
    padding: 10px;
}

#uploadForm button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    cursor: pointer;
}

#plot2DContainer img {
    width: 90%;
    max-width: 600px;
    margin: 10px;
}

#plot3DContainer {
    width: 90%;
    max-width: 800px;
    height: 600px;  
    margin: auto;
    border: 1px solid #ccc;  
}

”’

Why is my React component re-rendering on each keystroke when updating input fields?

I’m facing an issue in my React component where the input fields are re-rendering on every keystroke. I’ve tried optimizing it, but the problem persists. Here’s a breakdown of what I’ve tried and the code I’m working with:

I have several input forms in a component where the user can edit their names & addresses. The input fields update on every keystroke, which causes unnecessary re-renders of the entire component. I’m using React’s useState and useCallback to manage state and avoid unnecessary re-renders, but it doesn’t seem to work as expected.

import React, { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import './Account.css'

const Account = ({ user, setUser }) => {
  const [orders, setOrders] = useState([])
  const [addresses, setAddresses] = useState([])
  const [defaultAddressId, setDefaultAddressId] = useState(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [currentAddress, setCurrentAddress] = useState(null)
  const [selectedMainImages, setSelectedMainImages] = useState({})
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [addressToDelete, setAddressToDelete] = useState(null)
  const [showEditNameModal, setShowEditNameModal] = useState(false)
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [address, setAddress] = useState({
    street: '',
    city: '',
    state: '',
    zip: '',
    country: '',
    phone: '',
    isDefault: false,
  })
  const navigate = useNavigate()

  const fetchAddresses = useCallback(async () => {
    const accessToken = localStorage.getItem('accessToken')
    const response = await fetch(
      'http://localhost:8000/api/shopify/get-addresses',
      {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    )

    if (response.ok) {
      const data = await response.json()
      setAddresses(data.addresses)

      if (data.defaultAddressId) {
        setDefaultAddressId(data.defaultAddressId)
      } else if (data.addresses.length > 0) {
        setDefaultAddressId(data.addresses[0].id)
      }
    } else {
      console.error('Failed to fetch addresses')
    }
  }, [])

  const fetchOrders = useCallback(async () => {
    const accessToken = localStorage.getItem('accessToken')
    const response = await fetch(
      'http://localhost:8000/api/shopify/get-orders',
      {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    )

    if (response.ok) {
      const data = await response.json()
      setOrders(data.orders)
    } else {
      console.error('Failed to fetch orders')
    }
  }, [])

  const setDefaultAddress = async (addressId) => {
    const accessToken = localStorage.getItem('accessToken')
    const response = await fetch(
      'http://localhost:8000/api/shopify/set-default-address',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({ addressId }),
      }
    )

    if (response.ok) {
      setDefaultAddressId(addressId)
      alert('Default address updated successfully!')
    } else {
      const errorData = await response.json()
      alert(
        `Failed to update default address: ${
          errorData.error || 'Unknown error'
        }`
      )
    }
  }

  useEffect(() => {
    if (user) {
      fetchOrders()
      fetchAddresses()
    }
  }, [user, fetchAddresses, fetchOrders])

  const deleteAddress = async () => {
    if (!addressToDelete) return

    const accessToken = localStorage.getItem('accessToken')

    const isDeletingDefault = addressToDelete.id === defaultAddressId

    const response = await fetch(
      'http://localhost:8000/api/shopify/delete-address',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({ addressId: addressToDelete.id }),
      }
    )

    if (response.ok) {
      await fetchAddresses()

      if (isDeletingDefault) {
        const remainingAddresses = addresses.filter(
          (addr) => addr.id !== addressToDelete.id
        )
        if (remainingAddresses.length > 0) {
          await setDefaultAddress(remainingAddresses[0].id)
        }
      }

      setShowDeleteModal(false)
      setAddressToDelete(null)
      alert('Address deleted successfully!')
    } else {
      const errorData = await response.json()
      alert(`Failed to delete address: ${errorData.error || 'Unknown error'}`)
    }
  }

  const handleDeleteClick = (addr) => {
    if (addresses.length === 1) {
      alert('You must have at least one address.')
      return
    }

    setAddressToDelete(addr)
    setShowDeleteModal(true)
  }

  const handleAddressChange = (e) => {
    if (showEditModal) {
      setCurrentAddress({ ...currentAddress, [e.target.name]: e.target.value })
    } else {
      setAddress({ ...address, [e.target.name]: e.target.value })
    }
  }

  const handleThumbnailClick = (orderId, lineItemId, imageSrc) => {
    setSelectedMainImages((prev) => ({
      ...prev,
      [`${orderId}-${lineItemId}`]: imageSrc,
    }))
  }

  const addAddress = async () => {
    const accessToken = localStorage.getItem('accessToken')
    const response = await fetch(
      'http://localhost:8000/api/shopify/add-address',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify(address),
      }
    )

    if (response.ok) {
      const result = await response.json()

      if (result && result.addressId) {
        if (address.isDefault || addresses.length === 0) {
          setDefaultAddressId(result.addressId)
        }
      }

      await fetchAddresses()

      setAddress({
        street: '',
        city: '',
        state: '',
        zip: '',
        country: '',
        phone: '',
        isDefault: false,
      })

      setShowAddModal(false)
      alert('Address added!')
    } else {
      const errorData = await response.json()
      alert(`Failed to add address: ${errorData.message || 'Unknown error'}`)
    }
  }

  const editAddress = async () => {
    const accessToken = localStorage.getItem('accessToken')
    const response = await fetch(
      'http://localhost:8000/api/shopify/edit-address',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({
          addressId: currentAddress.id,
          street: currentAddress.street,
          city: currentAddress.city,
          state: currentAddress.state,
          zip: currentAddress.zip,
          country: currentAddress.country,
          phone: currentAddress.phone,
        }),
      }
    )

    if (response.ok) {
      await fetchAddresses()

      if (currentAddress.isDefault) {
        await setDefaultAddress(currentAddress.id)
      }

      setShowEditModal(false)
      alert('Address updated successfully!')
    } else {
      const errorData = await response.json()
      alert(`Failed to update address: ${errorData.error || 'Unknown error'}`)
    }
  }

  const handleEditClick = (addr) => {
    setCurrentAddress({
      ...addr,
      isDefault: addr.id === defaultAddressId,
    })
    setShowEditModal(true)
  }

  const updateName = async () => {
    const accessToken = localStorage.getItem('accessToken')

    if (!firstName && !lastName) {
      alert('Please enter at least one name field.')
      return
    }

    const response = await fetch(
      'http://localhost:8000/api/shopify/edit-name',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({ firstName, lastName }),
      }
    )

    if (response.ok) {
      const data = await response.json()
      setUser((prev) => ({
        ...prev,
        customer: {
          ...prev.customer,
          firstName: data.customer.firstName,
          lastName: data.customer.lastName,
        },
      }))
      alert('Name updated successfully!')
      setShowEditNameModal(false)
    } else {
      alert('Failed to update name.')
    }
  }

  const handleEditNameClick = () => {
    setFirstName(user?.customer.firstName || '')
    setLastName(user?.customer.lastName || '')
    setShowEditNameModal(true)
  }

  const logout = () => {
    localStorage.removeItem('accessToken')
    setUser(null)
    navigate('/login')
  }

  const Modal = ({ show, onClose, title, children }) => {
    if (!show) return null

    return (
      <div className="modal-backdrop">
        <div className="modal-content">
          <div className="modal-header">
            <h2>{title}</h2>
            <button onClick={onClose} className="close-button">
              &times;
            </button>
          </div>
          <div className="modal-body">{children}</div>
        </div>
      </div>
    )
  }

  if (!user) return <p>Loading...</p>

  return (
    <div className="account-container">
      <div className="account-header">
        <h1>Welcome, {user?.customer.firstName}!</h1>
        <button onClick={logout} className="logout-button">
          Logout
        </button>
      </div>
      <h1>Account Details</h1>
      <div className="account-details">
        <div className="name-container">
          <p>
            Name: {user?.customer.firstName} {user?.customer.lastName}
          </p>
          <p>Email: {user?.customer.email}</p>
        </div>
        <div className="edit-name-container">
          <button onClick={handleEditNameClick} className="edit-name-btn">
            Edit
          </button>
        </div>
      </div>

      <Modal
        show={showEditNameModal}
        onClose={() => setShowEditNameModal(false)}
        title="Edit Name"
      >
        <div className="name-edit-form">
          <div className="name-inputs">
            <label>
              First Name:{' '}
              <input
                type="text"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
              />
            </label>
            <label>
              Last Name:{' '}
              <input
                type="text"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
              />
            </label>
          </div>
          <div className="modal-actions">
            <button onClick={updateName} className="confirm-btn">
              Save Changes
            </button>
            <button
              onClick={() => setShowEditNameModal(false)}
              className="cancel-btn"
            >
              Cancel
            </button>
          </div>
        </div>
      </Modal>

      <h2>Your Addresses</h2>
      <div className="address-list">
        {addresses.length === 0 ? (
          <p>No addresses found.</p>
        ) : (
          addresses.map((addr) => (
            <div className="address-item" key={addr.id}>
              <div className="address-details">
                <p>
                  {addr.street}, {addr.city}, {addr.state}, {addr.zip},{' '}
                  {addr.country}
                  {addr.phone && ` • ${addr.phone}`}
                </p>
                {addr.id === defaultAddressId ? (
                  <span className="default-label">Default</span>
                ) : (
                  <span className="not-default-label">Not default</span>
                )}
              </div>
              <div className="address-actions">
                <button
                  className="edit-btn"
                  onClick={() => handleEditClick(addr)}
                >
                  Edit
                </button>
                <button
                  className="delete-btn"
                  onClick={() => handleDeleteClick(addr)}
                >
                  Delete
                </button>
              </div>
            </div>
          ))
        )}
      </div>

      <Modal
        className="delete-address-modal"
        show={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="Confirm Delete"
      >
        <div className="delete-confirmation">
          <p>Are you sure you want to delete this address?</p>
          {addressToDelete && (
            <div className="address-to-delete">
              <p>
                {addressToDelete.street}, {addressToDelete.city},{' '}
                {addressToDelete.state}, {addressToDelete.zip},{' '}
                {addressToDelete.country}
              </p>
            </div>
          )}
          <div className="modal-actions">
            <button onClick={deleteAddress} className="confirm-delete-btn">
              Yes, Delete
            </button>
            <button
              onClick={() => setShowDeleteModal(false)}
              className="cancel-delete-btn"
            >
              Cancel
            </button>
          </div>
        </div>
      </Modal>

      <div className="address-actions">
        <button
          className="add-address-btn"
          onClick={() => setShowAddModal(true)}
        >
          + Add New Address
        </button>
      </div>

      <Modal
        show={showAddModal}
        onClose={() => setShowAddModal(false)}
        title="Add New Address"
      >
        <div className="address-form">
          <div className="address-input">
            Street:{' '}
            <input
              name="street"
              placeholder="Street"
              value={address.street}
              onChange={handleAddressChange}
              required
            />
          </div>
          <div className="address-input">
            City:{' '}
            <input
              name="city"
              placeholder="City"
              value={address.city}
              onChange={handleAddressChange}
              required
            />
          </div>
          <div className="address-input">
            State:{' '}
            <input
              name="state"
              placeholder="State"
              value={address.state}
              onChange={handleAddressChange}
              required
            />
          </div>
          <div className="address-input">
            ZIP Code:{' '}
            <input
              name="zip"
              placeholder="ZIP Code"
              value={address.zip}
              onChange={handleAddressChange}
              required
            />
          </div>
          <div className="address-input">
            Country:{' '}
            <input
              name="country"
              placeholder="Country"
              value={address.country}
              onChange={handleAddressChange}
              required
            />
          </div>
          <div className="address-input">
            Phone Number:{' '}
            <input
              name="phone"
              placeholder="Phone Number"
              value={address.phone}
              onChange={handleAddressChange}
            />
          </div>
          <label className="checkbox-label">
            Set as Default
            <input
              type="checkbox"
              name="isDefault"
              checked={address.isDefault}
              onChange={(e) =>
                setAddress({ ...address, isDefault: e.target.checked })
              }
            />
          </label>
          <div className="modal-actions">
            <button onClick={addAddress} className="confirm-btn">
              Add Address
            </button>
            <button
              onClick={() => setShowAddModal(false)}
              className="cancel-btn"
            >
              Cancel
            </button>
          </div>
        </div>
      </Modal>

      <Modal
        className="edit-address-modal"
        show={showEditModal}
        onClose={() => setShowEditModal(false)}
        title="Edit Address"
      >
        {currentAddress && (
          <div className="address-form">
            <div className="address-input">
              Street:{' '}
              <input
                name="street"
                placeholder="Street"
                value={currentAddress.street}
                onChange={handleAddressChange}
                required
              />
            </div>
            <div className="address-input">
              City:{' '}
              <input
                name="city"
                placeholder="City"
                value={currentAddress.city}
                onChange={handleAddressChange}
                required
              />
            </div>
            <div className="address-input">
              State:{' '}
              <input
                name="state"
                placeholder="State"
                value={currentAddress.state}
                onChange={handleAddressChange}
                required
              />
            </div>
            <div className="address-input">
              ZIP Code:{' '}
              <input
                name="zip"
                placeholder="ZIP Code"
                value={currentAddress.zip}
                onChange={handleAddressChange}
                required
              />
            </div>
            <div className="address-input">
              Country:{' '}
              <input
                name="country"
                placeholder="Country"
                value={currentAddress.country}
                onChange={handleAddressChange}
                required
              />
            </div>
            <div className="address-input">
              Phone Number:{' '}
              <input
                name="phone"
                placeholder="Phone Number"
                value={currentAddress.phone}
                onChange={handleAddressChange}
              />
            </div>
            <label className="checkbox-label">
              Set as Default
              <input
                type="checkbox"
                name="isDefault"
                checked={currentAddress.isDefault}
                onChange={(e) =>
                  setCurrentAddress({
                    ...currentAddress,
                    isDefault: e.target.checked,
                  })
                }
              />
            </label>
            <div className="modal-actions">
              <button onClick={editAddress} className="confirm-btn">
                Save Changes
              </button>
              <button
                onClick={() => setShowEditModal(false)}
                className="cancel-btn"
              >
                Cancel
              </button>
            </div>
          </div>
        )}
      </Modal>

      <h2>Your Orders</h2>
      {orders.length === 0 ? (
        <p>No orders found.</p>
      ) : (
        <div className="order-items">
          {orders.map((order) => (
            <div key={order.id} className="order-item">
              <div className="order-item-image">
                {order.lineItems.length > 0 && (
                  <>
                    <img
                      src={
                        selectedMainImages[
                          `${order.id}-${order.lineItems[0].id}`
                        ] ||
                        order.lineItems[0].variant?.images[0] ||
                        'placeholder-image-url'
                      }
                      alt={order.lineItems[0].title}
                      className="order-main-image"
                    />
                    <div className="thumbnail-container">
                      {order.lineItems[0].variant?.images.map(
                        (imgSrc, index) => (
                          <img
                            key={index}
                            src={imgSrc}
                            alt={`Thumbnail ${index + 1}`}
                            className={`thumbnail ${
                              imgSrc ===
                              selectedMainImages[
                                `${order.id}-${order.lineItems[0].id}`
                              ]
                                ? 'active'
                                : ''
                            }`}
                            onClick={() =>
                              handleThumbnailClick(
                                order.id,
                                order.lineItems[0].id,
                                imgSrc
                              )
                            }
                          />
                        )
                      )}
                    </div>
                  </>
                )}
              </div>
              <div className="order-item-info">
                <div className="order-item-details">
                  <h3>Order: {order.name}</h3>
                  <p className="price">
                    Total: ${order.totalPrice} {order.currency}
                  </p>
                  <p>
                    Created At: {new Date(order.createdAt).toLocaleDateString()}
                  </p>
                  <p>Status: {order.fulfillmentStatus}</p>

                  <div className="order-line-items">
                    {order.lineItems.map((item, index) => (
                      <p key={index}>
                        {item.title} x {item.quantity}
                        {item.variant?.title ? ` - ${item.variant.title}` : ''}
                      </p>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default Account

Change cell value at certain times with javascript

I can’t find any resources to learn how to do this and I’m not very experienced with js

I have a table and I need one cells value to change at certain times

<tr class="view">
    <td>Subject1</td>
    <td id='s1'>OK</td>
    <td id='t1'>11:30</td>
</tr>

id=’t1′ is 11:30 but could be any time, I need td id=’s1′ value to change to ‘Begins in two hours’ at 09:30 (two hours before whatever the value in id=’t1′ is)
then I need it to change to ‘Begins in half an hour’ at 11:00
then change to ‘Closed’ at 11:30

What is the best way to accomplish this, everything I have attempted so far has turned to dust. I think I need a better plan of attack but haven’t found any relevant references. Is javascript the wrong way to attempt this? Please assist.

Xcode Build Fails – Command PhaseScriptExecution Failed Due to Missing Node Path – Xcode Version 16.2 – React Native iOS

I am working on a React Native project and encountering the following build error when trying to run my app on iOS using Xcode:

Node found at: /opt/homebrew/Cellar/node/22.6.0/bin/node
/Users/kiranjadhav/Library/Developer/Xcode/DerivedData/PivotalApp-fhfpmifbxjcwrmcuwtusqwdxiyas/Build/Intermediates.noindex/Pods.build/DebugStg-iphonesimulator/hermes-engine.build/Script-46EB2E00028700.sh: line 9: /opt/homebrew/Cellar/node/22.6.0/bin/node: No such file or directory
Command PhaseScriptExecution failed with a nonzero exit code

Rewriting nested loop with reduce [closed]

I wrote the below code to solve a prep test, found online. The goal is to find the min absolute difference between numbers in an array.

function minimumAbsoluteDifference(arr: number[]): number {
    // Write your code here
    let res = 0
    const length = arr.length
    let diff : number
    for (let i = 0; i < length; i++) {
        for (let j = 0; j < length; j++) {
            if (i !== j) {
                diff = Math.abs(arr[i] - arr[j])
                if (diff < res || res === 0)
                  res = diff
            }            
        }
    }
    return res
}

i ran tests on Math.abs(), and these days it is faster than a bitshift version… It seems that the only way to make this faster, is either with a reduce, or create a hash to optimize the nested array version.

Any ideas how to rewrite this with reduce()?

How to Build a T-Shirt Mockup Web App with Realistic Wrinkles & Color Change? [closed]

I want to build a web app where I can upload my designs and place them on t-shirt mockups. The tricky part is making the designs wrap realistically to match the t-shirt fabric’s wrinkles and creases—like in those high-quality mockup generators.

I also want to change the t-shirt color. I want to build something like this

Does anyone know what techniques or libraries can help with this? Any guidance on how to implement this in a web app would be really helpful!

problem to add the external script in my js file by CSP

Refused to load the script ‘https://cdn.jsdelivr.net/npm/[email protected]/dist/tesseract.min.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval’ ‘inline-speculation-rules’ http://localhost:* http://127.0.0.1:* chrome-extension://3aa17153-bad6-4578-a0d8-fc68e2278d10/”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

is it possible to output the full callstack in nodejs [duplicate]

I am capture the node error info like this:

process.on("uncaughtException", (error, origin) => {
  logger.error("uncaughtException", error, origin);
});

this works fine but I have a issue, the error output like this:

│ [2025-03-26T10:52:17.267] [ERROR] default - uncaughtException Error: connect ECONNREFUSED 10.109.79.31:8000                                                                     │
│     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {                                                                                                         │
│   errno: -111,                                                                                                                                                                  │
│   code: 'ECONNREFUSED',                                                                                                                                                         │
│   syscall: 'connect',                                                                                                                                                           │
│   address: '10.109.79.31',                                                                                                                                                      │
│   port: 8000                                                                                                                                                                    │
│ } uncaughtException

is it possible to output the full call stack? from this error I know there contains an error, but I could not know where is going on or the error come from without full callstack info.