var user = Session.getActiveUser().getEmail(); doesnt get the email but gets an empty string?

So my code suppose to make me a tracking sheet of edits on the main sheet but when its gets the email it gives an empty email unless its my main email then its works for some reason here is the main function. and my friend from his pc it didnt even got “” the script didnt run so irdk the problems. btw i am new to this so dont make fun of me please.

function onEdit(e) {
  // Check if the event object is defined
  if (!e || !e.source) {
    // If the event object is not defined or does not have 'source' property, exit the function
    return;
  }

  var ss = e.source; // Get the active spreadsheet
  var trackingSheetUrl = "https://docs.google.com/spreadsheets/d/1VR1wc5xGtAB6dYmQCf9ChphwfHoOYI-7qKEjJEs42Lo/edit#gid=1175584031"; // Put the URL of your tracking sheet here
  var trackingSpreadsheet = SpreadsheetApp.openByUrl(trackingSheetUrl);
  var trackingSheet = trackingSpreadsheet.getSheets()[1]; // Assuming the tracking sheet is the first sheet

  var user = Session.getActiveUser().getEmail(); // Get the email of the user who made the change
  if (user == ""){
    user = "error";
  }
  var userLocation = searchDataColumnWithUser(trackingSheetUrl, user);
  if (userLocation) {
    // User found, increment the value
    var currentValue = userLocation.getValue();
    userLocation.setValue(currentValue + 1);
  } else {
    // User not found, create new row
    var lastUserRow = trackingSheet.getLastRow();
    var newUserRow = lastUserRow + 1;
    trackingSheet.getRange(newUserRow, 1).setValue(user); // Set username
    trackingSheet.getRange(newUserRow, 2).setValue(1);    // Set initial value as 1
    trackingSheet.getRange(newUserRow, 2).setValue(1);    // Set initial value as 1
  }
}

I suppose to get the email and update the sheet.

I have an error with my singleton design pattern

I am attempting to do a singleton pattern in javascript. I am getting error message “Uncaught TypeError: route_socket.getInstance is not a function”. I was wondering what am I doing wrong. I can copy and paste the pattern from a training guide and it works. But when I am trying it here, it gives the error. So I know the pattern works.

var route_socket = require([
    "esri/WebMap",
    "esri/views/MapView",
    "esri/layers/RouteLayer",
    "esri/rest/support/Stop"
  ],
  function(WebMap, MapView, RouteLayer, Stop) { //singleton design pattern
    var instance;

    class RouteSocket {#
      apiKey;

      constructor() {
        this.#apiKey = token.getAttribute("token");
        this.routeUrl = "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
        this.churches = [];
        this.stompClient = null;
        this.view = null;
        connect();
        this.origin = new Stop({
          geometry: {
            x: OX,
            y: OY
          },
          name: "Origin"
        })
        this.destination = new Stop({
          geometry: {
            x: DX,
            y: DY
          },
          name: "Destination"
        })
        addRandomChurch();
        addRandomChurch();
        addRandomChurch();
      }

      addRandomChurch() {
        var randomX = ((OX - DX) * Math.random()) + OX;
        var randomY = ((OY - DY) * Math.random()) + OY;
        var ChurchStop = { //Create a point
          x: randomX,
          y: randomY,
          name: "Church"
        };
        this.churchAdded(ChurchStop);
      }

      setView(view) {
        this.view = view;
        console.log("We have set the view");
        //check for churches already found and map them if they are there
        this.churches.forEach(this.addRoute(church));
      }

      connect() {

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, this.onConnected, this.onError);
      }

      async addRoute(church) {
        let stops = [
          this.origin,
          church,
          this.destination
        ];

        let routeLayer = new RouteLayer({
          stops
        });
        view.map.add(routeLayer);
        await routeLayer.load();
        const results = await routeLayer.solve({
          apiKey
        });
        routeLayer.update(results);
        //            await view.goTo(routeLayer.routeInfo.geometry);
      }

      onConnected() {
        stompClient.subscribe('/topic/map/' + hobnobID.getAttribute("hobnobID"), this.onMessageReceived);
        synchroniseDataMapSocket.establishSocket(this);
      }

      onMessageReceived(payload) {
        var message = JSON.parse(payload.body);

        var ChurchStop = { //Create a point
          x: message.X,
          y: message.Y,
          name: "Church"
        };
        this.churchAdded(ChurchStop);
      }

      churchAdded(ChurchStop) {
        if (!this.view) {
          churches.add(ChurchStop);
          return;
        } else {
          this.addRoute(ChurchStop);
        }
        //else create stop on map
      }
    };

    function createInstance() {
      var object = new RouteSocket();
      return object;
    }

    return {
      getInstance: function() {
        if (!instance) {
          instance = createInstance();
        }
        return instance;
      }
    };
  });
route_socket.getInstance();

I am really grateful for any help I may receive. Thank you very much

Captivate SCORM in Moodle – JavaScript Error

I’m using Adobe Captivate Classic (2019).
I have created a SCORM project and it works great in Preview mode (Preview > Project menu).
I have created a variable named slideNum and a number of advanced actions. Again everything works well in preview mode. It also works well in my test in scorm.cloud.com as can be seen in the image where teh green tick appears after clicking the next button.

Works in scorm.cloud.com

I have JavaScript code as follows which is executed when I click the “next” button:

var currSlide = window.cpAPIInterface.getCurrentSlideIndex();
$("#icon_tick_slide" + currSlide + "c").css("visibility", "visible");

This displays an otherwise hidden tick mark when I click the next button.
The problem is that while this works in preview mode and in scorm.cloud.com, no matter what I try I cant get this to work on a moodle SCORM package. The tick simply wont show.

I’ve tried all sorts of combinations of SCORM exports from Moodle and code variations using window.onload and jQyery(document).ready even though none of the examples I’ve seen require this.

I’m using the documentation at https://helpx.adobe.com/captivate/classic/common-js-interface.html

Thanks for any help.

check if a specific div exists by class and data attribute without looping all the elements with that class

I have several divs in my UI with the same class. Each of them has a different data-id.
I want to check if one of the divs has a specific value for the data-id.
I can do it with .each() but was wondering if there is a way not to iterate every time on all the divs.
If I find a div (by class and data-id value) I need to manipulate its content. If I don’t find any div that satisfy the two criteria then I will perform some different activities.

What I have now (works but iterates every time the Dom)

let found = false;
$('.discussion').each(function(){
    if($(this).data("id")==myVariable){
        //I have found what I am looking for
        //do my stuff
        found = true;
    }
});
if(found===false){
    //I have not found what I was looking for
    //so I will add the div with that class and data-id
}

There can be even more then 10 divs with that class and this event will fire even 100 times a minute so performance may be impacted.

Is there a way to copy paste the contents of an HTML table into an Email Message?

I’m working on a locally hosted website using HTML, CSS, JS, Flask and SQLite3.

I want to create a functionality where the user is able to share the contents of a table via Email and I’ve created a ‘Share via Email’ button for the same.

When I run the program, the body of the email simply contains – ${inventoryTable} and the content is not displayed.

I know the data isn’t being retrieved correctly. How do I resolve this.

I don’t think I can attach the entire HTML page as its confidential, but the specific line of code I’m talking about is below…

<a href="mailto:?subject=Inventory Table &body=Inventory table details:%0D%0A%0D%0A ${inventoryTable}" target="_blank">Share via Email</a>

This line is supposed to retrieve data from a table wiht ID = “inventoryTable.”

This is what part of inventoryTable looks like –

<table id ="inventoryTable">
                <tr style="position: absolute; margin-top: -40px; z-index: 1;">
                    <th>Product ID</th>
                    <th>Product Name</th>
                    <th>Price(₹)/Unit</th>
                    <th>Quantity Available</th>
                    <th>Shelf Location</th>
                    <th>Accept Returns</th>
                    <th>Reorder Quantity</th>
                    <th>Edit Item</th>
                    <th>Delete Item</th>
                </tr>
                {% for item in data %}
                <tr>
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td>{{item.quant_a}}</td>
                    <td>{{item.shelf}}</td>
                    <td>{{item.returns}}</td>
                    <td>{{item.quant_r}}</td>
                    <td>

I basically want the table headers and the rows to be copied into the email. I think I need to use JS for this but I’m not sure.

Help, please.

P.S. – I’m a 16yr old high-school kid doing this for a real-world client so could really use some help. (Also would really appreciate it if you could explain your solution a tad bit extra).

App renavigates to the logIn Page even if a new JWT token is regenerated

I am generating an accessToken for a user upon Login and a refreshToken
which helps to regenerate another accessToken for the user
if the user trys to refresh a page or the token times out.
but the problem is though these tokens are generated as it should be,
I am always redirected to Login page when I refresh the page
or when I click to access another Tab in the menue. What could
be the problem here.


//here is the Routes

const App = () => {
  return (

    <Routes>
      <Route path='registerPage' element={<RegisterPage />} />

      <Route path='logIn' element={<LogInPage />} />
      
      {/* Protected Routes */}
      <Route element={<PersistLogIn/>}>
      <Route element={<RequireAuth />}>

        <Route path='/' element={<Layout />}>

          <Route index element={<Home />} />

          <Route path='dashboard' element={<HomeLayOutt />} />

          <Route path='moneyIn' element={<MoneyIn />} />

          <Route path='moneyOut' element={<MoneyOut />} />
          <Route path='inventory' element={<Inventory />} />
    </Route> 
    </Route>
 </Routes>


//LogIn Page

const LogInPage = () => {
    const [username, setUserName] = useState("")
    const [password, setPassWord] = useState("")
    const {setAuth} = useAuth()


    const handleUser_Name =(e)=>{
        setUserName(e.target.value)
      }
      const handlePass_word = (e)=>{
        setPassWord(e.target.value)
      }
    
    const location = useLocation()

    const from = location.state?.from?.pathname || '/'

    const navigate = useNavigate()

    const goToRegister =()=>navigate('/registerPage')

        const handleLogIn=()=>{
        Axios.post('http://localhost:3500/auth', JSON.stringify({username, password}),
          {
            headers:{'Content-Type' : 'application/json'},
            withCredentials: true
          }
        )
        .then(res=> {    
            console.log(JSON.stringify(res?.data))
            console.log((res?.data))
            const accessToken = res?.data?.accessToken
            setAuth({username, password, accessToken})

            setUserName('')
            setPassWord('')

            navigate(from, {replace: true})
            
        }).catch(err =>{console.log(err)})
    }
}

//Context API(AuthProvider)

import { createContext, useState } from "react";

const AuthContext = createContext({})

export const AuthProvider =({children})=>{
   const [auth, setAuth] = useState({})
   console.log(auth)

  return(
  <AuthContext.Provider value={{auth, setAuth}}>
    {children}
   </AuthContext.Provider>
  )
}
export default AuthContext

//useAuth

import { useContext } from "react";
import AuthContext from "../context/AuthProvider";

const useAuth = () =>{
    return useContext(AuthContext)
}
export default useAuth

//RequireAuth

import {useLocation, Navigate, Outlet} from 'react-router-dom'
import useAuth from '../hooks/useAuth'

//check if the user is logged in or not
//this is a component that will help us protect our routes
const RequireAuth = () =>{
    const {auth} = useAuth()
    const location = useLocation()
   console.log(auth)
     return(
        auth?.username ? <Outlet/> : <Navigate to='/login' state={{from: location}} replace/>
     )
}
export default RequireAuth

//PersistLogIn

const PersistLogIn = () => {
    const [isLoading, setIsLoading] = useState(true)
    const refresh = useRefreshToken()

    const {auth, persist} = useAuth()

    useEffect(()=>{

        const refreshTokenVerify = async () =>{
            try{
               
               await  refresh()
            }
            catch(err){
                console.error(err)
            }
            finally{
                setIsLoading(false)
            }
        }

        !auth?.accessToken ? refreshTokenVerify() : setIsLoading(false)
    },[])

    useEffect(()=>{
        console.log(`isLoading: ${isLoading}`)
        console.log(`aTh: ${JSON.stringify(auth?.accessToken)}`)
    },[isLoading])

  return (
    <>
                {isLoading
                    ? <p>Loading...</p>
                    : <Outlet />
            }
    </>
  )
}

export default PersistLogIn





//BackEnd

//authController

const handleUserLogIn = async (req, res)=>{
    const {username, password} = req.body
    if(!username || !password) return res.status(400).json({'message':'username or password is required'})//Bad Request

    const foundUserData = await User.findOne({username}).exec();
    console.log(foundUserData) 

    if(!foundUserData) return res.sendStatus(401)//Unauthorized

    const validPassword = await bcrypt.compare(password, foundUserData.password)
    if(!validPassword){
        return res.sendStatus(401)//Unauthorized
    }else{
      //create the JWT
      const accessToken= jwt.sign({'username':foundUserData.username}, 
      process.env.ACCESS_TOKEN_SECRET, {expiresIn: '30s'})
      const refreshToken= jwt.sign({'username':foundUserData.username}, 
      process.env.REFERESH_TOKEN_SECRET, {expiresIn: '5m'})

      //save refreshToken with current user
      foundUserData.refreshToken = refreshToken
      const result = await foundUserData.save()
      console.log(result)
      
      //create a secured cookie with refreshToken
      res.cookie('jwtToken',refreshToken, {httpOnly: true, maxAge: 300000} ) //secure: true
      
      //res.cookie('token', accessToken, {httpOnly: true, maxAge: 20000})

      //Send access Token to user
      res.json({accessToken})
    }
        
}

module.exports={handleUserLogIn}

//refreshTokenController

const handleRefreshToken = async(req, res)=>{
  const cookies = req.cookies
  console.log(cookies.jwtToken)

  if(!cookies?.jwtToken) return res.sendStatus(401)//unauthorized //.jwt
  console.log(cookies.jwtToken)
  const refreshToken = cookies.jwtToken

  const foundUserData2 = await User.findOne({refreshToken}).exec()
  if(!foundUserData2) return res.sendStatus(403)//Forbidden

  //evaluate JWT
  jwt.verify(refreshToken, process.env.REFERESH_TOKEN_SECRET, 
     (err, decoded)=>{
        if(err || foundUserData2.username !== decoded.username)return res.sendStatus(403);//forbidden
        //another accessToken is created
        const accessToken = jwt.sign(
        {'username':decoded.username}, 
        process.env.ACCESS_TOKEN_SECRET, 
        {expiresIn: '30s'}
        )

      res.json({accessToken})
     })
}
module.exports = {handleRefreshToken}

TypeScript check if return type is an array

I am setting up some apis using typescript. I have a particular api that either returns an array of objects or a string.

interface SubmissionDetails {
  branchName: string
  clientAddress1: string
  clientAddress2: string
  clientCity: string
  clientContactEmail: string
  clientContactFullName: string
  clientName: string
  clientState: string
  clientZip: string
  id?: string
  namedInsured: string
  submissionID: string
  underwriterDisplayName: string
}

  getAllReferralsBySubmissionId: (
    submissionId: string
  ) => Promise<SubmissionDetails[] | { message: string }>

Now I am taking the return value from getAllReferralsBySubmissionId and trying to run some logic.

  if (typeof referralsList === "object") {
    referralsList?.forEach((item: SubmissionDetails) => {
      item.id = item.submissionID
    })
  }

I am seeing a TypeScript error on the forEach function stating:

Property 'forEach' does not exist on type 'SubmissionDetails[] | { message: string; }'.
  Property 'forEach' does not exist on type '{ message: string; }'.

I understand that my function can return something that is not an array.
How can I update my function to remove this error?

Should I use “display: none” class or Javascript based conditional rendering for ISR or SSG Next.js

One quick question. I use getStaticProps with revalidate (ISR) in a nextjs 12 project. i can see in network tab that when i have 2 image components with same image but different sizes for example, and hide one on big screens and the other on small screens, that the fetch request for the hidden one is marked as “canceled” in the network tab.

Seems fine, 0 bytes fetched and no error response, just canceled. But i want to know if its better to not have it like that by conditionally rendering those images depending on screen size i got via a package, so javascript.

But then the question is is it making the performance worse or better because i use static site generation with revalidation.

Any languages with serializable / mobile runtime?

I am developing a system that executes arbitrary jobs. A job is a piece of code in some programming language (e.g. Javascript), it can run sub-jobs and wait for their completion as it is shown in the following snippet:

class Job {
    async run() {
        let subResult = await run_subjob();
    } 
}

I want to be able to start program, stop the execution at await, save the runtime state, save it in some persistent storage, efficiently wait for the subjob’s completion, load runtime back, continue execution. The OS-related resources (db connections, files and such stuff) referenced in the program can be guarded by using wrappers that maintain an execution session id and reinitialize entities when it doesn’t match the global session id.

Are there any programming languages that support this feature (AFAIK it is called Code Mobility)?

P.S. I found out that something similar was popular in 90s and was called “Mobile Agents” but I can’t find any maintained libraries.

set different color on click function in Canvas

I want to change color our button are Press then canvas inside text color change.

var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');

context.font = '48px serif';
context.fillStyle = 'red'; // sets text color to red
context.fillText('Example text', 20, 65);

function ChangeColor() {
  console.log("dd", context);
  context.fillStyle = "blue";
}
<!doctype html>
<html>

<head>
  <style>
    #my-canvas {
      border: 1px solid gray;
    }
  </style>
</head>

<body>
  <canvas id="my-canvas" width="300" height="100"></canvas>
  <br>
  <button onClick="ChangeColor()"> Change Font Color Blue</button>
</body>

</html>

How do I begin a composition event when programmatically focusing on an input/textarea element?

CompositionEvents are triggered on an input field when a user types in text using an IME, like when typing Chinese with a Pinyin keyboard.

I want the input to gain focus when I type anywhere on the web page. To do so I’ve attached a listener to the keydown event and call focus on the element:

const inputElement = document.querySelector('input[type="text"]');

function handleEvent(event) {
  console.log(event.type);
  console.log(event.data);
}

function handlekeydown(event) {
  inputElement.focus()
}

window.addEventListener("keydown", handlekeydown)

document.body.addEventListener("compositionstart", handleEvent);
document.body.addEventListener("compositionupdate", handleEvent);
document.body.addEventListener("compositionend", handleEvent);

And this works fine, but it does not carry over the composition event after focusing. So for example, if I type ‘ren’ in the input, ‘r’ is finalized into the input and then the IME menu opens for ‘en’:

enter image description here

But what I really want is for the IME menu to open for ‘ren’:

enter image description here

Css cube rotate with given sequence keeping picture orientation

I have 3d cube made from css, html. Like below.

<div class="box">
<div class="face">1</div>
<div class="face">2</div>
<div class="face">3</div>
Up to 6, for six sides of the box. 
</div>

Now I generate random near side sequence(keeping near side property).
Like [1,4,2,6,3,5] (this is just example, this maybe not near sided).

Near side :: which means when rotating cube only rotate to a near face / not skipping faces.

Without duplicate :: so that a face don’t show up until full all cube faces are shown by completing the given sequence. (no sequences like 1,4,1,6,3,5 or 1,4,2,6,3,6)

3)
Now I want to rotate the cube in this sequence.
Like
1(start/default face facing user), 4,2,6,3,5
1 to 4(4 facing user)
4 to 2(2 facing user)
So on up to 5.(complete of the sequence)

4)
I have images on every side of the box.
I want to keep/change the orientation, so that the image is in right orientation facing the user.

I have done 1) 2). But how do I accomplish 3rd and 4th.
I can provide more info / code if wanted.
But I would like to not effect your answer with my bad code/methods.

Basically what I want is to rotate the cube in a random face sequence (without duplicate) to near faces covering all 6 faces.

JavaScript filter() method not getting data [closed]

I am creating a Pokedex and I have added a filter to search for the Pokemon by either name or number. The ‘number’ filter is working correctly but the ‘name’ filter breaks every time. I am using if-else to check whether the ‘name’ or the ‘number’ filter is checked. Inside the else-if block I use the filter() method to filter out my ‘allPokemons’ array according to the search term. The problem is my filter() function does not get any data to work and the search fails.

function handleSearch() {
    const searchTerm = searchInput.value.toLowerCase()
    let filteredPokemons;

    if (numberFilter.checked) {
        filteredPokemons = allPokemons.filter( (pokemon) => {
            const pokemonID = pokemon.url.split("/")[6];
            return pokemonID.startsWith(searchTerm);
        });
    } else if (nameFilter.checked) {
        console.log(allPokemons);
        filteredPokemon = allPokemons.filter((pokemon) => {
            pokemon.name.toLowerCase().startsWith(searchTerm);
        })
    } else {
        filteredPokemons = allPokemons;
    }

    displayPokemons(filteredPokemons);

    if (filteredPokemons.length === 0) {
        notFoundMessage.style.display = 'block';
    } else {
        notFoundMessage.style.display = 'none';
    }
}

The error is as follows:
Error in Console

Honestly, I haven’t tried anything because I do not know what is wrong to think for any remedy for my situation. The problem does not arise in the if block of the code where I essentially do the same thing where I use one of the items of the object ‘pokemon’ just like in the else-if block. I tried console logging inside the else-if block and it works, but inside the filter method, it prints all the Pokemon names when I try to print the selected Pokemon, which leads me to the fact that the filter() method does not receive data. Here is the whole thing:

const MAX_POKEMON = 251;

const listWrapper = document.querySelector(".list-wrapper");
const searchInput = document.querySelector("#search-input");
const numberFilter = document.querySelector("#number");
const nameFilter = document.querySelector("#name");
const notFoundMessage = document.querySelector("#not-found-message");

let allPokemons = [];

fetch(`https://pokeapi.co/api/v2/pokemon?limit=${MAX_POKEMON}`)
.then((response) => response.json())
.then((data) => {
    allPokemons = data.results;
    displayPokemons(allPokemons);
});

async function fetchPokemonDataBeforeRedirect (id) {
    try{
        const [pokemon, pokemonSpecies] = await Promise.all([
            fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
            .then((res) => 
                res.json()
            ),
            fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}`)
            .then((res) =>
                res.json()
            ),
        ]);
        return true;
    }
    catch (error) {
        console.error("Failed to fetch Pokemon data before redirect")
    }
}

function displayPokemons (pokemon) {
    listWrapper.innerHTML = "";

    pokemon.forEach( (pokemon) => {
        const pokemonID = pokemon.url.split("/")[6];
        const listItem = document.createElement('div');
        listItem.className = 'list-item';
        listItem.innerHTML = `
        <div class="number-wrap">
            <p class="caption-fonts">${pokemonID}</p>
        </div>
        <div class="img-wrap">
            <img 
            src="https://raw.githubusercontent.com/pokeapi/sprites/master/sprites/pokemon/other/dream-world/${pokemonID}.svg" 
            alt="${pokemon.name}"/>
        </div>
        <div class="name-wrap">
            <p class="body3-fonts">${pokemon.name}</p>
        </div>
        `;

        listItem.addEventListener("click", async () => {
            const success = await fetchPokemonDataBeforeRedirect(pokemonID);
            if (success) {
                window.location.href = `./detail.html?id=${pokemonID}`;
            }
        });

        listWrapper.appendChild(listItem);
    })
}

searchInput.addEventListener('keyup', handleSearch);

function handleSearch() {
    const searchTerm = searchInput.value.toLowerCase()
    let filteredPokemons;

    if (numberFilter.checked) {
        filteredPokemons = allPokemons.filter( (pokemon) => {
            const pokemonID = pokemon.url.split("/")[6];
            return pokemonID.startsWith(searchTerm);
        });
    } else if (nameFilter.checked) {
        console.log(allPokemons);
        filteredPokemon = allPokemons.filter((pokemon) => {
            let selectedPokemon = pokemon.name.toLowerCase().startsWith(searchTerm);
            return selectedPokemon;
        })
    } else {
        filteredPokemons = allPokemons;
    }

    displayPokemons(filteredPokemons);

    if (filteredPokemons.length === 0) {
        notFoundMessage.style.display = 'block';
    } else {
        notFoundMessage.style.display = 'none';
    }
}

// const closeButton = document.querySelector("search-close-icon");
// closeButton.addEventListener("click", clearSearch);

// function clearSearch(){
    
// }
<main class="main">
        <header class="header-home">
            <div class="container">
                <div class="logo-wrapper">
                    <img src="./assets/pokeball.svg" 
                    alt="pokeball">
                    <h1>Pokedex</h1>
                </div>
                <div class="search-wrapper">
                    <div class="search-wrap">
                        <img 
                        src="./assets/search.svg" 
                        alt="search-icon" 
                        class="search-icon" 
                        />
                        <input 
                        type="text" 
                        class="search-input body3-fonts" 
                        placeholder="Search" 
                        id="search-input"
                        />
                        <img 
                        src="./assets/cross.svg" 
                        alt="cross icon" 
                        class="search-close-icon" 
                        id="search-close-icon"
                        />
                    </div>
                    <div class="sort-wrapper">
                        <div class="sort-wrap">
                            <img
                            src="./assets/sorting.svg" 
                            alt="sort-icon"
                            class="sort-icon"
                            />
                        </div>
                        <div class="filter-wrapper">
                            <p class="body2-fonts">Sort by:</p>
                            <div class="filter-wrap">
                                <div>
                                    <input
                                    type="radio"
                                    name="filters"
                                    id="number"
                                    value="number"
                                    checked
                                    autocomplete="off"
                                    />
                                    <label for="number" 
                                    class="body3-fonts">Number</label>
                                </div>
                                <div>
                                    <input
                                    type="radio"
                                    name="filters"
                                    id="name"
                                    value="name"
                                    autocomplete="off"
                                    />
                                    <label for="name"
                                    class="body3-fonts">Name</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </header>
        <section class="pokemon-list">
            <div class="container">
                <div class="list-wrapper"></div>
            </div>
            <div id="not-found-message">Pokemon not found</div>
        </section>
    </main>

Using getTimezoneOffset to get local time of the client

I need to capture the timezone offset of the client and store it in my database. To do this I have been using a hidden field in the login with some Javascript :

<form class="user" id="account" method="post">
    <input asp-for="Input.TimezoneOffset" type="hidden" />
....
</form>

$(document).ready(function () {

    var offset = new Date().getTimezoneOffset();
    document.getElementById("Input_TimezoneOffset").value = offset;
});

Then I store this value in a string session variable and whenever I need to convert a utc datetime from the database to display to the end user I use this code to convert the string to the local time :

public static DateTime ConvertUTCToLocalDateTime(DateTime utcDateTime, string timezoneOffset)
{
    TimeSpan offSet = TimeSpan.FromMinutes(Convert.ToDouble(timezoneOffset));
    DateTime localTime = utcDateTime - offSet;

    return localTime;
}

So far this is all working nicely. My question is, is this a reliable way to do this, or is there a better way?

How can I add scripts to Angular.json from a folder with a changing folder name?

I want to add multiple scripts contained in a downloaded folder to angular.json. The issue I’m facing is, that the scripts are generated by an external service and we just want to replace the folder containing the scripts in our project without changing any other configuration. Unfortunately the folders that contain the script and the scripts themselves are always generated with a different name than previously.

Is there a way to add all the .js files, that are contained in a specific folder to the scrips array in angular.json without providing the exact path?

Do you know any other approach to integrate the scripts dynamically?

We already thought about integrating them through a script injector service. That dynamically fetches all the scripts but we found this solution not to be good solution because it’s kind of ugly.