Semantic Segmentation video using PixelLib Python

I’m a beginner in python, I haven’t been there for a long time.
I am researching on the topic semantic segmentation of video with pixelLib. When I try to run this code, it doesn’t work.I already have downloaded PixelLib in Python and pre-trained model called Xception which has been trained on the ade20k dataset.

Website used to inform me: https://www.theclickreader.com/semantic-and-instance-segmentation-on-videos-using-pixellib/

Code used: (the code does not run for me)
I need the complete correct code to transform my video into semantic segmentation.

# Omporting the semantic_segmentation object type from pixellib.semantic
from pixellib.semantic import semantic_segmentation

# Setting the file path for the input video
input_video_file_path = "videos/test_video.mp4"

# Creating a semantic_segmentation object
segment_video = semantic_segmentation()

# Loading the Xception model trained on ade20k dataset
segment_video.load_ade20k_model("deeplabv3_xception65_ade20k.h5")

# Processing the video
segment_video.process_video_ade20k(
    `input_video_file_path, 
    `frames_per_second`=30,
    output_video_name="videos/semantic_segmentation_output.mp4",
)`

JS Class create multiple callback functions

I’m trying to create a modal class that, among other things, would be able to catch the onClose & onSubmit events and handle them separately.

So in one side of my app I would be doing something like this:

new Modal().setTitle('Some title')
    .onClose(function(form, modal)
    {   
        
    })
    .onSubmit(function(form, modal)
    {

    });

And somewhere else I might just do:

new Modal().setTitle('Some title');

If not possible, I’m ok with not nesting the functions:

const modal = new Modal().setTitle('Some title');
modal.onClose = function(form, modal)
{
    
};
modal.onSubmit = function(form, modal)
{
    
};

With that said, my current class is the following and can be seen in JSFiddle:

class Modal
{
    #btnClose;
    #btnConfirm;
    #modal;
    #form;

    constructor()
    {
        const self = this;

        this.#btnClose = document.getElementById('btn-close');
        this.#btnConfirm = document.getElementById('btn-confirm');
        this.#form = document.getElementById('form');    
        this.#modal = new bootstrap.Modal(document.getElementById('modal'), {});
        this.#modal.toggle();
        this.#btnClose.onclick = function()
        {
            self.#_onClose(self);
        }
    }

    #_onClose(self)
    {
        // default behavior
        self.#modal.toggle();
        
        // should call onClose() function
        self.onClose(() => (self.#form, self.#modal));
    }


    onClose(callback)
    {
        callback(this.#form, this.#modal);
        
        return this;
    }
}

Problems:

  1. The onClose() function is being called after pressing the «Open modal» button
  2. The onClose() function is never called after pressing the «Close» button

How can I achieve the desired result?

Vercel – Next.js 13 – problems when building

I’m having trouble deploying my Next.js 13.4.4 app on Vercel. I had this app working previously, and I updated my endpoints with the new structure inside the app folder. I also implemented a middleware. Everything works perfectly fine in my local environment, and even building the app locally works correctly. However, the problem arises when I try to deploy it on Vercel, and it throws this error…

enter image description here

I’m sharing the screenshot of the complete Vercel log and also the error text in case you want to copy it

"SyntaxError: Unexpected end of JSON input"

"Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error"

Something that seems very strange to me is that when I try to redeploy another point where the app was working fine before, it now returns the same error during the build. I hope you can help me. Thank you very much in advance.

The information I found suggested that I should check the dependencies since this error often occurs when accidentally importing a library. However, that’s not the case for me. Another recommendation is to verify if we have a JSON file since it can cause an error if it’s structured incorrectly. However, upon reviewing it, I see that everything is correct.

How to apply image change on React element, when hovering over another

So what I want to do sounds simple. I actually did it before, when I was making this project of mine before learning React, and I used plain JavaScript and JQuery.

So in this Homepage.js component, I have one section and it has 2 children, ‘s1-left-div’ and ‘s1-right-div’.

Inside the ‘s1-right-div’ resides a ‘gradient-img-container’ div that basically has an image as a background, set through scss ‘background-image: url()’ property.
Now, when I hover over any of the ‘s1-left-div’ buttons, I want the image of the ‘s1-right-div’ to change.
Basically, there’s 3 buttons on the left div, and I want each one to display its own image in the right div.
And by my experience, I thought it’s easy to access and modify the background-image property in scss, but it’s just unreachable and I don’t know what causes this issue.

Can you help me figure out how to hover and modify properly?
Should be very simple and I feel I’m missing something, but what…
I have shared pastebin links for you in my comment below.
Thank you in advance!

ChartJs Legend OnClick Update Datasets

I’m new to ChartJs and I want your help please, as you can see I have a mixed chart in the image below, what I want to happen is to; Update both of my Line One and Line Two datasets dynamically when I clicked either Bar One and Bar Two. Is there a tooltip should I use here?

Output : https://jsfiddle.net/juvielonelagos/qjav2gmL/1/

 const ctx = document.getElementById("myChart");

      new Chart(ctx, {
        data: {
          datasets: [
            {
              type: "line",
              label: "Line One",
              data: [10, 30, 21, 11],
              backgroundColor: "blue",
              borderColor: "blue",
            },
            {
              type: "line",
              label: "Line Two",
              data: [20, 24, 13, 30],
              backgroundColor: "red",
              borderColor: "red",
            },
            {
              type: "bar",
              label: "Bar One",
              data: [10, 20, 30, 40],
              backgroundColor: "orange",
            },
            {
              type: "bar",
              label: "Bar Two",
              data: [10, 30, 20, 13],
              backgroundColor: "purple",
            },
          ],
          labels: ["January", "February", "March", "April"],
        },
      });

      document.getElementById("red").style.back;

enter image description here

Append html if no rows are visible with selected dropdowns

I’m using this script(filtering html table columns with select dropdowns) from an old Question to filter a table via select options and I would like to append data, when all rows are hidden/ or when there are no results under that filter choise.

I basically want to add sth like, no results found under this query.

I’ve tried adding something like this, but nothing is happening.

const
  table = document.querySelector('.filter-table'),
  filterState = {};

const dataFromRow = (row, headers) =>
  Object.fromEntries([...row.querySelectorAll('td')]
    .map((td, index) => [headers[index], td.textContent]));

const matchesCriteria = (rowData, filters) =>
  filters.every(([key, value]) => rowData[key] === value);

const refresh = () => {
  const
    headers = [...table.querySelectorAll('thead th')].map(th => th.textContent),
    filters = Object.entries(filterState),
    showAll = filters.length === 0;
  table.querySelectorAll('tbody tr').forEach(row => {
    const show = showAll || matchesCriteria(dataFromRow(row, headers), filters);
    row.classList.toggle('hidden-row', !show);
  });
};

const handleFilterChange = (e) => {
  const
    field = e.target.dataset.field,
    value = e.target.value;
  if (value) { filterState[field] = value; }
  else { delete filterState[field]; }
  refresh();
};

document.querySelectorAll('.filter').forEach(filter =>
  filter.addEventListener('change', handleFilterChange));

                        const jobrow = document.querySelectorAll("tbody tr.hidden-row");
                        hiddenrows = Array.from(jobrow);
                        console.log(hiddenrows);
                        let result = hiddenrows.every(isSameAnswer);

                        function isSameAnswer(el, index, arr) {
                        if (index === 0) {
                            return true;
                        } else {
                            return (el.answer === arr[index - 1].answer);
                        }
                        }
  .filter-table {
    border-collapse: collapse;
  }
  
  .filter-table {
    border: thin solid grey;
  }
  
  .filter-table thead {
    border-bottom: thin solid grey;
  }
  
  .filter-table th, .filter-table td {
    padding: 0.25em 0.5em;
  }
  
  .filter-table th {
    background: #CCC;
  }
  
  .filter-table tbody tr:nth-child(even) {
    background: #EEE;
  }
  
  .hidden-row {
    display: none;
  }
  <select class="filter" data-field="Status">
  <option value="">None</option>
  <option value="OK">OK</option>
  <option value="NO">NO</option>
</select>
<select class="filter" data-field="Cough">
  <option value="">None</option>
  <option value="No">No</option>
  <option value="Yes">Yes</option>
</select>
<select class="filter" data-field="Fever">
  <option value="">None</option>
  <option value="No">No</option>
  <option value="Yes">Yes</option>
</select>
<hr />
<table class="filter-table">
  <thead>
    <tr><th>Status</th><th>Cough</th><th>Fever</th></tr>
  </thead>
  <tbody>
    <tr><td>OK</td><td>No</td><td>Yes</td></tr>
    <tr><td>NO</td><td>Yes</td><td>Yes</td></tr>
    <tr><td>OK</td><td>No</td><td>No</td></tr>
    <tr><td>NO</td><td>Yes</td><td>No</td></tr>
  </tbody>
</table>

JavaScript modify nested arrays to array of objects

I’ve an resultant array and needs serious modification

[
    [
        {
            "name": "Attestation Component - 1",
            "values": [
                {
                    "crId": "10005887",
                    "component": "Attestation Component - 1",
                }
            ]
        }
    ],
    [
        {
            "name": "Attestation Component - 2",
            "values": [
                {
                    "bfaId": "G44.5.3.1N/A",
                    "component": "Attestation Component - 2",
                }
            ]
        }
    ]
]

Expected O/P

[
    {
        "name": "Attestation Component - 1",
        "values": [
            {
                "crId": "10005887",
                "component": "Attestation Component - 1",
            }
        ]
    },
    {
        "name": "Attestation Component - 2",
        "values": [
            {
                "bfaId": "G44.5.3.1N/A",
                "component": "Attestation Component - 2",
            }
        ]
    }
]

I’ve some nested arrays Set, and I need an single level array of object, I’m unable to convert it to the expected O/P. How can I achieve the expected O/P? Would be great if anyone can throw some light on the steps I need to perform. Thanks

canvas element flashing when i move it

I have a project with NextJS, and I want to create a canvas that contains svg images.
I was able to create the canvas element, add the images to it, and also implement the logic of moving one element in the canvas, but the problem is that when I drag an element, all the elements flash (because I clear the canvas and redraw the elements), and I don’t know how to prevent that from happening.

jsx code :

 <div style={{ width: "100%", height: "calc(100% - 40px)", overflow: "scroll" }}>
      <canvas
        width={1210}
        height={495}
        style={{ backgroundColor: "#FFF" }}
        id="canvas-container"
        ref={canvasRef}
      ></canvas>
    </div>

The logic of draw the images and moving them :

const canvasRef = useRef(null);
  let [canvas, setCanvas] = useState(null);
  let [context, setContext] = useState(null);
  let [tablesState, setTablesState] = useState([]);

  function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (const el of tablesState) {
      let image = new Image();
      switch (el.shape) {
        case "square":
          image.onload = function () {
            context.drawImage(image, el.x, el.y, 80, 80);
          };
          image.src =
            "data:image/svg+xml;base64," +
            window.btoa(`
          <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="140" height="140">
          <defs>
          </defs>
          <rect x="20" y="20" fill="#CCC" width="100" height="100"/>
          <text id="tableNumText" x="70" y="70" text-anchor="middle" alignment-baseline="middle" fill="#000" font-size="26px">${el.tableNbr}</text>
          <circle cx="115" cy="25" r="25" fill="#000"/>
          <text id="bookingInfo" x="115" y="27" text-anchor="middle" alignment-baseline="middle" fill="#FFF" font-weight="700"    font-size="24px">-/${el.nbrPlaces}</text>
          </svg>`);
          break;

        case "oval":
          image.onload = function () {
            context.drawImage(image, el.x, el.y, 140, 100);
          };
          image.src =
            "data:image/svg+xml;base64," +
            window.btoa(`
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="190" height="140">
        <defs>
        </defs>
        <ellipse cx="100" cy="70" rx="80" ry="50" fill = "#CCC" />
        <text id="tableNumText" x="100" y="70" text-anchor="middle" alignment-baseline="middle" fill="#000" font-size="26px">${el.tableNbr}</text>
        <circle cx="160" cy="30" r="25" fill="#000"/>
        <text id="bookingInfo" x="160" y="30" text-anchor="middle" alignment-baseline="middle" fill="#FFF" font-weight="700" font-size="24px">-/${el.nbrPlaces}</text>
        </svg>`);
          break;

        case "rectangular":
          image.onload = function () {
            context.drawImage(image, el.x, el.y, 150, 100);
          };
          image.src =
            "data:image/svg+xml;base64," +
            window.btoa(`
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="210" height="140">
        <defs>
        </defs>
        <rect width = "150" height = "100"  x="20" y="20"  fill="#CCC"/>
        <text id="tableNumText" x="95" y="70" text-anchor="middle" alignment-baseline="middle" fill="#000" font-size="26px">${el.tableNbr}</text>
        <circle cx="170" cy="30" r="25" fill="#000"/>
        <text id="bookingInfo" x="170" y="30" text-anchor="middle" alignment-baseline="middle" fill="#FFF" font-weight="700" font-size="24px">-/${el.nbrPlaces}</text>
        </svg>`);
          break;

        default: // circle
          image.onload = function () {
            context.drawImage(image, el.x, el.y, 80, 80);
          };
          image.src =
            "data:image/svg+xml;base64," +
            window.btoa(`
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="140" height="140">
      <defs>
      </defs>
      <circle cx="70" cy="70" r = "50" fill="#CCC"/>
      <text id="tableNumText" x="70" y="70" text-anchor="middle" alignment-baseline="middle" fill="#000" font-size="26px">${el.tableNbr}</text>
      <circle cx="110" cy="35" r="25" fill="#000"/>
      <text id="bookingInfo" x="110" y="35" text-anchor="middle" alignment-baseline="middle" fill="#FFF" font-weight="700" font-size="24px">-/${el.nbrPlaces}</text>
      </svg>`);
          break;
      }
    }
  }

  const hitElement = (x, y, index) => {
    let element = tablesState.find((el) => el.id === index);
    let height = element?.shape === "square" || element?.shape === "circle" ? 80 : 100;
    let width = element?.shape === "square" || element?.shape === "circle" ? 70 : 150;

    return (
      x >= element?.x && x <= element?.x + width && y >= element?.y && y <= element?.y + height
    );
  };

  useEffect(() => {
    setTablesState(tables);
  }, []);

  useEffect(() => {
    if (!canvasRef) return;

    setCanvas(canvasRef.current);
  }, [canvasRef]);

  useEffect(() => {
    if (!canvas) return;

    setContext(canvas.getContext("2d"));
  }, [canvas]);

  useEffect(() => {
    if (!context) return;

    if (!isDragging) {
      draw();
    }
    let prevX = 0;
    let prevY = 0;
    let isDragging = false;
    let selectedElement = -1;

    const handleMouseDown = (event) => {
      event.preventDefault();
      isDragging = true;

      prevX = event.offsetX;
      prevY = event.offsetY;

      for (var i = 0; i < tablesState.length; i++) {
        if (hitElement(prevX, prevY, i)) {
          selectedElement = i;
        }
      }
    };

    const handleMouseUp = (e) => {
      e.preventDefault();
      isDragging = false;
      selectedElement = -1;
    };

    function handleMouseOut(e) {
      e.preventDefault();
      isDragging = false;
      selectedElement = -1;
    }

    const handleMouseMove = (event) => {
      if (!isDragging || selectedElement === -1) return;
      event.preventDefault();

      let element = tablesState.find((el) => el.id === selectedElement);

      let width = element?.shape === "square" || element?.shape === "circle" ? 80 : 150;
      let height = element?.shape === "square" || element?.shape === "circle" ? 80 : 100;

      tablesState?.map((el) => {
        if (el.id === selectedElement) {
          el.x = event.offsetX - width / 2;
          el.y = event.offsetY - height / 2;
        }
        return el;
      });

      draw();
    };

    canvas.addEventListener("mousedown", handleMouseDown);
    canvas.addEventListener("mouseup", handleMouseUp);
    canvas.addEventListener("mousemove", handleMouseMove);
    canvas.addEventListener("mouseout", handleMouseOut);

    return () => {
      canvas.removeEventListener("mousedown", handleMouseDown);
      canvas.removeEventListener("mouseup", handleMouseUp);
      canvas.removeEventListener("mousemove", handleMouseMove);
      canvas.removeEventListener("mouseout", handleMouseOut);
    };
  }, [context]);

tablesState contains the data in this format :

[
  {
    id: 0,
    tableNbr: 159,
    shape: "circle",
    color: "#AAA",
    x: 50,
    y: 150,
    nbrPlaces: 2,
    isDragging: false,
  },
  {
    id: 1,
    tableNbr: 357,
    shape: "square",
    color: "#AAA",
    x: 100,
    y: 50,
    nbrPlaces: 4,
    isDragging: false,
  },... ]

I need any help with that guys thank you in advance

E2E Playwright (JS, TS): how can i wait a loader disappear when have more than 1 element on page? it’s need to wait all elements

(JS) I’m trying to wait a loader (div class=”loader” data-testid=”form-loader”) disappear on my page.

The test is failing because the loader doesn’t allow saving the form but my methods isn’t working.

I too have tried to use a function and Promise.all with waitForElementState(‘hidden’), but doesn’t work. It’s necessary to get all elements of this component (with $$, all() or another way) because the page is finding more than 2 elements (sometimes is 3 or more).

My methods:

function (called by await waitForLoadersToDisappear(page)), i’ve tried with page.$$ too:

async waitForLoadersToDisappear() {
  const loaders = await this.page.getByTestId('form-loader').all(); 

  await Promise.all(
    loaders.map(async (loader) => {
      await loader.waitForElementState('hidden');
    }),
  );
}

I too have tried this methods without functions:

await expect(page.$$('.loader')).toBeHidden();

await expect(page.locator('div[class="loader"]')).toBeHidden();

await expect(page.getByTestId('form-loader').all()).toBeHidden();

const loader = page.$$('form-loader'); //tried with locator.all() too await loader.waitForElementState('hidden');

Loader image:
enter image description here

HTML element:
enter image description here

Maybe can i wait this ::before stop works?

Javascript: Get id for one of many similar divs

I am using the following code form w3schools that uses a button to toggle text:

function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

Now, I want to have a page with many buttons that toggle different texts (every button corresponds to a unique text). Of course, I can make it work by copying the function each time I create a new text; myFunction1 <-> myDIV1, myFunction2 <-> myDIV2 etc.

But is there a smarter way to do it? I am thinking it can be done with a single function that select id’s in a specific form but I don’t know how.

“React does not recognize the `staticContext` prop on a DOM element” but I’m not using it at anywhere

The error:

index.js:1 Warning: React does not recognize the `staticContext` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `staticcontext` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
        at svg
        at SvgIcon (http://localhost:3000/material-dashboard-act/static/js/vendors~main.chunk.js:14367:24)
        at WithStyles (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:24127:31)
        at DashboardIcon
        at Route (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:80337:29)
        at Switch (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:80508:29)
        at div
        at div
        at div
        at div
        at Admin (http://localhost:3000/material-dashboard-react/static/js/main.chunk.js:11031:173)
        at Route (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:80337:29)
        at Switch (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:80508:29)
        at Router (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:80019:30)
        at BrowserRouter (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:78856:35)
        at PersistGate (http://localhost:3000/material-dashboard-react/static/js/vendors~main.chunk.js:87045:5)
        at Provider

Dashboard.js:

/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from "react";

////////// REACT PLUGINS FOR CREATING CHARTS //////////
import ChartistGraph from "react-chartist";

////////// MATERIAL-UI CORE //////////
import { makeStyles } from "@material-ui/core/styles";
import { Box, Container, Typography } from "@material-ui/core";

////////// MATERIAL-UI ICONS //////////
import ArrowUpward from "@material-ui/icons/ArrowUpward";
import AccessTime from "@material-ui/icons/AccessTime";
import BugReport from "@material-ui/icons/BugReport";
import Code from "@material-ui/icons/Code";
import Cloud from "@material-ui/icons/Cloud";
import FlightTakeoffIcon from "@mui/icons-material/FlightTakeoff";
import NightShelterIcon from "@mui/icons-material/NightShelter";
import LocalOfferIcon from "@mui/icons-material/LocalOffer";
import MonetizationOnIcon from "@mui/icons-material/MonetizationOn";

////////// CORE COMPONENTS //////////
import GridItem from "components/Grid/GridItem.js";
import GridContainer from "components/Grid/GridContainer.js";
import Table from "components/Table/Table.js";
import Tasks from "components/Tasks/Tasks.js";
import CustomTabs from "components/CustomTabs/CustomTabs.js";
import Card from "components/Card/Card.js";
import CardHeader from "components/Card/CardHeader.js";
import CardIcon from "components/Card/CardIcon.js";
import CardBody from "components/Card/CardBody.js";
import CardFooter from "components/Card/CardFooter.js";

////////// VARIABLES //////////
import { bugs, website, server } from "variables/general.js";
import {
  dailySalesChart,
  emailsSubscriptionChart,
  completedTasksChart,
} from "variables/charts.js";

////////// STYLES //////////
import styles from "assets/jss/material-dashboard-react/views/dashboardStyle.js";
import { useSnackbar } from "notistack";

////////// REACT REDUX //////////!SECTION
import { useSelector } from "react-redux";

////////// REACT ROUTER //////////!SECTION
import { useHistory } from "react-router-dom";

////////// FETCHING APIS //////////
import {
  getSpecificCustomer,
  getSpecificWallet,
  getAllBookings,
} from "../../crud";

const useStyles = makeStyles(styles);

export default function Dashboard() {
  const classes = useStyles();
  const history = useHistory();
  const [type, setType] = useState("");
  const [render, setRender] = useState("all");
  const { enqueueSnackbar } = useSnackbar();

  ///// STATES FOR DISPLAYING NAME /////
  const [firstName, setFirstName] = useState("");
  const [middleName, setMiddleName] = useState("");
  const [lastName, setLastName] = useState("");

  ////////// STATES FOR DISPLAYING VALUE (FLIGHTS && TRAVEL_PACKAGES && HOTEL) //////////
  const [listBookings, setListBookings] = useState([]);
  const [totalPage, setTotalPage] = useState(1);
  const [totalRecord, setTotalRecord] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");

  ///// STATES FOR DISPLAYING ACCOUNT BALANCE /////
  const [balance, setBalance] = useState(0);

  ///// DISPLAYING DATA AFTER THE COMPONENT RENDERED PERFECTLY /////
  useEffect(() => {
    fetchData();
  }, []);

  ///// DEFINING USER BY USERID /////
  const userId = useSelector(
    ({
      user: {
        user: { sub },
      },
    }) => sub
  );

  ////////// INTEGRATTING APIS /////////!SECTION
  useEffect(() => {
    const bookingType = localStorage.getItem("bookingType");
    const bookingDetails = JSON.parse(localStorage.getItem("bookingDetails"));
    if (bookingDetails && bookingType) {
      history.push("/customer/booking");
    }

    ///// USER DATA /////
    getSpecificCustomer(userId)
      .then((res) => {
        loadValuesHandler(res.data.data.customer);
      })
      .catch((error) => {
        if (error.response.status === 401) {
          history.push("/401");
        } else {
          console.log(error.response.data);
          console.log(error.response.status);
          enqueueSnackbar("Unable to fetch data.", {
            variant: "error",
          });
        }
      });
  }, []);

  //// USER ACCOUNT BALANCE /////
  getSpecificWallet(userId)
    .then((res) => {
      setBalance(res?.data?.data?.wallet?.balance);
    })
    .catch((error) => {
      if (error?.response?.status === 401) {
        history.push("/401");
      } else {
        console.log(error?.response?.data);
        console.log(error?.response?.status);
        enqueueSnackbar("Unable to fetch data.", {
          variant: "error",
        });
      }
    });

  //// FETCHING USER INFO /////
  const loadValuesHandler = (user) => {
    setFirstName(user.firstName ? user.firstName : "");
    setMiddleName(user.middleName ? user.middleName : "");
    setLastName(user.lastName ? user.lastName : "");
  };

  ///// DISPLAYING NUMBER OF BOOKINGS ////
  const fetchData = () => {
    const params = {
      search: '{"query":""}',
      sort: "_id",
      page,
      pageSize: 10000,
    };
    getAllBookings(params)
      .then((res) => {
        console.log(res.data.data);
        setListBookings(res.data.data.bookings);
        setTotalPage(res.data.data.totalPages);
        setTotalRecord(res.data.data.totalRecords);
      })
      .catch((error) => {
        if (error.response.status === 401) {
          history.push("/401");
        } else {
          console.log(error.response.data);
          console.log(error.response.status);
          enqueueSnackbar("Unable to fetch data.", {
            variant: "error",
          });
        }
      });
  };

  ///// FORMATTING THE NUMBER THAT /////
  ///// IF THE VALUE LENGTH IS IN THOUSANDS /////
  ///// THE VALUE WILL HAVE A K OR MILLION /////
  ///// WITH IT /////
  const formatNumber = (num) => {
    if (num >= 1000 && num < 1000000) {
      return (num / 1000).toFixed(1) + "k";
    } else if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + "m";
    } else {
      return num;
    }
  };

  return (
    <div>
      <Container maxWidth="lg">
        <Typography variant="h5">
          Welcome {firstName} {middleName} {lastName}!
        </Typography>
      </Container>
      <Box justifyContent="start">
        <hr style={{ lineHeight: "1px" }} />
      </Box>
      <GridContainer>
        <GridItem xs={12} sm={6} md={3}>
          <Card>
            <CardHeader color="warning" stats icon>
              <CardIcon color="warning">
                <FlightTakeoffIcon />
              </CardIcon>
              <p className={classes.cardCategory}>Flights</p>
              <h3 className={classes.cardTitle}>
                {listBookings
                  .filter((bkg) => bkg.lob === "AIR")
                  .map((bkg) => (
                    <span
                      className={classes.tr}
                      onClick={() => {
                        setType(bkg.lob);
                        setRender(bkg._id);
                      }}
                      key={bkg._id}
                    >
                      {bkg.lob}
                    </span>
                  )).length && listBookings.length === 0
                  ? `No Flights Booked`
                  : formatNumber(listBookings.length)}
              </h3>
            </CardHeader>
            <CardFooter stats>
              <div className={classes.stats}>All Tme Book Ticket</div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={6} md={3}>
          <Card>
            <CardHeader color="success" stats icon>
              <CardIcon color="success">
                <NightShelterIcon />
              </CardIcon>
              <p className={classes.cardCategory}>Hotels</p>
              <h3 className={classes.cardTitle}>
                {listBookings
                  .filter((bkg) => bkg.lob === "HOTEL")
                  .map((bkg) => (
                    <span
                      className={classes.tr}
                      onClick={() => {
                        setType(bkg.lob);
                        setRender(bkg._id);
                      }}
                      key={bkg._id}
                    >
                      {bkg.lob}
                    </span>
                  )).length && listBookings.length === 0
                  ? `No Hotels Booked`
                  : formatNumber(listBookings.length)}
              </h3>
            </CardHeader>
            <CardFooter stats>
              <div className={classes.stats}>All Time Available Hotels</div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={6} md={3}>
          <Card>
            <CardHeader color="danger" stats icon>
              <CardIcon color="danger">
                <LocalOfferIcon />
              </CardIcon>
              <p className={classes.cardCategory}>Packages</p>
              <h3 className={classes.cardTitle}>
                {listBookings
                  .filter((bkg) => bkg.lob === "TRAVEL_PACKAGE")
                  .map((bkg) => (
                    <span
                      className={classes.tr}
                      onClick={() => {
                        setType(bkg.lob);
                        setRender(bkg._id);
                      }}
                      key={bkg._id}
                    >
                      {bkg.lob}
                    </span>
                  )).length && listBookings.length === 0
                  ? `No Hotels Booked`
                  : formatNumber(listBookings.length)}
              </h3>
            </CardHeader>
            <CardFooter stats>
              <div className={classes.stats}>All Time Available Packages</div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={6} md={3}>
          <Card>
            <CardHeader color="info" stats icon>
              <CardIcon color="info">
                <MonetizationOnIcon />
              </CardIcon>
              <p className={classes.cardCategory}>Your BalancE</p>
              <h3 className={classes.cardTitle}>
                {balance.length === 0
                  ? `No Balance In Account`
                  : formatNumber(balance)}
              </h3>
            </CardHeader>
            <CardFooter stats>
              <div className={classes.stats}>All Time Balance</div>
            </CardFooter>
          </Card>
        </GridItem>
      </GridContainer>
      <GridContainer>
        <GridItem xs={12} sm={12} md={4}>
          <Card chart>
            <CardHeader color="success">
              <ChartistGraph
                className="ct-chart"
                data={dailySalesChart.data}
                type="Line"
                options={dailySalesChart.options}
                listener={dailySalesChart.animation}
              />
            </CardHeader>
            <CardBody>
              <h4 className={classes.cardTitle}>Daily Sales</h4>
              <p className={classes.cardCategory}>
                <span className={classes.successText}>
                  <ArrowUpward className={classes.upArrowCardCategory} /> 55%
                </span>{" "}
                increase in today sales.
              </p>
            </CardBody>
            <CardFooter chart>
              <div className={classes.stats}>
                <AccessTime /> updated 4 minutes ago
              </div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={12} md={4}>
          <Card chart>
            <CardHeader color="warning">
              <ChartistGraph
                className="ct-chart"
                data={emailsSubscriptionChart.data}
                type="Bar"
                options={emailsSubscriptionChart.options}
                responsiveOptions={emailsSubscriptionChart.responsiveOptions}
                listener={emailsSubscriptionChart.animation}
              />
            </CardHeader>
            <CardBody>
              <h4 className={classes.cardTitle}>Email Subscriptions</h4>
              <p className={classes.cardCategory}>Last Campaign Performance</p>
            </CardBody>
            <CardFooter chart>
              <div className={classes.stats}>
                <AccessTime /> campaign sent 2 days ago
              </div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={12} md={4}>
          <Card chart>
            <CardHeader color="danger">
              <ChartistGraph
                className="ct-chart"
                data={completedTasksChart.data}
                type="Line"
                options={completedTasksChart.options}
                listener={completedTasksChart.animation}
              />
            </CardHeader>
            <CardBody>
              <h4 className={classes.cardTitle}>Completed Tasks</h4>
              <p className={classes.cardCategory}>Last Campaign Performance</p>
            </CardBody>
            <CardFooter chart>
              <div className={classes.stats}>
                <AccessTime /> campaign sent 2 days ago
              </div>
            </CardFooter>
          </Card>
        </GridItem>
      </GridContainer>
      <GridContainer>
        <GridItem xs={12} sm={12} md={6}>
          <CustomTabs
            title="Tasks:"
            headerColor="primary"
            tabs={[
              {
                tabName: "Bugs",
                tabIcon: BugReport,
                tabContent: (
                  <Tasks
                    checkedIndexes={[0, 3]}
                    tasksIndexes={[0, 1, 2, 3]}
                    tasks={bugs}
                  />
                ),
              },
              {
                tabName: "Website",
                tabIcon: Code,
                tabContent: (
                  <Tasks
                    checkedIndexes={[0]}
                    tasksIndexes={[0, 1]}
                    tasks={website}
                  />
                ),
              },
              {
                tabName: "Server",
                tabIcon: Cloud,
                tabContent: (
                  <Tasks
                    checkedIndexes={[1]}
                    tasksIndexes={[0, 1, 2]}
                    tasks={server}
                  />
                ),
              },
            ]}
          />
        </GridItem>
        <GridItem xs={12} sm={12} md={6}>
          <Card>
            <CardHeader color="warning">
              <h4 className={classes.cardTitleWhite}>Employees Stats</h4>
              <p className={classes.cardCategoryWhite}>
                New employees on 15th September, 2016
              </p>
            </CardHeader>
            <CardBody>
              <Table
                tableHeaderColor="warning"
                tableHead={["ID", "Name", "Salary", "Country"]}
                tableData={[
                  ["1", "Dakota Rice", "$36,738", "Niger"],
                  ["2", "Minerva Hooper", "$23,789", "Curaçao"],
                  ["3", "Sage Rodriguez", "$56,142", "Netherlands"],
                  ["4", "Philip Chaney", "$38,735", "Korea, South"],
                ]}
              />
            </CardBody>
          </Card>
        </GridItem>
      </GridContainer>
    </div>
  );
}

Javascript function event.target.getAttribute(“src”) returns null

I have this list of images

    <div class="item board col-sm-6 col-md-4 col-lg-4 mb-4" onclick="show()">
    <a href="#" class="item-wrap fancybox">
      <div class="work-info">
        <h3>TITLE</h3>
        <span>TEXT</span>
      </div>
      <img class="img-fluid" src="img/image-9.jpg" >
    </a>
  </div>


    <div class="item maison col-sm-6 col-md-4 col-lg-4 mb-4" onclick="show()">
    <a href="#" class="item-wrap fancybox">
      <div class="work-info">
        <h3>TITLE</h3>
        <span>TEXT</span>
      </div>
      <img class="img-fluid" src="img/image-1.jpg" >
    </a>
  </div>

I would like the the the full path of the image when I click on the div

  function show(){
    var img = event.target.getAttribute("src");
    console.log(img);
  }

However when I look in the console it returns null why is that?

Office Script – array.splice affects 2 arrays for unknown reasons

I am currently creating a script to automate populating a calendar. Right now, I’m stuck on this problem where I don’t know why but this splice seems to be affecting my 2 arrays…

Here is the section of code where I have my splice :

// Remove element from temporary list
console.log('--before', ihListCountry, populatingIhListCountry);  
populatingIhListCountry.splice(j, 1);  
console.log('--after', ihListCountry, populatingIhListCountry);

And here is the result in the console :

--before  
(11) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …]  
(11) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …]  
--after  
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]  
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]  
--before  
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]  
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
--after  
(9) [Object, Object, Object, Object, Object, Object, Object, Object, Object]  
(9) [Object, Object, Object, Object, Object, Object, Object, Object, Object]

As you can see from the lenght, both are affected by the splice, anyone knows what the problem is here?

I want to add a custom script JS to elementor and wp forms

This is the script that I want to work on elementor elements, the wp forms is on another page perhaps and there is another page where I would like this script to be run kindly guide me through the steps of making it work with elementor. Thankyou

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Specify the path to the PDF worker script
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

        // Event handler for the Convert button click
        document.getElementById('convertButton').addEventListener('click', () => {
            const fileInput = document.getElementById('pdfFileInput');
            const file = fileInput.files[0];

            if (file) {
                const reader = new FileReader();
                reader.onload = function (event) {
                    const arrayBuffer = event.target.result;

                    // Load the PDF using pdf.js
                    pdfjsLib.getDocument(arrayBuffer).promise.then(pdf => {
                        const numPages = pdf.numPages;
                        const promises = [];

                        // Iterate over each page of the PDF
                        for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                            // Get the page data
                            const pagePromise = pdf.getPage(pageNumber).then(page => {
                                // Extract the text content of the page
                                return page.getTextContent().then(textContent => {
                                    const textItems = textContent.items;
                                    const pageText = textItems.map(item => item.str).join(' ');

                                    return { pageNumber, pageText };
                                });
                            });

                            promises.push(pagePromise);
                        }

                        // Wait for all page promises to resolve
                        Promise.all(promises).then(pagesData => {
                            // Convert the array of page data to JSON
                            const jsonData = JSON.stringify(pagesData);
                            console.log(jsonData);

                            // Define the prompts for each section
                            const prompts = [
                                "Create an impressive but appropriate career snapshot from the experience described. Don't mention names or addresses. Make a 3-5 line detailed snapshot",
                                "List three expert skills from the text.",
                                "Make a list of accomplishments from the text.",
                                "Make a list of utilized technologies based on the text.",
                                "Pick out, list, and eloquently rephrase the top 3 achievements from the text.",
                                "List any awards or trainings mentioned in the text.",
                                "List the school names, degree titles, and dates for each from the education section in the text.",
                                "List the top three employment companies roles and dates from the text with a 2-line description for each."
                            ];

                            // Create an array to hold the generated responses
                            const generatedResponses = [];

                            // Define a function to handle the OpenAI API completion for a specific prompt
                            const handleCompletion = (promptIndex, response) => {
                                // Extract the generated text from the OpenAI API response
                                console.log(response);
                                const generatedText = response.choices[0].text.trim();

                                // Add the generated response to the array
                                generatedResponses[promptIndex] = generatedText;

                                // Check if all prompts have received responses
                                if (generatedResponses.length === prompts.length) {
                                    // Insert the generated responses into their respective fields
                                    document.getElementById('careerTitle').innerText = generatedResponses[0];
                                    document.getElementById('expertSkills').innerText = generatedResponses[1];
                                    document.getElementById('accomplishments').innerText = generatedResponses[2];
                                    document.getElementById('utilizedTechnologies').innerText = generatedResponses[3];
                                    document.getElementById('topAchievements').innerText = generatedResponses[4];
                                    document.getElementById('awardsTrainings').innerText = generatedResponses[5];
                                    document.getElementById('education').innerText = generatedResponses[6];

                                    const employmentRolesList = document.getElementById('employmentRoles');
                                    employmentRolesList.innerHTML = '';
                                    const employmentRoles = generatedResponses[7];
                                    if (employmentRoles) {
                                        const roles = employmentRoles.trim().split(/d+./).slice(1);
                                        for (let i = 0; i < roles.length; i++) {
                                            const role = roles[i].trim();
                                            const listItem = document.createElement('li');
                                            listItem.textContent = role;
                                            employmentRolesList.appendChild(listItem);
                                        }
                                    }
                                }
                            };

                            // Loop through each prompt and send a separate request to the OpenAI API
                            for (let i = 0; i < prompts.length; i++) {
                                $.ajax({
                                    url: 'https://api.openai.com/v1/completions',
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'Authorization': 'Bearer ' // Replace with your OpenAI API key
                                    },
                                    data: JSON.stringify({
                                        model: 'text-davinci-003',
                                        prompt: prompts[i] + "n" + jsonData,
                                        max_tokens: 200,
                                        temperature: 0.5,
                                    }),
                                    success: function (response) {
                                        handleCompletion(i, response);
                                    },
                                    error: function (error) {
                                        console.error('Error:', error);
                                    }
                                });
                            }
                        });
                    });
                };
                reader.readAsArrayBuffer(file);
            }
        });
    </script>

I am expecting a user to register using a form and insert their CV then their CV is summarised using api and sent to open ai api to get response for CV optimization and then to work on the elementor elements respectively.

SVG2PNG font not recognized on Linux

Im trying to build a discord bot that responds with an image. But the TextFont not correct, charakters displayed as “[]”

Font not correct, charakters displayed as "[]"
My Code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const { svg2png } = require('svg-png-converter');
const { MessageAttachment } = require('discord.js');
let declareCount = 0;

module.exports = {
    data: new SlashCommandBuilder()
        .setName('test')
        .setDescription('dei!'),


    async execute(interaction) {
        let svg = 
        `
        <svg height="30" width="200">
        <text x="0" y="15" fill="red">I love SVG!</text>
      </svg>
        `

          declareCount+=1;
          const outputBuffer = await svg2png({
              input: svg,
              encoding: 'buffer',
              format: 'png',
              quality: 1
          })
          await interaction.reply({
            ephemeral: false,
            content: `Test #${declareCount}`,
            files: [new MessageAttachment(outputBuffer, '${name}.png')]
        });
      },
    };

Everything works on my local windows system. Is there any way, to do it with linux?
Thanks in regards