How to get the current weekday date in JavaScript

I have a function that takes the desired day number and ultimately I want it to be able to return the date of that day in the current week, given the day number it takes. This is my code.

function getDateForDayInWeek(day) {
    const today = new Date();
    const currentDay = (today.getDay() + 1) % 7;
    const adjustedDay = currentDay === 0 ? 6 : currentDay - 1;
    const daysToAdjust = (day - adjustedDay + 7) % 7;

    today.setDate(today.getDate() + daysToAdjust);

    // Formatting the date to YYYY-MM-DDTHH:mm:ss
    return today.toISOString().slice(0, 19);
}


console.log(getDateForDayInWeek(6)); //  2024-12-21 ,Saturday
console.log(getDateForDayInWeek(0)); //  2024-12-22 ,Sunday
console.log(getDateForDayInWeek(5)); //  2024-12-27 ,Friday

array.find() with sveltekit reactivity functioning sporadically

An app showing a list of building systems components with the ability to add a component. Database is Mongodb.

+page.js fetches the list, a defintition of the table + populates “lookup” lists (to display text instead of _id on the list), returning all these things in data

page.svelte uses svelte component <GenericListPage> passing in data.rows.components thus:

<div class="mt-2">
  Components
    <GenericListView
      definition="{data.subAssetDefinition}"
      data="{data.rows.components}"
      table="true"
      on:invalidate="{myInvalidate}"
    />
</div>

<GenericListView> builds a <table>, including a <TableRowTd> component:

{#each data as row}
  <tr on:click="{rowClick (row)}">
    {#each definition.tableFields as field}
      <TableRowTd
        {definition}
        {field}
        data="{row[field] || ''}"
      />
    {/each}
  </tr>
{/each}

Component <TableRowTd> has a $: function that takes the value in data (which is an _id) and searches through the appropriate list to match against the _id in the list and get the text.

$: {
  displayValue = data;
  let fieldDef = definition.schema.find (el => el.name == field);

  if (fieldDef && fieldDef.listType) {
    console.log (`<TableRowTd> looking up list for ${field} ${data} ${fieldDef.table}`)
    try {
      console.log (definition.lists)
      let list = definition.lists.find ((el) => el.table === fieldDef.table);

      if (list) {
        console.log (`found the list`)
        let row = list.data.find (el => el._id === data);
        if (row) {
          console.log (`found`)
          displayValue = row.value;
        }
      }
    } catch (err) {
      console.log('error on %s: %s', fieldDef.table, err.toString())
    }
  }
}

All functions as desired on initial page load:

image of list of components with lookup values shown

On adding an entry, the invalidate event is raised and passed up the stack – page.js' load function is called again.

However, now, in the $: function in <TableRowTd>, the let list = definition.lists.find ((el) => el.table === fieldDef.table); call now returns undefined, i.e. it does not find the item in the list, despite the item being present in the list:

image of list of components with _ids shown

Structure of the list:

screendump of array from console

Console log where we see the “match” failing:

console log showing failure of array.find()

Any thoughts on what’s going on here? Maybe I’m “overloading” array.find() somehow? Maybe there’s smart way to move this searching “up” to the <Generic ListPage> component?

Vite: ‘Failed to resolve import “./App.css”‘ error after deleting App.css from project

I’m working on a Vite project where I am using Tailwind CSS, and I’ve deleted the App.css file to replace it with Tailwind’s utility classes. However, I’m getting the following error:
Failed to resolve import "./App.css" from "src/App.jsx". Does the file exist?
My App.jsx file no longer imports App.css and contains:

import React from 'react';

const App = () => {
  return (
    <div>App</div>
  );
};

export default App;

I deleted App.css because I am not using it anymore, and I want to rely solely on Tailwind CSS for styling.
However, after deleting the App.css file, I am still getting the error about it trying to resolve ./App.css from App.jsx.
I have ensured that no other files are still referencing App.css.
I confirmed that Tailwind CSS is properly set up and working in my project.
The project runs fine when I revert to the old setup where App.css was present, but the error reappears after deleting App.css.

tailwind.config.js contains:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./index.html",  // Path to HTML files
    "./src/**/*.{js,jsx,ts,tsx}",  // Path to JS/JSX/TS/TSX files
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

main.jsx contains:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

I was following the setup from a youtube tutorial https://www.youtube.com/watch?v=zA9r5zTllx4 timestamp 00:03:48

Any help would be appreciated! Thanks in advance!

TipTip Tooltip Not Working on Multi-Select Element

I am using the TipTip JavaScript plugin to display tooltips on form inputs, including multi-select elements. The tooltips work fine on other input elements but are not showing up on the multi-select input. Below is the relevant code snippet I am using:

$(function () {
    // Tooltip
    $(".form_tiptip").tipTip({
        maxWidth: "auto",
        defaultPosition: "bottom",
        delay: 0,
        activation: "focus"
    });
});

<tr class="input-row">
    <td class="input-label"><?php echo __(T_FACILITY_NAME); ?></td>
    <td class="input-required"><span class="require-label"><?php echo __("*"); ?></span></td>
    <td class="input-form">
        <?php echo $this->Form->input(
            'store_id',
            [
                'id' => 'store-select',
                'type' => 'select',
                'empty' => '-',
                'options' => array_map(fn($x) => ['value' => $x['id'], 'text' => $x['store_name']], $shoppingStores),
                'default' => isset($selectedStore) ? $selectedStore['store_id'] : null,
                'disabled' => isset($selectedStore),
                'label' => false,
                'title' => CHK_STORE_NAME,
                'class' => 'input-xlarge chkselect form_tiptip multi-select'
            ]
        ); ?>
    </td>

What I Have Tried:

  • Verified that the .form_tiptip class is applied to the multi-select
    element.
  • Checked that the title attribute is present on the multi-select
    element.
  • Confirmed that the TipTip plugin works for other input types in the
    same form.
    Issue:
  • Despite the above efforts, the tooltip does not appear when focusing
    on the multi-select element. The same setup works fine with text
    inputs and other elements.

Question:

  • How can I make TipTip work with multi-select elements? Is there any
    workaround or additional configuration required for TipTip to support
    multi-select elements?

Why do the coordinates seem different

when hovering, the block animates and rises up, but RigidBody is a little late
synchronization occurs in each frame
it seems that the animation takes the origin of coordinates from the coordinates of RigidBody
how can this be fixed

enter image description here
enter image description here

 function BoxObject({count}) {
        const meshRef = useRef();
        const rigidBodyRef: MutableRefObject<RapierRigidBody> = useRef();   
    
        const [isHovered, setHovered] = React.useState(false);
        const props = useSpring<MeshProps>({
            position: isHovered ? [2, 2, 0] : [2, 1, 0]
        });
    
        const updateRigidBody = useCallback(() => {
            if (!meshRef.current || !rigidBodyRef.current) {
                return;
            }
            if (!isHovered) {
                return;
            }
            const {position, rotation} = meshRef.current;
            rigidBodyRef.current.setTranslation(position, false);
            // rigidBodyRef.current.setRotation(rotation, true);
        }, [isHovered]);
    
        useFrame(() => {
            updateRigidBody();
        })
    
        return <group position={[2, 1, 0]}>
            {new Array(count).fill(0).map((k, i) =>
                <a.mesh
                    {...props}
                    ref={meshRef}
                    key={`box${i}`}
                    onPointerOver={() => setHovered(true)}
                    onPointerOut={() => setHovered(false)}
                >
                    <RigidBody
                        ref={rigidBodyRef}
                        name={`box${i}`}>
                        <Block/>
                    </RigidBody>
                </a.mesh>
            )}
        </group>
    }

Uncaught (in promise) TypeError: – website loads the data but error message in console

i am trying to build a simple website, fetching data from github.
I have two datasets here.
The currentAPI is loaded correctly, while the other one throws error message “Uncaught (in promise) TypeError: album is not defined”, nevertheless the website loads the data!

    I have an async function:
    
            async function getData() {
            
            
              const previousPromise=fetch('https://raw.githubusercontent.com/balintov/matchmaker/refs/heads/main/previousPicturesAPI');
              const currentPromise=fetch('https://raw.githubusercontent.com/balintov/matchmaker/refs/heads/main/currentPicturesAPI');
              const responses = await Promise.all([previousPromise, currentPromise]);
              const dataPromises = responses.map(r => r.json());
              const [previous, current] = await Promise.all(dataPromises);
          for (var props in previous) {
            document.getElementById('main').innerHTML+= `<div class="previousTitle"><h2> Korábbi részek </h2><p>${previous[props].series} évad</p></div>`
            for (var episodes in previous[props]) {
              for (var episode in previous[props][episodes]) {
        
                //THIS CONSOLE MESSAGE RETRIVES THE DATA
                console.log(previous[props][episodes][episode].album.photolink);
        
                var episodeProp= previous[props][episodes][episode];
                document.getElementById('main').innerHTML+= `<div class="episode-container">
                <div class="episode-head">

/* HERE THE DATA WORKS, DOES NOT THROW MESSAGE */
                <h2>${episodeProp.episode_date}</h2>
                <p><a href=${episodeProp.episode} target="_blank">Hallgatom az epizódot!</a></p>
                </div>
                <div class="match-container">
                <div class="album-container">
                <div class="content-container">
                <h3>Album</h3>
    /* FROM HERE THROWS THE ERROR MESSAGE */
                <img src="${episodeProp.album.photolink}" alt="${episodeProp.album.description}" width="350" height="450" class="image">
                <p>${episodeProp.album.song}</p><p><a href="${episodeProp.album.spotifylink}" target="_blank">Hallgatom ▶️</a></p>
                </div>
                </div>
                <div class="picture-container">
                <div class="content-container">
                <h3>Kép</h3>
                <img src="${episodeProp.picture.photolink}" alt="${episodeProp.picture.description}" width="350" height="450" class="image">
                <p>${episodeProp.picture.description}</p>
                </div>
                </div>
                </div>
                </div>`
              }
            }
          }
        
        
        }
        
        getData();

I put the data set in JSON validator, I put the JS file into JS validator.
As I mentioned in the code comment, before the template literal string the data is not undefined.
Also in the template literal some data work perfectly.

The exact error message is: “Uncaught (in promise) TypeError: episodeProp.album is undefined”

I really do not understand what the problem is, could someone give a clue?

IN Google Apps Script How to get current active/triggered trigger ID ,

I have build an Sheets Add-on Which performs a task based on trigger setup by user
So the problem is that User sets triggers for multiple sheets e.g Sync

the trigger is executed but only for 1st trigger in the list of triggers not all

The PROBLEM IS only one trigger is being triggered for all of the setup triggers

Logs for one trigger & the same logs comes for all triggers

Active Trigger: -5962537404932988746 for function: fetchSynctriggerWithDetails
Active Trigger: -9139074510508922527 for function: fetchSynctriggerWithDetails
Active Trigger: -1495623190131824397 for function: fetchSynctriggerWithDetails
Active Trigger: -1224866675796805716 for function: fetchSynctriggerWithDetails
Active Trigger: 1983234386806141271 for function: fetchSynctriggerWithDetails
Active Trigger: -8082155554848723508 for function: fetchSynctriggerWithDetails

Response: {"success":true,"triggerDetails":{"trigger_id":"-5962537404932988746","sheet_name":"SKU","databaseid":"1","trigger_time":"1hour"}}

so the problem is it has all the triggers but it always run for

Response: {“success”:true,”triggerDetails”:{“trigger_id”:”-5962537404932988746″,”sheet_name”:”SKU”,”databaseid”:”1″,”trigger_time”:”1hour”}}

Because it can;t find
var triggerId = currentTrigger.getUniqueId();
for each trigger
& each time it returns -5962537404932988746 as current trigger ID

which is wrong

ANY HELP IS APPRECIATED


function createSyncTrigger() {

/// all the setup for setting up trigger 

// I am also saving trigger in PropertiesService

PropertiesService.getScriptProperties().setProperty(triggerId, JSON.stringify(triggerDetails));

}


Code snippet to fetch trigger details


function getTriggerDetailsSync() {
  var triggers = ScriptApp.getProjectTriggers();
   // Log all active triggers for debugging
  triggers.forEach(trigger => {
    Logger.log('Active Trigger: ' + trigger.getUniqueId() + ' for function: ' + trigger.getHandlerFunction());
  });

   //var currentTrigger = triggers.find(trigger => trigger.getHandlerFunction() === 'fetchSynctriggerWithDetails');

 // Get the current trigger that invoked this function
  var currentTrigger = ScriptApp.getProjectTriggers().find(trigger => 
    trigger.getHandlerFunction() === 'fetchSynctriggerWithDetails'
  );

  if (!currentTrigger) {
    Logger.log('No trigger found for fetchSynctriggerWithDetails');
    return null;
  }

  var triggerId = currentTrigger.getUniqueId();

}

Angular 17: localStorage is not defined Error After Saving Changes and Browser Stuck in Reloading State

When i run project in angular 17 it runs successfully. However when i made some changes in code and save changes then:

The browser page stucks in a reloading state

Also this error shown up:

Error during ngOnInit: ReferenceError: localStorage is not defined

Here is my ngOnInit code block:

async ngOnInit() {
    try {
      await this.fetchUsers();
  
      this.chatService.fetchMessages();
      this.chatService.messages.subscribe((messages) => {
        this.messages = messages;
      });
  
      const users = this.authService.getUsers();
      const { username, id } = this.authService.getUserNameFromToken() || {};
      this.name = username ?? '';
      console.log("Display token name:", this.name);
      let token = localStorage.getItem('authToken');
      console.log("Token: ",token);
      this.id = id ?? '';
    } catch (error) {
      console.error("Error during ngOnInit:", error);
    }

  }
```[![Here is image of browser page which stucks in loading state when i made changes in code and save them][1]][1]


  [1]: https://i.sstatic.net/4jvdngLj.png

FormData Not Appending Files in React

I’m working on a React component that allows users to upload files. The files are managed in a state array where each file has additional metadata such as a unique id (required for DataGrid) and a docType field (e.g., INVOICE).

Here’s the state definition:

export interface EnrichedFile {
  id: string; // Unique ID for each file (required for DataGrid)
  docType: string; // A description of the file, e.g., INVOICE
  file: File; // The actual file object
}

const [selectedFiles, setSelectedFiles] = useState<EnrichedFile[]>([]);

Component Code:

Below is the relevant portion of my component where users can drag-and-drop or browse files to upload:

return (
  <Box component="div" className="w-96 overflow-hidden">
     .....
  </Box>
    {selectedFiles.length !== 0 && (
      <Animated className="w-full mt-4 h-48" animationIn="fadeInUp" animationOut="fadeOut" isVisible={true}>
        <ExDataGrid
          processRowUpdate={updateRowHandler}
          disableColumnMenu
          disableColumnFilter
          disableDensitySelector
          columnHeaderHeight={36}
          slots={{
            footer: () => (
              <div className="flex justify-center">
                <LoadingButton onClick={uploadHandler} variant="contained" color="primary" loading={isPending}>
                  Upload
                </LoadingButton>
              </div>
            ),
          }}
          columns={columnsDocumentsUpload(deleteFileUpload)}
          rows={selectedFiles}
        />
      </Animated>
    )}
  </Box>
);

Upload Process:

When I click the Upload button, I create a FormData object and attempt to append the files and metadata before sending it to the server via Axios. However, the FormData appears to be empty when inspected.

Here is my uploadHandler function:

const uploadHandler = useCallback(async () => {
  // Validate that all files have a docType
  const hasError = selectedFiles.some(file => file.docType.trim() === '');
  if (hasError) {
    return toast.error('Please select a document type for all files');
  }

  // Create FormData object
  const formData = new FormData();
  selectedFiles.forEach(file => {
    if (file.file instanceof File) {
      formData.append('files', file.file); // Append the actual file
      formData.append('metadata', JSON.stringify({ id: file.id, docType: file.docType })); // Include metadata for each file
    } else {
      console.error("Invalid file object:", file.file);
    }
  });

  // Debugging: Log FormData entries
  for (const [key, value] of formData.entries()) {
    console.log(`${key}:`, value);
  }

  mutate(formData);
}, [selectedFiles, mutate]);

Expected Behavior:

The FormData object should include the appended files (files) and metadata (id, docType) and send them to the server.

Questions:

  1. Why is the FormData object empty even though selectedFiles contains valid File objects?
  2. Am I appending files to FormData incorrectly?

Node.js v22.12 Ends Immediately Without Any Output When Running a File on Windows

I recently upgraded Node.js on my Windows machine to version v22.12, and now any script I run from a file exits immediately without displaying any output. For example:

> node test.js
# (no output, program finishes instantly)

Here is a minimal example of test.js (though the content seems irrelevant; even a single console.log() fails to produce output):

console.log("Hello from Node.js");
setInterval(() => {
  console.log("Still running...");
}, 2000);

Key observations:

  1. If I run the same code inline using -e, it does work:
    node -e "console.log('Hello from inline'); setInterval(() => {console.log('Still running inline...');}, 3000)"
    
  2. If I downgrade Node.js to v20.18, the file-based execution works as expected, producing output as normal.
  3. Before upgrading to 22.12, everything worked correctly on the same machine.
  4. After reverting to 20.18, it started working again without changing any other settings.

Question:

  • Was there a change in Node.js v22.12 that affects how scripts should be started on Windows?
  • Or could there be a specific configuration or security policy on my Windows PC that might cause this behavior?
  • Has anyone else encountered this issue or found a workaround?

For now, I’m okay staying on v20.18 since it resolves the problem, but I’d prefer to upgrade if there’s a known fix or setting adjustment. Any insights would be much appreciated!

How can I add a console.log statement to a JavaScript file on a live website?

I want to see print something in console so I can see the values, its a live website that I dont have control, its not mine.

Here is what I did.

  1. Went to SOURCES tab
  2. opened that Javascript file
  3. put console.log()
  4. clicked CTRL+S
  5. Then without re-freshing website, I clicked on that particular
    button on website, AJAX was sent, but no message in console

NOTE: that orange icone you see? it says “changes to this file were not saved to file system”

PS: I know I can see in XHR request payload but thats not I want, that is different data, I want see data at that specific point.

enter image description here

Java OpenCv to Maven

Is there any way to get OpenCV from repository? Which artifact should I add to pom.xml? Every tutorial I’d found is from ’14 and it seems like something changed – they say it is’nt in official Maven repository yet, but I’ve found entry:

when I’m using System.loadLibrary(Core.NATIVE_LIBRARY_NAME). Can I add this library in a way that would make my project include it and ‘forget’ about manually adding it to classpath?

How to prevent downloading the desktop component code in Next.js when using dynamic imports based on user-agent?

I’m trying to create a layout in Next.js where the component rendered depends on the device (mobile or desktop). I want to prevent the desktop layout’s source code from being downloaded to the browser if the user is on a mobile device. Here’s what I have:



"use server";

import React, {ReactNode, ComponentType} from "react";

import {parseUserAgent} from "@repo/helpers";
import dynamic from "next/dynamic";
import {headers} from "next/headers";

interface Props {
  CommonWrapper?: ComponentType<{children: ReactNode}>;
  MobileComponent: () => Promise<{default: React.ComponentType<any>}>;
  DesktopComponent: () => Promise<{default: React.ComponentType<any>}>;
}

const withResponsiveLayout = async ({
  CommonWrapper,
  MobileComponent,
  DesktopComponent,
}: Props) => {
  const header = new Headers(headers());
  const parsedUserAgent = parseUserAgent(header);
  let isMobile = parsedUserAgent?.device.is("mobile");

  const Wrapper = CommonWrapper ?? React.Fragment;
  const Component = isMobile
    ? dynamic(MobileComponent)
    : dynamic(DesktopComponent);

  return (
    <Wrapper>
      <Component />
    </Wrapper>
  );
};

export default withResponsiveLayout;



// example

'use server'

async function Page() {
  const data = await getSomeData();

  return await withResponsiveLayout({
    CommonWrapper: ({children}: PropsWithChildren) => (
      <MandatoryAuthWrapper>
        <CommonProvier initialData={data}>{children}</CommonProvier>
      </MandatoryAuthWrapper>
    ),
    DesktopComponent: () => import("./Main"),
    MobileComponent: () => import("./MobMain"),
  });
}


I’m trying to render either a mobile or desktop layout based on the user-agent, and I want to ensure that the desktop layout never gets downloaded by the browser if the user is on a mobile device. I don’t want to make the layout responsive but rather load an entirely different layout based on the device.

Am I doing something wrong in my approach? How can I ensure the desktop component is excluded from the client-side bundle entirely when the user is on a mobile device?