unable to get the results on spreadsheet despite running a code and it saying execution completed

Hi guys I am a total noob please if sombody can help

I have a live portfolio in my spread sheet so IN Cell E32 the % change in portfolio gets updated on real time basis, now I want to get the % change every day so I copied a code

I went to my google sheet, clicked on extension and then on add script

Now there I pasted my code and clicked on run, I did this some 10 times but nothing is happening on my google sheet, can somebody please help,

I also dont know how many times I might have run the code so I need help in deleting all these codes executing as well

the code is as follows
enter image description here

also if sombody can explain me, once this code runs how do I run another code because every time I open this add script I can se the old code only, dont know how to add a new one

I have explained everything above

Populating element with thousands of data, freezes the webpage. How do I fix this?

homepage/index.php

var form = document.createElement("form");
form.id = "survey-form";
var elements = [
       {
           type: "select",
           label: "Send to employee",
           id: "empno",
           options: [] // Options will be populated dynamically
       },
];
elements.forEach(function (element) {
       var wrapper;
       var label = document.createElement("label");
       label.className = "form-label";
       label.textContent = element.label;
       if (element.type === "select") {
           input = document.createElement("select");
           input.id = element.id;
           input.className = "user-input";

           form.appendChild(label);
           form.appendChild(input);
           fetchOptionsUsingWorker(input, element.options);

           $(document).ready(function() {
               $('#' + element.id).select2();
           });
       }
});

function fetchOptionsUsingWorker(selectElement) {
    var worker = new Worker('optionsWorker.js');

    worker.addEventListener('message', function(e) {
        if (e.data.type === 'optionsData') {
            var optionsData = e.data.data;
            populateSelectWithOptions(selectElement, optionsData);
        } else if (e.data.type === 'error') {
            console.error('Error fetching options data:', e.data.message);
        }
    });

    worker.postMessage('fetchOptions');
}

function populateSelectWithOptions(selectElement, optionsData) {
    selectElement.innerHTML = '';
    optionsData.forEach(function (option) {
        var optionElement = document.createElement("option");
        optionElement.value = option;
        optionElement.text = option;
        selectElement.appendChild(optionElement);
     });
}

homepage/optionsWorker.js

function fetchOptionsFromServer() {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "../backend.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onload = function () {
            if (xhr.status === 200) {
                var data;
                if (xhr.responseText === "No data found") {
                    data = ["No data found"];
                } else {
                    data = JSON.parse(xhr.responseText);
                }
                resolve(data);
            } else {
                reject(xhr.statusText);
            }
        };
        var data = "input=get_options";
        xhr.send(data);
    });
}

self.addEventListener('message', async function(e) {
    if (e.data === 'fetchOptions') {
        try {
            const optionsData = await fetchOptionsFromServer();
            self.postMessage({ type: 'optionsData', data: optionsData });
        } catch (error) {
            self.postMessage({ type: 'error', message: error });
        }
    }
});

As there are thousands of data being fetched from the server, I used webworkers to run the code which fetches the data in the background thread, otherwise the webpage keeps on freezing. But even after using webworkers, it was of no good, as the webpage still freezes. Where am I going wrong? Please guide me.

HTML borders for dynamic data

I have a below data, I’m expecting to generate a border dynamically for each data set,


<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Subject</th>
      <th>Average Marks</th>
      <th>Name</th>
      <th>Marks Scored</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 1</td>
      <td>90</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 2</td>
      <td>70</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Maths</td>
      <td>80</td>
      <td>Student 3</td>
      <td>80</td>
    </tr>
    <tr>
      <th>3</th>
      <td>English</td>
      <td>80</td>
      <td>Student 1</td>
      <td>90</td>
    </tr>
    <tr>
      <th>4</th>
      <td>English</td>
      <td>80</td>
      <td>Student 2</td>
      <td>70</td>
    </tr>
  </tbody>
</table>

Actual table,

enter image description here

Expectation,

enter image description here

Any suggestion would be appreticiated

Coding a WooCommerce Multi-Step Checkout

I’ve been trying to get some code to work but doesn’t seem to be firing. Think I might be missing something between versions.

I’m using the base checkout from WooCommerce plugin. Text appears at the bottom of checkout instead of buttons, but that might be a theme issue and haven’t added a CSS. Pretty sure I’ve enqueued the script right from everything I can find.

Here’s what I have:

In Function.php

add_action( 'woocommerce_after_checkout_form', 'step_controls');
function step_controls() {
    echo '
        <div class="step_controls_container">
            <a class="btn-primary step_back_to_cart" href="'.site_url("/cart", "https").'">Back to Cart</a>
            <a class="btn-primary step_next">Next</a>
            <a class="btn-primary step_prev">Previous</a>
        </div>
    ';
}
//

function cart_steps() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('cartsteps', get_stylesheet_directory_uri() . '/js/cart-steps.js');

} 
add_action( 'wp_enqueue_scripts', 'cart_steps' ); 

In custom JS file

var steps = [
    {
        name: 'Billing & Shipping Details',
        selector: '#customer_details'
    },
    {
        name: 'Order Review & Payment',
        selector: '#order_review'
    }
]
var activeStep;
// Adjust the array length to match zero-base
var stepsLengthAdjusted = steps.length - 1;

// Utility functions
function initSteps() {
    // Set first checkout step
    sessionStorage.setItem('checkout_step', '0');
}
function getCurrentStep() {
    return sessionStorage.getItem('checkout_step');
}
function showCurrentStep() {
    activeStep = getCurrentStep();
    // Loop through the steps and see which is currently active
    for (let i = 0; i < steps.length; i++){
        let stepSelector = steps[i].selector;
        if ( i != activeStep ) {
            // Hide if not the current step
            $(stepSelector).hide();
        } else {
            // Show the correct step div
            $(stepSelector).fadeIn();
            // Show or hide navigation  buttons as appropriate
            $('.step_next, .step_prev').show();
            if ( getCurrentStep() == stepsLengthAdjusted ) {
                // This is the last step, so remove next button
                $('.step_next').hide();
            }
            if ( getCurrentStep() == 0 ) {
                // This is the first step, so remove previous button
                $('.step_prev').hide();
            }
        }
    }
    // Always go to the top of the steps
    $("body").get(0).scrollIntoView();
}
function nextStep() {
    if ( getCurrentStep() < stepsLengthAdjusted ) {
        var nextStep = parseInt(getCurrentStep()) + 1;
        sessionStorage.setItem('checkout_step', nextStep);
        showCurrentStep();
    }
}
function previousStep() {
    if ( getCurrentStep() > 0 ) {
        var previousStep = parseInt(getCurrentStep()) - 1;
        sessionStorage.setItem('checkout_step', previousStep);
        showCurrentStep();
    }
}

// Initialise
if ( getCurrentStep() == null ) {
    initSteps();
}
// Always show the correct step
showCurrentStep();
// Navigation
$('.step_next').click(function() {
    nextStep();
});
$('.step_prev').click(function() {
    previousStep();
});
// Hide a elements not in parent containers!
$('h3#order_review_heading').hide();

// Flush the current step when navigating away from checkout to prevent customer confusion
if ( !$('body').hasClass('woocommerce-checkout') ) {
    initSteps();
}

$('body').on('checkout_error', function(){
    for (let i = 0; i < steps.length; i++){
        let stepSelector = steps[i].selector;
        let fields = stepSelector + ' p';
        $( fields ).each(function() {
            if ( $(this).hasClass('woocommerce-invalid') ) {
                sessionStorage.setItem('checkout_step', i);
                showCurrentStep();
                return false;
            }
        });
    }
});

XSLTProcessor not running

Have been knocking my head trying to figure why the following XSLTProcessor call is not working.

The XSL-T

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:space="default">
    <xsl:output method="text" version="1.0" encoding="UTF-8" indent="no"/>
    <xsl:strip-space elements="*"/>
    <xsl:param name="include-header" select="'false'"/>
    <xsl:template match="/">
       <!--xsl:element name="row"-->
       <xsl:text>{</xsl:text>
        <xsl:apply-templates select="*"/>
        <!--/xsl:element-->
       <xsl:text>}</xsl:text>
    </xsl:template>
    <xsl:template match="*[count(descendant::*)=0]">
        <xsl:param name="parent"/>
        <xsl:variable name="quote" select="'&quot;'"/>
        <xsl:variable name="thisName" select="name()"/>
        <xsl:variable name="precedingSibling" select="count(preceding-sibling::*[name()=$thisName])+1"/>
        <xsl:variable name="parentChild" select="concat($parent, '.',$thisName, $precedingSibling)"/>
        <xsl:value-of select="concat($quote,$parentChild, $quote, ': ', $quote, ., $quote, ',')"/>
        <xsl:text>
</xsl:text>
    </xsl:template>
    <xsl:template match="*">
        <xsl:call-template name="recurse-descendents"/>
    </xsl:template>
    <xsl:template match="*[count(descendant::*)>0]">
        <xsl:call-template name="recurse-descendents"/>
    </xsl:template>
    <xsl:template name="recurse-descendents">
        <xsl:variable name="thisName" select="name()"/>
        <xsl:apply-templates select="*[count(descendant::*)=0]">
            <xsl:with-param name="parent" select="concat($thisName, count(preceding-sibling::*[name()=$thisName])+1)"/>
        </xsl:apply-templates>
        <xsl:apply-templates select="*[count(descendant::*)>0]"/>
    </xsl:template>
</xsl:stylesheet>

Sample XML

<?xml version="1.0" encoding="UTF-8"?>
<foods>
    <meats>
        <meat>Beef</meat>
        <meat>Chicken</meat>
        <meat>Lamb</meat>
    </meats>
    <fruits>
        <fruit>Orange</fruit>
        <fruit>Apple</fruit>
        <fruit>Banana</fruit>
        <fruit>Avacado</fruit>
    </fruits>
    <vegetables>
        <vegetable>Carrot</vegetable>
        <vegetable>Cellery</vegetable>
        <vegetable>Potato</vegetable>
    </vegetables>
</foods>

Output from XML Spy (as expected)

{"meats1.meat1": "Beef",
"meats1.meat2": "Chicken",
"meats1.meat3": "Lamb",
"fruits1.fruit1": "Orange",
"fruits1.fruit2": "Apple",
"fruits1.fruit3": "Banana",
"fruits1.fruit4": "Avacado",
"vegetables1.vegetable1": "Carrot",
"vegetables1.vegetable2": "Cellery",
"vegetables1.vegetable3": "Potato",
}

Javascript code using XSLTProcessor (not working)

async function GenerateTestCaseResponse(xml, testCase) {
    const domParser = new DOMParser();
    const xsltProcessor = new XSLTProcessor();

    const xslResponse = await fetch("transformer/generate-response-json.xslt");
    const xslText = await xslResponse.text();
    const xslStylesheet = domParser.parseFromString(xslText, "application/xml");
    xsltProcessor.importStylesheet(xslStylesheet);
    var responseDomParser = new DOMParser();
    var responseDocument = responseDomParser.parseFromString(xml, "text/xml");
    var result =  xsltProcessor.transformToDocument(responseDocument);
    console.log(result.body);
    return result;
}

The call to xsltProcessor.transformToDocument returns empty with no error or exception. At a loss how to resolve, and any thoughts gratefully received.

need to write algorithm for this question in javascript [closed]

given 2 strings p and Q each consisting of N lowercase english letters for each position in the strings we have to choose one letter from either P and Q in order to construct a new String S, such that the number of distinct letters is S is minmal. Our task is to find the number of distinct letters in resulting string for example P=”abc, Q=”bcd”, your function should return 2 all possible strings s that can be constructed are “abc, “abd”, “acc”,”acd”, “bbc”, “bbd”, “bcc”,”bcd the minimum number of dsitinct letters is 2 which be obtained by constructing the follwing strings “acc”, “bbc”,”bbd”, “bcc” given P=”axxz”, Q=”yzwy”, your function should return 2 string S must consist of at least 2 distinct letters in this case we can construct S=”yxxy” where the number of distinct letters is equal to 2 and this is the only optimal solution given P=”bacad
, Q=”abada, your function should return 1 we can choose the letter ‘a’ in each position, so S can be equal to “aaaa”. given P = “amz”, Q=”amz” your function should return 3 the the input string are identical so the only possible S that can be constructed is “amz” and its number of distinct letter is 3 write the efficient algorithm for the follwoing assumption N is an inetger within the range [1…200,000] string P and Q are both of length N strings P and Q are made only of lowercase letters(a-z) string P and Q contain a total of at most 20 distinct letters

Need answer for this javascript question

Javascript if statement is executing on false condition

const value = '2555-555-5555';
const regex = /(1s?)?(d{3}|(d{3}))[-s]?d{3}[-s]?d{4}/; //I found this is an incorrect regex

if (regex.test(value)) {
  console.log(regex.test(value)); //is false
  resultsDiv.querySelector("p").textContent = `Valid US number: ${value}`;
} else {
  resultsDiv.querySelector("p").textContent = `Invalid US number: ${value}`;
}

The if condition here should not be executing.

drag and drop box showing stop sign

I want to be able to drag and drop the draggable box to any other date and it should remove that previous one.
For example if I move drag box from 5th march to 6th march it should remove from 5th march and update to 6th march
my problem is when I drag and drop this box it shows a stop sign and I cannot move it. Is there any way to fix it or any other way so I can move my boxes to another date along with its data (has some data name and subrub when you hover over drag box?
enter image description here

my code for runsheetpreview.js

import React, { useState, useRef } from "react";
import { startOfMonth, endOfMonth, startOfWeek, endOfWeek, format, addDays, addMonths, subMonths, isSameMonth } from "date-fns";
import "../assets/css/RunSheetPDF.css";

const DraggableBox = ({ day, onDrop, name: initialName, suburb: initialSuburb }) => {
  const [editable, setEditable] = useState(false);
  const [name, setName] = useState(initialName);
  const [suburb, setSuburb] = useState(initialSuburb);
  const [showTooltip, setShowTooltip] = useState(false);
  const boxRef = useRef(null);

  const handleDoubleClick = () => {
    setEditable(true);
  };

  const handleChangeName = (e) => {
    setName(e.target.value);
  };

  const handleChangeSuburb = (e) => {
    setSuburb(e.target.value);
  };

  const handleBlur = () => {
    setEditable(false);
  };

  const handleDragStart = () => {
    setShowTooltip(false);
    boxRef.current.classList.add('dragging');
  };

  const handleDragEnd = () => {
    boxRef.current.classList.remove('dragging');
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = (e) => {
    e.preventDefault();
    const draggedDay = parseInt(e.dataTransfer.getData("text/plain"));
    onDrop(draggedDay, day);
  };

  return (
    <div
      className="drag-box"
      ref={boxRef}
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDoubleClick={handleDoubleClick}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
      style={{
        width: "70px",
        height: "80px",
        textAlign: "center",
        backgroundColor: "#F5F5F5",
        color: "#333333",
        marginTop: "5px",
        position: "relative",
        cursor: "move" // Set cursor to move when hovering over the box
      }}
    >
      <p style={{ margin: 0, lineHeight: "80px" }}>{day}</p>
      {showTooltip && (
        <div className="tooltip">
          <p>Name: {name}</p>
          <p>Suburb: {suburb}</p>
        </div>
      )}
    </div>
  );
};

const RunSheetPreview = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [calendarData, setCalendarData] = useState([
    { day: 5, name: "John", suburb: "Suburb 1" },
    { day: 15, name: "Alice", suburb: "Suburb 2" },
    { day: 25, name: "Bob", suburb: "Suburb 3" },
    { day: 27, name: "Eva", suburb: "Suburb 4" }
  ]);

  const handleDrop = (draggedDay, dropDay) => {
    const newData = [...calendarData];
    const draggedItem = newData.find(item => item.day === draggedDay);
    draggedItem.day = dropDay;
    setCalendarData(newData);
  };

  const generateCalendar = () => {
    const monthStart = startOfMonth(selectedDate);
    const monthEnd = endOfMonth(selectedDate);
    const startDate = startOfWeek(monthStart, { weekStartsOn: 0 });
    const endDate = endOfWeek(monthEnd, { weekStartsOn: 0 });

    const rows = [];
    let days = [];
    let day = startDate;

    while (day <= endDate) {
      for (let i = 0; i < 7; i++) {
        const dayOfMonth = format(day, "d");
        const isCurrentMonth = isSameMonth(day, monthStart);
        const draggableData = calendarData.find(item => item.day === parseInt(dayOfMonth));
        const draggableBoxExists = draggableData !== undefined;

        days.push(
          <td key={day} style={{ width: "70px", height: "80px" }}>
            {isCurrentMonth && (
              <div>
                {draggableBoxExists ? (
                  <DraggableBox
                    day={draggableData.day}
                    name={draggableData.name}
                    suburb={draggableData.suburb}
                    onDrop={handleDrop}
                  />
                ) : (
                  <p>{dayOfMonth}</p>
                )}
              </div>
            )}
          </td>
        );
        day = addDays(day, 1);
      }
      rows.push(<tr key={day}>{days}</tr>);
      days = [];
    }

    return rows;
  };

  const handleNextMonth = () => {
    setSelectedDate(addMonths(selectedDate, 1));
  };

  const handlePreviousMonth = () => {
    setSelectedDate(subMonths(selectedDate, 1));
  };

  return (
    <div style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center", marginTop: "20px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", marginBottom: "0px" }}>
        <button onClick={handlePreviousMonth} style={{ backgroundColor: "#F5F5F5", color: "#333333", border: "1px solid #CCCCCC", borderRadius: "5px", padding: "5px 10px", marginRight: "10px" }}>Previous Month</button>
        <h2 style={{ color: "#333333", margin: 0 }}>{format(selectedDate, "MMMM yyyy")}</h2>
        <button onClick={handleNextMonth} style={{ backgroundColor: "#F5F5F5", color: "#333333", border: "1px solid #CCCCCC", borderRadius: "5px", padding: "5px 10px", marginLeft: "10px" }}>Next Month</button>
      </div>
      <div className="calendar-container">
        <table className="calendar-table">
          <thead>
            <tr>
              <th>Sun</th>
              <th>Mon</th>
              <th>Tue</th>
              <th>Wed</th>
              <th>Thu</th>
              <th>Fri</th>
              <th>Sat</th>
            </tr>
          </thead>
          <tbody>
            {generateCalendar()}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default RunSheetPreview;

my code for RunSheetPDF.css

.centered-text {
  text-align: center;
  font-weight: 700;
}

.title {
  text-align: left;
  font-weight: bold;
  font-size: 30px;
  text-transform: uppercase;
  font-style: bold;
}

.table-container {
  width: 1000px;
  background: white;
  font-family: "Times New Roman";
}

.table {
  width: 90%;
  border-collapse: collapse;
}

.top-header th {
  text-align: left;
  border: none;
}

.table-body td {
  text-align: left;
  border: none;
}

.paper {
  padding: 20px;
  display: flex;
  justify-content: space-between;
}

.left-content {
  flex: 1;
  text-align: left;
}

.right-content {
  flex: 1;
  text-align: left;
}

.flex-content {
  display: flex;
  justify-content: space-between;
}

.empty-box {
  text-align: left;
}

.border-box {
  width: 100px;
  height: 20px;
  border: 1px solid #000;
}

.bold-text {
  font-weight: bold;
}

.normal-text {
  font-weight: normal;
}

.text-left {
  text-align: left;
  font-family: "Times New Roman", Times, serif;
}

.no-border {
  border: none;
}
.page-content {
  height: 38rem;
  overflow: auto;
  border: solid 1px black;
  margin: 0 80mm 30mm 45mm;
  width: 35rem;
  page-break-after: always;
}

/* Use media query to apply styles only when printing */
@media print {
  .page-content {
    page-break-before: always; /* This will force a page break before each .page-content element */
  }
}

/* Add this to your CSS file or CSS module */
.print-button-wrapper {
  position: fixed;
  bottom: 130px; /* Adjust this value to change the vertical position */
  right: 150px; /* Adjust this value to change the horizontal position */
}

.calendar-container {
  margin: 20px auto;
  max-width: 800px;
  background-color: #f2f2f2;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.calendar-table {
  width: 100%;
  border-collapse: collapse;
}

.calendar-table th, .calendar-table td {
  padding: 10px;
  text-align: center;
  border: 2px solid #fff; /* White border to separate cells */
}

.calendar-table th {
  background-color: #3f51b5; /* Dark blue background for days */
  color: #fff;
  font-weight: bold;
  font-size: 18px;
}

.calendar-table td {
  background-color: #ffffff; /* White background for date cells */
}

.calendar-table td:first-child {
  background-color: #f5f5f5; /* Light gray background for first column */
}

.drag-box {
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
}

.drag-box p {
  margin: 5px 0;
}

.drag-box input {
  width: 100%;
  padding: 5px;
  margin-bottom: 5px;
}

.drag-box.draggable {
  background-color: #ffd700; /* Gold background for draggable box */
  border-color: #ffd700;
  color: #000;
}

.drag-box.draggable p {
  color: #000;
}


.drag-box {
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 100px; /* Adjust the width as needed */
  height: 60px; /* Adjust the height as needed */
  transition: opacity 0.3s ease; /* Add transition for smooth hide/show effect */
}

.drag-box.hidden {
  opacity: 0; /* Hide the box during drag */
}

.calendar-table {
  border-collapse: collapse;
  width: 100%; /* Make the table fill its container */
  background-color: #f0e8ff; /* Light purple background color */
}

.calendar-table th,
.calendar-table td {
  border: 1px solid #cccccc;
  padding: 8px;
  text-align: center;
  width: 100px; /* Adjust the width of table cells */
}
.drag-box {
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin: 2px;
}

.calendar-table {
  width: 100%;
}

.calendar-table td {
  border: 1px solid #ccc;
  padding: 5px;
  text-align: center;
}

.calendar-table p {
  margin: 0;
}
.drag-box {
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  margin: 2px;
  position: relative; /* Add relative positioning */
}

.tooltip {
  position: absolute;
  top: 100%; /* Position below the draggable box */
  left: 50%; /* Center horizontally */
  transform: translateX(-50%); /* Center horizontally */
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  z-index: 1; /* Ensure tooltip appears above other elements */
  white-space: nowrap; /* Prevent line breaks */
  visibility: hidden; /* Initially hidden */
}

.drag-box:hover .tooltip {
  visibility: visible; /* Show tooltip on hover */
}

How do I remove an item from localStorage and update the state once removed?

// **Card.jsx code**

import { useState, useEffect } from "react";
import "./card.scss";

function Card({ movieList, removeMovie }) {
  const [saved, setSaved] = useState(null);

  const handleButtonClick = (movie) => {
    setSaved(saved === movie ? null : movie);
    if (saved === movie) {
      setSavedMovies((prev) => prev.filter((item) => item !== movie));
      removeMovie(movie);
    } else {
      setSavedMovies((prev) => [...prev, movie]);
    }
  };

  const handleDelete = (movie) => {
    const filtered = movieList.filter((item) => {
      return item !== movie;
    });
    setSavedMovies(filtered);
  };

  const [savedMovies, setSavedMovies] = useState([]);

  useEffect(() => {
    const retrieveSavedMovies = () => {
      const savedMovies = localStorage.getItem("savedMovies");

      return savedMovies ? JSON.parse(savedMovies) : [];
    };

    setSavedMovies(retrieveSavedMovies());
  }, []);

  useEffect(() => {
    localStorage.setItem("savedMovies", JSON.stringify(savedMovies));
  }, [savedMovies]);

  return (
    <div className="cardContainer">
      {movieList.map((movie) => (
        <div className="card" key={movie.id}>
          <div className="save">
            <button
              onClick={() => {
                handleButtonClick(movie);
              }}
              className={`button ${saved === movie ? "saved" : ""}`}
            >
              {saved === movie ? (
                <img src="/star.png" alt="" />
              ) : (
                <img src="/trash.png" alt="" />
              )}
            </button>
          </div>
          <img
            src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
            alt=""
          />
          <p>{movie.title}</p>
        </div>
      ))}
    </div>
  );
}

export default Card;

// **SavedMovie.jsx code**

import "./savedMovie.scss";
import { useState, useEffect } from "react";
import Card from "../card/Card";

function SavedMovie() {
  const [savedMovies, setSavedMovies] = useState([]);

  useEffect(() => {
    const retrieveSavedMovies = () => {
      const savedMovies = localStorage.getItem("savedMovies");
      return savedMovies ? JSON.parse(savedMovies) : [];
    };

    setSavedMovies(retrieveSavedMovies());
  }, []);

  return (
    <div className="savedMovie">
      <div className="body">
        <div className="content">
          {savedMovies.length > 0 ? (
            <Card movieList={savedMovies} />
          ) : (
            <p>No saved movies</p>
          )}
        </div>
      </div>
    </div>
  );
}

export default SavedMovie;


Hello, I’m trying to create a movie list app with react. I have 2 tabs, the first one being “Movies” which is also the homepage, where I display a list of movies using TMDB API, and the second tab is “To Watch” where I display all the movies the user chose to save by clicking on the button. How do I remove the movie from the “To Watch” tabs when the user clicks on the same button?

I tried creating a removeMovie function and passing it to the Card component as props and then call it in the handleButtonClick function which is being called by the button onClick. However nothing actually happened.

How to I can view background apps in a React Native application?

I’m working on a Gaming Social Media app with react native and I need to access information about background apps running on the device. Specifically, I want to retrieve a list of background apps along with their information such as the time when it started and package name. to set status automatically for ex: “playing {game name}” if user allow me.

I’ve searched through the React Native documentation and various libraries, but I couldn’t find a clear solution for this. Is there a native module or library available that allows me to achieve this functionality? If not, what would be the recommended approach to implement this feature in a React Native application?

Any guidance or suggestions would be greatly appreciated. Thank you!

Javascript in TypeWriter Effect

I try to create a typeWriter effect using Javascript. It done perfectly, but it cannot type ‘<‘ character. I don’t know how to fix it

My code is:

let other = document.getElementById('other');
let txt = "Hello World <br> this typing effect.";
let i = 0;
function typeWriter() {
    if (i < txt.length) {
      other.innerHTML += txt.charAt(i); i++;
      setTimeout(typeWriter, 10);
      window.scrollTo(0, document.body.scrollHeight);
    }
}

typeWriter();
<h1 id='other'></h1>

I hope the result like:

Hello World
this typing effect.

Actual result I get:

Hello World <br> this typing effect.

Please give me some clue. Thanks in advance

How do I create a custom command to generate files with Node?

For my job, we create a lot of small web applications with NodeJS for the backend and Angular for the frontend

Said apps usually involve a lot of CRUDs

With Angular, I can run:

ng generate component 'component-name'

Which generates the ts, html, scss, and spec files

How would I go about creating a custom script to do something similar in NodeJS?

Currently, the project uses ExpressJS and Sequelize, and the structure as follows:

├── src
│   ├── controllers
│   |   ├── product.controller.js
│   ├── models
|   |   ├── product.model.js
│   ├── routes
|   |   ├── product.routes.js
├── index.js
├── package.json

Basically I want to create a script that generates all 3 files when given the name, something like

node generate client

Is it possible?

event listener is not removing even though command is complete

I’m making an RPG game inspired by freecodecamp but with my own twist where I have a buy weapons section and you can choose which weapon you would like to buy. it works normally up until i return to the store function and all of a sudden the button function isn’t changed even though i already added removeEventListener

Javascript

let xp = 0
let health = 100
let coin = 1000;
let inv = [
    {weapon : "Spiderweb", damage : 2}
]

const xpNum = document.querySelector("#xpNum");
const healthNum = document.querySelector("#healthNum");
const coinNum = document.querySelector("#goldNum");
const button1 = document.querySelector("#button1");
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const button4 = document.querySelector("#button4");
const textbox = document.querySelector("#textbox");
const textbox2 = document.querySelector("#textbox2");

xpNum.innerHTML = xp
healthNum.innerHTML = health
coinNum.innerHTML = coin

const weapons = [
    {weapon : "Shield", damage : 5, price : 50},
    {weapon : "Taser", damage : 10, price : 75},
    {weapon : "Gun", damage : 15, price : 100},
    {weapon : "Trident", damage : 20, price : 200},
];

const villains = [
    {villain : "Sandman" , health : 40, place : "under"},
    {villain : "Robber" , health : 20 , place : "city"},
    {villain : "Kidnapper" , health : 30, place : "city"},
    {villain : "Green Goblin" , health : 50, place : "city"},
    {villain : "Mysterio" , health : 50, place : "under"},
    {villain : "Lizard" , health : 50, place : "under"},
    {villain : "Kingpin" , health : 100, place : "city"},
];

const places = [
    {place : "store" , 
    text : "Spiderman is inside the store. What should he do?",
    btnText : ["Buy Weapons" , "Sell Weapons" , "Increase Health", "Leave Store"],
    btnFunc : [buy,sell,increase,start],
    text2 : "Im boutta cum"
}
];

function update(location) {
    button1.innerHTML = location.btnText[0]
    button2.innerHTML = location.btnText[1]
    button3.innerHTML = location.btnText[2]
    button4.innerHTML = location.btnText[3]

    button1.onclick = location.btnFunc[0]
    button2.onclick = location.btnFunc[1]
    button3.onclick = location.btnFunc[2]
    button4.onclick = location.btnFunc[3]

    textbox.innerHTML = location.text

    if(Object.hasOwn(location,"text2")){
        textbox2.innerHTML = location.text2
    } else {
        textbox2.style.display = "none"
    }
}

function store() {
    update(places[0])
}

function buy() {
    let weaponsText = ""
    inv.forEach((item,index) => {
        weaponsText += `${index + 1}. ${item.weapon}<br>`
    })
    textbox2.innerHTML = "1. Shield - 5 Damage - 50 Coins<br>2. Taser - 10 Damage - 75 Coins<br>3. Gun - 15 Damage - 100 Coins<br>4. Trident - 20 Damage - 200 Coins<br>"
    textbox.innerHTML = `Spiderman currently has <br>${weaponsText} Which weapon should Spiderman buy?`
    button1.innerHTML = "Shield"
    button2.innerHTML = "Taser"
    button3.innerHTML = "Gun"
    button4.innerHTML = "Trident"

    button1.removeEventListener("click",buyWeapon)

    const buyWeapon = (cmd) => {
        let weaponName = cmd.target.innerHTML
        let weapon = weapons.find(item => item.weapon == weaponName)
        if(weapon){
            inv.push(weapon)
            alert(`${weaponName} bought!`)
            coin -= weapon.price
            coinNum.innerHTML = coin
            cmd.target.removeEventListener("click",buyWeapon)
            store()
        }
    }

    button1.addEventListener("click",buyWeapon)
}

function sell() {

}

function increase() {

}

function start() {

}

button1.addEventListener("click",()=>{
    store()
})

HTML

<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>RPG Game</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div id="container">
            <div id="stats">
                <span id="xpText" class="stat">XP : <strong id="xpNum">0</strong></span> |
                <span id="healthText" class="stat">Health : <strong id="healthNum">0</strong></span> |
                <span id="coinsText" class="stat">Coins : <strong id="goldNum">0</strong></span>
            </div>
            <div id="buttons">
                <button id="button1" class="button">Go to store</button>
                <button id="button2" class="button">Go to city</button>
                <button id="button3" class="button">Go to underground</button>
                <button id="button4" class="button">Exit</button>
            </div>
            <div id="textbox2">ddddddd</div>
            <div id="textbox">
                Spiderman is near a mom-and-pop shop in Queens. What should he do?
            </div>
        </div>
        
        <script src="script.js" async defer></script>
    </body>
</html>```

Javascript code random insult nested in html not working [duplicate]

It just doesn’t work. Nothing in the console. I hope someone can debug it.
Thanks!

I’ve tried changing the script around, but still nothing. This is actually based off another one of my posts, but when I added more insults, and changed the random picker, it stopped working as needed. As I’ve said before, this will be a basis for more of my projects to come.

<main>
    <script>
        const insults = [
'${name} is a lucky ducky! 99, dam!.',
'${name} was so close to success. But I guess you`re just a failure in life.',
'${name}, is kinda stupid.',
'Hey, ${name}, turn 96 upside down.',
'${name}, 95 is literally the most boring number you could have gotten. Go try again..',
'${name}, can I have the name of your hair salon? I need to know where not to go.',
'${name}, you are the human equivalent of a participation trophy.',
'${name}, you have a face for radio.',
'${name}, whatever kind of look you were aiming for, you missed.',
'${name}, I smell something burning. Are you trying to think again?',
'${name}, you’re like a lighthouse in a desert: bright but not very useful.',
'${name}, you’re as useless as the “ueue” in “queue!',
'${name}, whatever is eating you must be suffering terribly.',
'${name}, if you ever had a thought, it would die of loneliness.',
'${name}, this is why the gene pool needs a lifeguard.',
'${name}, you have the charisma of a wet sock.',
'${name}, I don’t understand, but I also don’t care, so it works out nicely.',
'${name}, I’ve seen salad that dresses better than you.',
'${name}, You have the communication skills of an alarm clock.',
'${name}, honestly, I`m just impressed you could read this.',
'${name}, no I`m not insulting you, I`m describing you.',
'${name},  your birth certificate is an apology letter from the condom factory.',
'${name}, the only way you`ll ever get laid is if you crawl up a chicken`s ass and wait.',
'${name}, my psychiatrist told me I was crazy and I said I want a second opinion. He said okay, you`re ugly too.',
'${name}, you must have been born on a highway because that`s where most accidents happen.',
'${name}, brains aren`t everything. In your case they`re nothing.',
'${name}, some babies were dropped on their heads but you were clearly thrown at a wall.',
'${name}, you can walk, but can you talk?',
'${name}, I`d slap you, but that would be animal abuse.',
'${name}, stop trying to be a smart ass, you`re just an ass.',
'${name}, Damn, you just got the best number! 6--------9!',
'${name}, One off from 69, get better at life.',
'${name}, why was six scared of seven? Because seven ate nine!',
'${name}, why don`t you slip into something more comfortable... like a coma.',
'${name}, you get ten times more girls/boys than me? ten times zero is zero...',
'${name}, You`re so fat, you could sell shade.',
'${name}, have you been shopping lately? They`re selling lives, you should go get one.',
'${name}, I don`t think you understand the concept of `no eating`.',
'${name}, that`s one small step for me, and a massive one for you.',
'${name}, I`d like to see things from your point of view but I can`t seem to get my head that far up my ass.',
'${name}, every time I`m next to you, I get a fierce desire to be alone.',
'${name}, why do you always wear black? Do you like looking like a clown?',
'${name}, you`re so dumb that you got hit by a parked car.',
'${name}, how did you get here? Did someone leave your cage open?',
'${name}, I didn’t ask for your opinion.',
'${name}, pardon me, but you`ve obviously mistaken me for someone who gives a damn.',
'${name}, don`t you have a terribly empty feeling - in your skull',
'${name}, as an outsider,what do you think of the human race?',
'${name}, I have neither the time nor the crayons to explain this to you.',
'${name}, I would agree with you but then we would both be wrong.',
'${name}, you`re so dense, light bends around you.',
'${name}, you`re as useful as a waterproof teabag.',
'${name}, you`re so clumsy, you could trip over a wireless network.',
'${name}, you`re so slow, you make sloths look like Olympic sprinters.',
'${name}, you`re not completely useless; you can always serve as a bad example.',
'${name}, you`re so gullible, I could sell you air and you`d buy it.',
'${name}, your family tree must be a cactus, because everyone on it is a prick.',
'${name}, you`re not just a clown; you`re the entire circus.',
'${name}, your agility is comparable to a turtle on a trampoline.',
'${name}, you have the problem-solving skills of a confused penguin in a desert',
'${name}, you look like you were drawn with my left hand',
'${name},  I do not consider you a vulture. I consider you something a vulture would eat',
'${name}, what do you think of that, Mr. Pajama-Wearing, Basket-Face, Slipper-Wielding, Clipe-Dreep-Bauchle, Gether-Uping-Blate-Maw, Bleathering, Gomeril, Jessie, Oaf-Looking, Stauner, Nyaff, Plookie, Shan, Milk-Drinking, Soy-Faced Shilpit, Mim-Moothed, Sniveling, Worm-Eyed, Hotten-Blaugh, Vile-Stoochie, Callie-Breek-Tattie?',
'${name}, Your mother was a broken down tub of junk with more gentlemen callers than the operator.',
'${name}, White people are just untitled word documents.',
'${name}, you`re so dumb, when your dad said to put your grades up, you put your test up on the roof.',
'${name}, Mirrors can`t talk. Lucky for you, they can`t laugh either.',
'${name}, in a parallel universe, you might be smart.',
'${name},  Only 1 in 100 people get this on their first try. You aren`t lucky. you`re just the hundreth person.',
'${name}, I`ll never forget the first time we met. But I`ll keep trying.',
'${name}, Here are the first hundred digits of pi! you`re welcome: 3.1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825 3421170679',
'${name}, Honestly, does anyone even appreciate my work?',
'${name},The number 29 is fine. But are you?',
'${name}, Did the mental hospital test too many drugs on you today?',
'${name}, thought of you today. It reminded me to take out the trash.',
'${name}, somewhere out there is a tree tirelessly producing oxygen for you. You owe it an apology.',
'${name}, you just might be why the middle finger was invented in the first place.',
'${name}, if I had a face like yours, I would sue my parents.',
'${name}, if I wanted to kill myself, I would climb to your ego and jump to your IQ.',
'${name}, Phew, I`m getting tired of typing all those insults. Why don`t you help me out a little, and tell me your personality so that I can make more.',
'${name}, don’t be ashamed of who you are. That’s your parent`s job.',
'${name}, you are proof that evolution can go in reverse.',
'${name}, Isn’t it dangerous to use your whole vocabulary in one sentence?',
'${name}, if I had a dollar for every time you said something smart, I’d be broke.',
'${name}, people clap when they see you. They clap their hands over their eyes',
'${name}, I bet your parents change the subject when their friends ask about you.',
'${name}, find the fact that you’ve lived this long both surprising and disappointing.',
'${name}, carry a plant around with you to replace the oxygen you waste.',
'${name}, don’t know what your problem is, but I’m guessing it’s hard to pronounce.',
'${name}, you see that door? I want you on the other side of it.',
'${name}, final 10, I can see the light. Oh wait, you`re on the other side. Back we go!',
'${name}, You look like a person in their 80`s, but you act like someone who`s 9.',
'${name}, If I had a dollar for everytime you said something smart I would be broke.',
'${name}, may both sides of your pillow be uncomfortably warm.',
'${name}, This is the most useless number you could have gotten.',
'${name}, you had a five percent chance to get this number. Good job!',
];

function Submit(e){
  e.preventDefault();
  let data = new FormData(e.target);
  let name = data.get("name");
  let random = Math.round(Math.random() * 96 - 1); //(4) change according to array length - 1
  const insult = insults[random]?.replace('${name}',name);
  setResult(insult);
}

const res = document.getElementById('result');

function setResult(val){
  res.textContent = val;
}
    </script>
    <form onsubmit='Submit(event)'>
      <label for='name'>Name</label>
      <input id='name' name='name' type='text'>
      <button type='submit'>Check</button>
    </form>
    <div>
      <h2>Insult</h2>
      <h3 id='insult'></h3>
    </div>
  </main>

I hope someone can help.