The “^” character does not interpreted as a start of line in regular expression provided to the route handler

I have one issue with express I want to use "^" as we use it in Javascript regex but unfortunately it does not work…
so here i added “^” to give pattern to the storeName path parameter::

router.get(
  "/stores/:storeName(^[a-zA-Z0-9_-][a-zA-Z0-9_-]{0,})",
  async(req, res) => {
    console.log("here");
  }
);

This route is not mach this route

"http://localhost:3000/stores/saidm"

nor this

"http://localhost:3000/stores/^saidm"

I expected the route to be matched for at least one of this paths

removing ghost js-asset in odoo 16

After having removed a js asset file (kanban_controller_zsb.js) from one of my custom module (event_xsb1) in odoo 16 (and moved in another one), it is still remaining and causes trouble to load new js assets of other custom modules to customize a kanban-view.

enter image description here

Missing dependencies:     
Array [ "web.Sidebar" ]
web.assets_common.min.js:formatted:299:16
Non loaded modules:       
Array [ "event_xsb1.kanban_controller_zsb" ]
​
0: "event_xsb1.kanban_controller_zsb"
​
length: 1
​
<prototype>: Array []
web.assets_common.min.js:formatted:321:14
Debug:                    
Object { "event_xsb1.kanban_controller_zsb": {…} }
​
"event_xsb1.kanban_controller_zsb": Object { dependencies: (3) […], dependents: [], name: "event_xsb1.kanban_controller_zsb", … }
​​
dependencies: Array(3) [ "web.core", "web.KanbanController", "web.Sidebar" ]
​​​
0: "web.core"
​​​
1: "web.KanbanController"
​​​
2: "web.Sidebar"
​​​
length: 3
​​​
<prototype>: Array []
​​
dependents: Array []
​​
missing: Array [ "web.Sidebar" ]
​​
name: "event_xsb1.kanban_controller_zsb"

I have already tried to find this asset manually (in App-Settings > Assets) but i could not find it. I have tried to find the assets.xml of the previous odoo version (v13) in the view but i could not find it neither. So that i am wondering where this js script is located. Any idea how to remove it properly ?

Issue with grabbing data from object

I’m having some trouble getting the right values to show up in this following code. The console log is correct, but when the actual information is being plugged into the page, it’s off by 1.

What I’m hoping to get displayed is:

Name    James   person ID   1
first location  $35
fee amount calculated
fee3    a million in spacecash
Name    Jordan  person ID   2
second location $40
fee amount calculated

Here’s the code:

$(document).ready(function() {
  for (person of personInformation) {
    const personTable = document.createElement("table");
    personTable.innerHTML = "<thead><th id='personName'>Name</th><th id='personId'>person ID</th></thead>";
    personTable.setAttribute("id", "table");

    const newRow = document.createElement("tr");
    newRow.setAttribute("class", "personRow");
    const first_name = document.createElement("th");
    const person_id = document.createElement("th");

    console.log('person', person)

    person_id.textContent = person.person_id;
    first_name.textContent = person.first_name;
    console.log(first_name);
    $("th#personName").after(first_name);
    $("th#personId").after(person_id);
    personTable.appendChild(newRow);
    for (fees of person.fees) {
      const feeRow = document.createElement("tr");
      const fee = document.createElement("td");
      const amount = document.createElement("td");
      fee.textContent = fees.name;
      amount.textContent = fees.amount;
      console.log("fee", fee);
      feeRow.appendChild(fee);
      feeRow.appendChild(amount);
      personTable.appendChild(feeRow);
    }
    console.log(person_id);
    console.log(first_name);
    const persons = document.getElementById('test');
    persons.appendChild(personTable);
  }
  console.log(personInformation);
  $('#personSearch').on('input', function() {
    let value = $(this).val().toLowerCase();
    let searchVal1 = $('.personRow').find('td').text();
    let searchVal2 = $('.personRow').text();
    $('form').filter(function() {

      console.log('searchVal1', searchVal1);
      console.log('searchVal2', searchVal2);
      $(this).toggle($(this).text()
        .toLowerCase().indexOf(value) > 0);
    });
  });
});
<body>
  <div class="container">
    <div class="col-md-12">
      <div class="panel panel-default">
        <div id="test">
        </div>
      </div>
    </div>
  </div>

</body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

<script>
  const personInformation = [{
      "person_id": 1,
      "first_name": "James",
      "fees": [{
          "name": "first location",
          "amount": "$35"
        },
        {
          "name": "fee",
          "amount": "amount calculated"
        },
        {
          "name": "fee3",
          "amount": "a million in spacecash"
        }
      ]
    },
    {
      "person_id": 2,
      "first_name": "Jordan",
      "fees": [{
          "name": "second location",
          "amount": "$40"
        },
        {
          "name": "fee",
          "amount": "amount calculated"
        }
      ]
    }
  ];
</script>

Thanks for any suggestions!

Parsing payload data from razorpay callback url [duplicate]

I am trying to add razorpay to my site, and after successful payment it is redirecting to callback URL with some payload data,
Here is my callback URL where it is redirecting after payment.

https://www.someurl.com/payment-callback.html

and this is how i am getting payload
Payload data

Here is code for my payment-callback.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Callback</title>
    <style>
        body { font-family: Arial, sans-serif; }
        h1 { color: #4CAF50; }
        .status { margin: 20px 0; font-size: 18px; }
        .logs { background: #f9f9f9; padding: 10px; border: 1px solid #ddd; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
<h1>Payment Status</h1>
<div class="status" id="status"></div>
<div class="logs" id="logs"></div>

<script>
    // Function to extract query parameters from the URL
    function getQueryParams() {
        const params = new URLSearchParams(window.location.search);
        const paymentId = params.get('razorpay_payment_id');
        const orderId = params.get('razorpay_order_id');
        const signature = params.get('razorpay_signature');

        return { paymentId, orderId, signature };
    }

    const paymentInfo = getQueryParams();

    // Print the received URL and parameters for debugging
    const currentUrl = window.location.href;
    const logsDiv = document.getElementById('logs');
    logsDiv.innerHTML = `
        <p><strong>Current URL:</strong> ${currentUrl}</p>
        <p><strong>Received Payment ID:</strong> ${paymentInfo.paymentId || 'N/A'}</p>
        <p><strong>Received Order ID:</strong> ${paymentInfo.orderId || 'N/A'}</p>
        <p><strong>Received Signature:</strong> ${paymentInfo.signature || 'N/A'}</p>
    `;

    // Display status based on the query parameters received
    const statusDiv = document.getElementById('status');

    if (paymentInfo.paymentId && paymentInfo.orderId && paymentInfo.signature) {
        statusDiv.innerHTML = `
            <p class="success">Payment Successful!</p>
            <p><strong>Payment ID:</strong> ${paymentInfo.paymentId}</p>
            <p><strong>Order ID:</strong> ${paymentInfo.orderId}</p>
            <p><strong>Signature:</strong> ${paymentInfo.signature}</p>
        `;
        // Optionally: Send these parameters to your server for further verification.
    } else {
        let errorMessage = '<p class="error">Payment Failed or Invalid Response!</p>';

        // Detailed error reporting
        if (!paymentInfo.paymentId) {
            errorMessage += '<p class="error">Missing Payment ID!</p>';
        }
        if (!paymentInfo.orderId) {
            errorMessage += '<p class="error">Missing Order ID!</p>';
        }
        if (!paymentInfo.signature) {
            errorMessage += '<p class="error">Missing Signature!</p>';
        }

        statusDiv.innerHTML = errorMessage;
    }
</script>
</body>
</html>

i am trying to parse it but unable to get, any help would be appreciated.

I am expecting either i get all data in url or i can extract from payload.

Animated blob keeps drifting off the mouse

I have a spotlight to have on the background of my website. It essentially shows through a dark grey layer to show a gradient on the background layer. I really want the circle to be morphing as I’m moving the mouse around, but right now it’s deviating off the center of where the mouse is. I was hoping for the blob to stay centered on the mouse like it is in this example. When I run my code, the rotating looks fine at first, but once I continue to move my mouse, the blob moves away from my mouse and rotates even off the screen before returning to my mouse. But in the example, the blob stays on track with the mouse movement and if there is no movement the blob stays stationary despite continuing to rotate. I’m wondering if it’s because the background layer is a rectangle and how I can fix it? Thank you!

Here is my code!

document.addEventListener("DOMContentLoaded", () => {
  const blob = document.getElementById("blob");

  window.onpointermove = event => {
    const {
      clientX,
      clientY
    } = event;

    blob.animate({
      left: `${clientX}px`,
      top: `${clientY}px`
    }, {
      duration: 2500,
      fill: "forwards"
    });
  };
});
body {
  background-color: #222020;
  height: 100vh;
  margin: 0;
  overflow: hidden;
  position: relative;
}

#gradient-color {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(50% 123.47% at 50% 50%, #00ff94 0%, #720059 100%), linear-gradient(121.28deg, #669600 0%, #ff0000 100%), linear-gradient(360deg, #0029ff 0%, #8fff00 100%), radial-gradient(100% 164.72% at 100% 100%, #6100ff 0%, #00ff57 100%), radial-gradient(100% 148.07% at 0% 0%, #fff500 0%, #51d500 100%);
  background-blend-mode: screen, color-dodge, overlay, difference, normal;
}

#blob {
  width: 1px;
  height: 1px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  overflow: visible;
  background-color: white;
  mix-blend-mode: multiply;
}

#blob::before {
  content: "";
  display: block;
  width: 200vw;
  height: 200vh;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #000;
}

#blob::after {
  content: "";
  display: block;
  width: 34vmax;
  aspect-ratio: 1;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  animation: rotate 20s infinite;
  -webkit-animation: rotate 20s infinite;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  -ms-border-radius: 50%;
  -o-border-radius: 50%;
}

@-webkit-keyframes rotate {
  from {
    rotate: 0deg;
  }
  50% {
    scale: 1 1.5;
  }
  to {
    rotate: 360deg;
  }
}

@keyframes rotate {
  from {
    rotate: 0deg;
  }
  50% {
    scale: 1 1.5;
  }
  to {
    rotate: 360deg;
  }
}

#blur {
  height: 100%;
  width: 100%;
  position: fixed;
  backdrop-filter: blur(12vmax);
}
<div id="gradient-color"></div>
<div id="blob"></div>
<div id="blur"></div>

Firebase Update operations is overlapping with other entries in firebase collection

I’m facing a weird error in my Firebase update operations though it doesn’t happen every time but happens sometimes, the update operation sometimes overlaps with a different entry in my Firebase collection.

Explaining everything with in detail here

Here is the image of my user entries in my Firebase Authentication ( I’m using signinwithEmailAndPassword functionality )

enter image description here

Now here is the Firestore entry of my first user whose ID is dv6d... with it’s data

enter image description here

Now when I applied update operation on my entery with user id pzF1.. my firestore collection for that ID is updated with the entries of user with id dv6d.. and the entires for that particular use has lost

here is the screenshot of that

enter image description here

I don’t know why it is happening

Here is the code which I worte for the update operations

This file displays all the users inside the dashboard

import React, { useState, useEffect, useMemo } from "react";
import PageTitle from "../components/Typography/PageTitle";
import {
  TableBody,
  TableContainer,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  TableFooter,
  Badge,
  Pagination,
  Button,
} from "@windmill/react-ui";
import { EditIcon, TrashIcon } from "../icons";
import { useAdmin } from "../context/AdminContext";
import { EditUser } from "../components/Dashboard/User";
import ThemedSuspense from "../components/ThemedSuspense";
import Search from "../helpers/Search";
import useSearch from "../hooks/UseSearch";

function User() {
  const { deleteData, getData } = useAdmin();
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [userData, setUserData] = useState([]);
  const [page, setPage] = useState(1);
  const [selectedUser, setSelectedUser] = useState(null);

  const resultsPerPage = 10;

  const searchOptions = {
    keys: [
      "fullName",
      "email",
      "phone",
      "facilityName",
      "facilityAddress",
      "status",
      "formId",
    ],
    threshold: 0.3,
  };

  const { results, search, searchPattern } = useSearch(userData, searchOptions);

  const paginatedUsers = useMemo(() => {
    const startIndex = (page - 1) * resultsPerPage;
    return results.slice(startIndex, startIndex + resultsPerPage);
  }, [results, page]);

  const totalResults = results.length;
  const totalPages = Math.ceil(totalResults / resultsPerPage);

  const handleSearchChange = (value) => {
    search(value);
    setPage(1);
  };

  const onPageChange = (newPage) => {
    setPage(newPage);
  };

  const handleSelectedUser = (user) => {
    setSelectedUser(user);
    setIsModalOpen(true);
  };

  const handleDeleteUser = (id) => {
    if (window.confirm("Are you sure you want to delete this User?")) {
      deleteData(id, "Users", setLoading);
    }
  };

  useEffect(() => {
    const loadUserData = async () => {
      setLoading(true);
      try {
        await getData("Users", setLoading, setUserData);
      } catch (error) {
        console.error("Error loading user data:", error);
      } finally {
        setLoading(false);
      }
    };

    loadUserData();
  }, [getData]);

  return (
    <>
      <div className="flex items-center flex-wrap lg:gap-5 justify-between">
        <PageTitle>Users</PageTitle>
        <Search
          searchQuery={searchPattern}
          setSearchQuery={handleSearchChange}
        />
      </div>
      {loading ? (
        <ThemedSuspense />
      ) : (
        <TableContainer className="mb-8">
          <Table>
            <TableHeader>
              <tr>
                <TableCell>Full Name</TableCell>
                <TableCell>FormId</TableCell>
                <TableCell>Email</TableCell>
                <TableCell>Phone</TableCell>
                <TableCell>Facility Name</TableCell>
                <TableCell>Facility Address</TableCell>
                <TableCell>User Status</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>Images</TableCell>
                <TableCell>Actions</TableCell>
              </tr>
            </TableHeader>
            <TableBody>
              {paginatedUsers.map((user, i) => (
                <TableRow key={i}>
                  <TableCell>
                    <span className="text-sm capitalize">{user?.fullName}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-sm capitalize">{user?.formId}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-sm lowercase">{user?.email}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-sm capitalize">{user?.phone}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-sm capitalize">
                      {user?.facilityName}
                    </span>
                  </TableCell>
                  <TableCell>
                    <span>{user?.facilityAddress}</span>
                  </TableCell>
                  <TableCell>
                    {user?.isVerified ? (
                      <Badge type="success">verified</Badge>
                    ) : (
                      <Badge type="danger">Not verified</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    {user?.status === "verified" && (
                      <Badge type="success">{user?.status}</Badge>
                    )}
                    {user?.status === "rejected" && (
                      <Badge type="danger">{user?.status}</Badge>
                    )}
                    {user?.status === "underprocessing" && (
                      <Badge type="warning">{user?.status}</Badge>
                    )}
                    {user?.status !== "verified" &&
                      user?.status !== "rejected" &&
                      user?.status !== "underprocessing" && (
                        <Badge>{user?.status}</Badge>
                      )}
                  </TableCell>
                  <TableCell>
                    <Button>
                      <a
                        href={user?.images[0]}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        Check Images
                      </a>
                    </Button>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-4">
                      <Button
                        layout="link"
                        size="icon"
                        aria-label="Edit"
                        onClick={() => handleSelectedUser(user)}
                      >
                        <EditIcon className="w-5 h-5" aria-hidden="true" />
                      </Button>
                      <Button
                        layout="link"
                        size="icon"
                        aria-label="Delete"
                        onClick={() => handleDeleteUser(user?.id)}
                      >
                        <TrashIcon className="w-5 h-5" aria-hidden="true" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          <TableFooter>
            <Pagination
              totalResults={totalResults}
              resultsPerPage={resultsPerPage}
              onChange={onPageChange}
              label="Table navigation"
            />
          </TableFooter>
        </TableContainer>
      )}
      {selectedUser && (
        <EditUser
          user={selectedUser}
          isModalOpen={isModalOpen}
          closeModal={() => setIsModalOpen(false)}
        />
      )}
    </>
  );
}

export default User;

Here is the EditUser component file

import React, { useState } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Input,
  Label,
  Select,
} from "@windmill/react-ui";

import { useAdmin } from "../../context/AdminContext";
import { sendMail } from "../../helpers/email";

export const EditUser = ({ user, isModalOpen, closeModal }) => {
  const [loading, setLoading] = useState(false);

  const { updateData } = useAdmin(); // updateData is a function from the AdminContext

  const [updatedData, setUpdatedData] = useState({ ...user });

  const handleSave = async () => {
    await updateData(user?.id, "Users", updatedData, setLoading);

    if (user.status !== updatedData.status) {
      if (updatedData.status.toLowerCase() === "verified") {
        sendMail(user?.email, "verified");
      } else if (updatedData.status.toLowerCase() === "rejected") {
        sendMail(user?.email, "rejected");
      } else if (updatedData.status.toLowerCase() === "underprocessing") {
        sendMail(user?.email, "underprocessing");
      } else if (updatedData.status.toLowerCase() === "qrcodeprocessing") {
        sendMail(user?.email, "qrcodeprocessing");
      } else if (updatedData.status.toLowerCase() === "qrcodecompleted") {
        sendMail(user?.email, "qrcodecompleted");
      }

      closeModal();
    }
  };

  const handleChange = (e) => {
    setUpdatedData({ ...updatedData, [e.target.name]: e.target.value });
  };

  return (
    <Modal isOpen={isModalOpen} onClose={closeModal}>
      <ModalHeader>Edit user</ModalHeader>
      <ModalBody className="space-y-4">
        <div className="grid md:grid-cols-2 grid-cols-1 gap-3">
          <Label>
            <span>Full Name</span>
            <Input
              className="mt-1"
              placeholder="Ex. John"
              defaultValue={user?.fullName}
              name="fullName"
              onChange={handleChange}
            />
          </Label>
          <Label>
            <span>FormId</span>
            <Input
              className="mt-1"
              placeholder="Ex. John"
              defaultValue={user?.formId}
              name="formId"
              onChange={handleChange}
            />
          </Label>
        </div>
        <div className="grid md:grid-cols-2 grid-cols-1 gap-3">
          <Label>
            <span>Facility Name</span>
            <Input
              className="mt-1"
              name="facilityName"
              defaultValue={user?.facilityName}
              onChange={handleChange}
            />
          </Label>

          <Label>
            <span>Facility Address</span>
            <Input
              className="mt-1"
              placeholder="facilityAddress"
              name="facilityAddress"
              defaultValue={user?.facilityAddress}
              onChange={handleChange}
            />
          </Label>
        </div>
        <div className="grid md:grid-cols-2 grid-cols-1 gap-3">
          <Label>
            <span>Phone</span>
            <Input
              className="mt-1"
              placeholder="number"
              name="phone"
              defaultValue={user?.phone}
              onChange={handleChange}
            />
          </Label>
          <Label>
            <span>Status</span>
            <Select
              className="mt-1"
              name="status"
              onChange={handleChange}
              defaultValue={user?.status}
            >
              <option value="verified">Verified</option>
              <option value="underprocessing">Under Processing</option>
              <option value="qrcodeprocessing">QRCode Processing</option>
              <option value="qrcodecompleted">QRCode Completed</option>
              <option value="rejected">Rejected</option>
            </Select>
          </Label>
        </div>
      </ModalBody>
      <ModalFooter>
        <div className="hidden sm:block">
          <Button layout="outline" onClick={closeModal} disabled={loading}>
            Cancel
          </Button>
        </div>
        <div className="hidden sm:block" onClick={handleSave}>
          <Button>Save</Button>
        </div>
        <div className="block w-full sm:hidden">
          <Button block size="large" layout="outline" onClick={closeModal}>
            Cancel
          </Button>
        </div>
        <div className="block w-full sm:hidden">
          <Button block size="large" disabled={loading} onClick={handleSave}>
            Save
          </Button>
        </div>
      </ModalFooter>
    </Modal>
  );
};

here is the update data funtion from my AdminContext


  const updateData = async (docId, dbName, updatedData, setLoading) => {
    try {
      setLoading(true);
      const docRef = doc(db, dbName, docId);

      await runTransaction(db, async (transaction) => {
        const docSnapshot = await transaction.get(docRef);

        if (!docSnapshot.exists()) {
          throw new Error("Document does not exist!");
        }

        const { id, ...dataWithoutId } = updatedData;

        // Perform the update within the transaction
        transaction.update(docRef, dataWithoutId);
      });

      toastSuccess(`${dbName} Updated Successfully`);
    } catch (error) {
      toastError(error.message);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

I’m using firebase transaction to ensure atomicity but still the update operations is overlapping my enteries

Please let me know if there is any confusion.

Accessing SVG to extract bounding boxes

I have a local SVG file and want to access the individual bounding boxes of each group, rendered by the browser (and write them to a JSON file).
My html file looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>SVG Group Access Test</title> 
    </head>
    <body>

        <object data="output.svg" type="image/svg+xml"
         id="alphasvg" width="100%" height="100%"></object>

        <script>
            var a = document.getElementById("alphasvg");

            // It's important to add a load event listener to the object,
            // as it will load the svg doc asynchronously
            a.addEventListener("load", function() {

                // Get the inner DOM of output.svg
                var svgDoc = a.contentDocument;

                // Check if the SVG document is loaded
                if (svgDoc) {
                    // Get all <g> elements within the SVG
                    var groups = svgDoc.querySelectorAll('g');

                    // Iterate over each <g> element
                    groups.forEach((group, index) => {
                        // Log group details to console
                        console.log(`Group ${index + 1}:`, group);

                        // Optionally, get the bounding box of the group
                        var bbox = group.getBBox();
                        console.log(`Bounding box for Group ${index + 1}: x=${bbox.x}, y=${bbox.y}, width=${bbox.width}, height=${bbox.height}`);
                    });
                } else {
                    console.error("Could not access the SVG document.");
                }
            }, false);
        </script>
    </body>
</html>

this html file and output.svg are both in same directory and I open the html with a browser. Despite this, I can not access the SVG (svgDoc is null). I think this has something to do with access policies as described here

I am new to this and want to prevent running a server. I want to call this html file from python as command instead.

How to style dayHeaders and dayGrids in FullCalendar in Vue?

I’m new to Vue and JS in general, currently trying to implement a calendar using FullCalendar. I would like to change the text color of the day headers and days but unable to do so. I read the documentation where there is an option for Day-Header Render Hooks but I’ve tried and it didn’t work, the following are my code:

<template>
    <FullCalendar class="calendar-app-calendar" :options="calendarOptions">
        <template v-slot:eventContent="arg">
            <p> Text </p>
        </template>
    </FullCalendar>
</template>

<script setup>
    import { ref } from 'vue';
    import FullCalendar from '@fullcalendar/vue3';
    import dayGridPlugin from '@fullcalendar/daygrid';
    import timeGridPlugin from '@fullcalendar/timegrid';
    import interactionPlugin from '@fullcalendar/interaction';

    const handleDayHeader = (arg) => {
        arg.el.style.color = 'red';
    }

    const calendarOptions = ref({
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth' //,timeGridWeek,timeGridDay
        },
        initialView: 'dayGridMonth',
        dayHeaderDidMount: handleDayHeader,
        dayHeaderClassNames: (arg) => {
            console.log('dayheaderclassnames...', arg);
            return ['week-header'];
        }
    });
</script>

<style>
    .week-header {
        color: red !important; /* Change text color of weekend headers */
    }
</style>

I tried the code I provided above but it did not have any effect on my calendar. I expect the text color of day header “Mon, Tues etc.” to change to red.

Auto load task pane in a newly created Word document from existing word document in a Word add in blazor project?

I have created a new Word document from existing word document in a Word addin Blazor project. I want to add content in a new Word document and also load the task pane in a new word document similar to existing Word task pane. I have written a code but it does not display the content in a new document, it displays in existing word context and the task pane is also not auto loaded in a new word document. Basically I want to create a word document similar to an existing word document.

export async function createNewDocument() {
    try {
        // Create and open the new document
        let newDocUrl;
        await Word.run(async (context) => {
            const newDoc = context.application.createDocument();
            newDoc.open();

            // Sync to ensure the new document is opened
            await context.sync();

            // Get the URL of the new document (if possible, or use another method)
            newDocUrl = Office.context.document.url; // This helps confirm we're dealing with the new doc
        });

        // Adding a short delay to ensure the new document is fully initialized
        await new Promise(resolve => setTimeout(resolve, 1000));

        // Use another `Word.run` block to interact with the new document explicitly
        await Word.run(async (newContext) => {
            // Ensure the context is correctly tied to the newly opened document
            if (Office.context.document.url === newDocUrl) {
                const newDocument = newContext.document;

                // Insert content into the new document
                newDocument.body.insertText(
                    "This is the new content for the new document.",
                    Word.InsertLocation.end
                );

                // Sync after content insertion
                await newContext.sync();

                // Set the task pane to auto-show with the new document
                Office.context.document.settings.set(
                    'Office.AutoShowTaskpaneWithDocument',
                    true
                );

                // Save the settings asynchronously
                await new Promise((resolve, reject) => {
                    Office.context.document.settings.saveAsync((result) => {
                        if (result.status === Office.AsyncResultStatus.Succeeded) {
                            resolve();
                        } else {
                            reject(result.error);
                        }
                    });
                });

                // Show the task pane explicitly in the new document
                Office.addin.showAsTaskpane();

                // Sync to confirm task pane is shown
                await newContext.sync();
            } else {
                throw new Error("Failed to switch to the new document context.");
            }
        });

    } catch (error) {
        console.error("Error creating or modifying the new document: ", error);

        // Detailed error logging
        if (error instanceof OfficeExtension.Error) {
            console.error("Debug info: ", JSON.stringify(error.debugInfo));
        }

        throw error; // Re-throw to handle in the calling function
    }
}

I have successfully created a new word document from existing word document. But I cannot add the content in a new Word document and auto load the task pane as it is similar to existing word task pane. I want to auto load the sideloader in Word. My condition is if the existing document is already saved and it already contains the content I need to create a new document and insert my content or data in a new word document and also load the taskpane(sideloader) same as existing word document? my c# code is below

private async Task<string> EditDocument()
{
    try
    {
              isDocumentSaved = await JSRuntime.InvokeAsync<bool>("wordInterop.checkIfDocumentIsSaved");
        Console.WriteLine("status of saved docuemnt"+ isDocumentSaved);
  if (isDocumentSaved == true)
  {
      try
      {
          // Create a new document and ensure all operations are in its context
           await JSModule.InvokeVoidAsync("createNewDocument");     

        
          return "New document created and operations performed.";

      }
catch (Exception ex)
        {
    Console.WriteLine($"Error: {ex.Message}");
                throw new Exception("Error in processing new document: " + ex.Message);
            }

        }

  else
  {
 //perform ooperation in existing word document 
}
    }
    catch (Exception ex)
    {
        throw new Exception("message:-"+ ex.Message);
    }

}

Initialization error when calling a function in an imported helper file

After writing a lot of TypeScript form logic held in multiple files, I thought I would include all my common functions in a helper.ts file. Getting it wired up is proving a bit difficult. Be interested in hearing any advice.

I have set up simple project structure for an app. To start with I have 2 files

  1. utilshelper.ts

       // show a simple dialog
       export function displayPromptText(titleText : string, promptText : string)
       {
         let alertStrings = { confirmButtonLabel: "Ok", text:promptText, title: 
         titleText  };
         var confirmOptions = { height: 400, width: 450 }; 
         Xrm.Navigation.openAlertDialog(alertStrings, confirmOptions).then(  
         function (success) {    
    
         console.log("Dialog closed using OK button.");
         }, function (error) {
          console.log(error.message)
       }  
    
     )   
    }
    
  2. FormsMyForm.ts

      import * as helper from  "../utils/helper"
      // also tried this
     // import { displayPromptText } from "../utils/helper";
    
    
      // if you call the line below say in Form load you get the intialisation error 
      helper.displayPromptText("test","test");
    

Calling a function in the helper.ts triggers this error

How to redirect to calling page if Javascript fetch gets a redirect

I have a case where I’m calling fetch() and if the response is a 302 Redirect, I want to redirect the calling page to wherever it redirects to instead of following the redirect to retrieve the data.

The scenario is that the user does something on a page which is going to do a fetch to retrieve something to update on the page. But if their login session has expired, the server is going to return a 302 Redirect to the login page. My Javascript is expecting a JSON response back, but instead fetch follows the redirect and it gets an HTML page.
What I really want to do is check if the response.status is 302, get the URL that the redirect pointed to and set window.location.

According to the documentation, I should be able to set redirect: "manual", then if the response.redirected is true redirect to response.url, or some say to retrieve the location header from the response

But none of that works.

  • response.redirected is never true.
  • response.status is zero.
  • response.url is the URL of the page that made the call, not where it was redirected to.
  • The location header is null.

The only thing that seems to work is that the Network tab shows that the server returned a 302 status.
Here’s my code:

   fetch("url-that-forces-a-redirect", {
       method: "POST",
       redirect: "manual",
       body: formData
    }).then((response) => {
       console.log("Response had status " + response.status);
       if (response.redirected) {
           var redirectedUrl = response.headers.get('location');
           console.log("Got redirect: location header = " + redirectedUrl);
           console.log("                 response.url = " + response.url);
           // window.location = redirectedUrl;
           return;
       }
    });

Is there any way to do this?

BTW, I tried doing this with XMLHttpRequest first and couldn’t find a way to do it there either.

Multilingual URL validation in React JS?

How can i implement multilingual URL validation in React JS?

Code Snippet: –

import * as Yup from "yup";
const validUrl = require("valid-url");
const validateUrl = (url) => {
  const isValidUri = validUrl.isUri(url);
  return isValidUri && isValidUri.startsWith("https://");
};

producturl: Yup.string()
    .test("url", "Invalid Product Url", (value) => {
      return validateUrl(value);
    })
    .required("Product url field is required"),

What is the difference between initializing an array, filling with a value, and mapping to empty arrays versus just filling with empty arrays? [duplicate]

I am currently working on this problem on Leetcode. I noticed that depending on how I initialize the array that will hold the adjacency lists for each course, I get a different answer.

let graph = new Array(numCourses).fill(0).map(() => []) // works

let graph = new Array(numCourses).fill([]) // does not work

I logged the value of graph after initialization to the console and for both cases, I get [ [], [] ] for my first test case. I was expecting them both to work as from what I can see, they are both arrays of equal length containing empty arrays. However, the graph that was set by just filling with empty arrays did not produce the expected outcome.

Is there difference bewteen arrays that are filled and then mapped to some value and those that are just filled with that value?

How can I add a scale animation to a background-attachment:fixed element?

I am trying to make an element that :

  • has the background-attachment: fixed attribute, so when you scroll it does not scroll with you ;
  • have a beautifull scale-out animation that runs once.

My problem is that both does not seem to be compatible.

  1. When I use the scale or transform: scale(...) properties, the background-attachment property gets broken.
  2. When I use the width and height properties, it does not seem to change the position and size of the image, so there is not any animation, because the image gets only cropped.
  3. I’ve found for a lot of pages, but I couldn’t find any dealing with that on stackoverflow, except some couples of unanswered questions.

There is my css code (exemple with “scale”):

main div.full-banner
{
    position: relative;
    width: 100%;
    padding: var(--main-full-banner-padding);
    box-sizing: border-box;
    overflow: hidden;
    box-shadow: 0px 0px var(--main-full-banner-shadow-size) var(--main-full-banner-shadow-color);
}

div.full-banner div.banner-background
{
    position: absolute;
    background-position: 50% 50%;
    background-size: cover;
    background-image: url('...');
    top: -1%;
    left: -1%;
    
    width: 102%;
    height: 102%;

    padding: 0px;
    margin: 0px;
    animation: full-banner-zoom 60s ease-out;
}

@keyframes full-banner-zoom {
    from {
        scale: 120%;
    }

    to {
        scale: 100%;
    }
}

main div.full-banner div.banner-content
{
    position: relative;
    z-index: 2;
}


And there is an example of how to use it :

<div class='full-banner'>
    <div class='banner-background'>
    </div>
    <div class='banner-content'>
        <h2>Hello world!</h2>
        <p>Lorem Ipsum Dolor Sit Amet</p>
    </div>
</div>

How can I allow the background to at the same time have background-attachment: fixed and a animation on its scale?

filterBooks() function is giving me a run for my money

I have been trying to figure this out for about an hour. It’s from a CodeAcademy snipet that I just can’t seem to get to work. All other functions are functional, but this one keeps failing with the same error. Maybe I just need to walk away and try again tomorrow but I figured I’d ask the hive brain here.

// Click handler for search button
const captureSearchValue = () => {
  const searchInput = document.getElementById("search-bar"); // Corrected ID
  return searchInput ? searchInput.value.trim() : "";
};

// Filter books based on search input
const filterBooks = (books, searchValue) => {
  return books.filter((book) => {
    // Flatten the book object into a single array
    const valuesArray = flattenObjectValuesIntoArray([book])[0];
    return valuesArray.includes(searchValue);
  });
};

// Empty the book list container, iterate over list of filtered books,
// return list of books formatted as HTML using the function in `helper.js`
const structureBooksAsHtml = (filteredBooks) => {
  // Assuming structureBookAsHtml is defined in helper.js
  return filteredBooks.map((book) => structureBookAsHtml(book));
};

// Handler triggered when a user clicks the "Search" button
const searchBtnClickHandler = (books) => {
  const searchValue = captureSearchValue();
  const filteredBooks = filterBooks(books, searchValue);
  const bookHtmlArray = structureBooksAsHtml(filteredBooks);

  renderBooksToDom(bookHtmlArray);
};

// Grab search button from the DOM
const searchBtn = document.getElementById("search-btn");

// Attach an event listener to the search button
searchBtn.addEventListener("click", () => {
  searchBtnClickHandler(books);
});





The filterBooks() function takes in a search string and a list of books as parameters and returns all of the books that contain an exact match of the search input as an array of objects. Objects in this array should be formatted as books with title, author, and tags properties, similar to the original books array. It should use the flattenObjectValuesIntoArray() function to search all fields within a book object easily.

There was an error with the function `filterBooks`. Please check that it was defined correctly.

Above is where I’m at so far. Some of the changes I’ve tried make all other functions fail, and others don’t seem to do anything at all.

Requirements:
The captureSearchValue function captures the search bar input value and returns it. (complete)

The filterBooks() function takes in a search string and a list of books as parameters and returns all of the books that contain an exact match of the search input as an array of objects. Objects in this array should be formatted as books with title, author, and tags properties, similar to the original books array. It should use the flattenObjectValuesIntoArray() function to search all fields within a book object easily. (incomplete)

There was an error with the function filterBooks. Please check that it was defined correctly.
The structureBooksAsHtml() function takes a list of books as a parameter, iterates over the list, formats them as HTML using the structureBookAsHtml() helper function, and returns an array of formatted book elements. (complete)

The searchBtnClickHandler() function is triggered when a user clicks the search button. It takes in a list of books as a parameter and integrates the individual functions that make up the app to render a list of books to the DOM that matches the search input when the search button is clicked. (complete)