How can I solve the JS code problem to make my simple project better than before?

I have made an analog and digital clock project for front-end development practice. The digital clock is running correctly, but the analog clock is not working correctly. The analog clock’s minute and hour hands rotate smoothly but those two hands are jumping ahead and resetting back to the correct positions in respected seconds and minutes intervals.

Before this issue occurred I had faced another one where the minute and hour hands were not in the correct positions. After solving it the minute and hour hands both jump one minute and one hour ahead respectively (one minute more and one hour more) when the 60-second interval is completed the minute hand smoothly rotates one minute ahead but in the exact 60 seconds, it jumps one more minute ahead. In the same way, when the 60 minutes interval is done the hour hand behaves in the same way. Again the minute and hour hands reset to the correct position after 15 seconds and 15 minutes respectively.
Here are the code snippet.

const hourHand = document.getElementById('hour');
const minuteHand = document.getElementById('minute');
const secondHand = document.getElementById('second');
const digitalClock = document.getElementById('digital-clock');

// Offset variables (to correct the delay)
const offsetHours = 3; // Analog clock is 3 hours ahead
const offsetMinutes = 15; // Analog clock is 15 minutes ahead
const offsetSeconds = 15; // Analog clock is 15 seconds ahead

function updateClock() {
  const now = new Date();

  // Adjust Bangladesh time for both clocks
  const localOffset = now.getTimezoneOffset() * 60 * 1000; // Local offset in milliseconds
  const bangladeshOffset = 6 * 60 * 60 * 1000; // Bangladesh offset in milliseconds (GMT+6)
  const bangladeshTime = new Date(now.getTime() + localOffset + bangladeshOffset);

  // Get digital time components
  const digitalHours = bangladeshTime.getHours();
  const digitalMinutes = bangladeshTime.getMinutes();
  const digitalSeconds = bangladeshTime.getSeconds();

  // Adjust analog clock by subtracting the offset
  const correctedHours = (digitalHours - offsetHours + 24) % 24; // Ensure valid 24-hour format
  const correctedMinutes = (digitalMinutes - offsetMinutes + 60) % 60; // Ensure valid 60 minutes
  const correctedSeconds = (digitalSeconds - offsetSeconds + 60) % 60; // Ensure valid 60 seconds

  // Calculate degrees for the analog clock hands
  const hourDeg = (360 / 12) * (correctedHours % 12) + (30 / 60) * correctedMinutes;
  const minuteDeg = (360 / 60) * correctedMinutes + (6 / 60) * correctedSeconds;
  const secondDeg = (360 / 60) * correctedSeconds;

  // Apply rotation to analog clock hands
  hourHand.style.transform = `rotate(${hourDeg}deg)`;
  minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
  secondHand.style.transform = `rotate(${secondDeg}deg)`;

  // Update the digital clock display
  const formattedHours = digitalHours < 10 ? `0${digitalHours}` : digitalHours;
  const formattedMinutes = digitalMinutes < 10 ? `0${digitalMinutes}` : digitalMinutes;
  const formattedSeconds = digitalSeconds < 10 ? `0${digitalSeconds}` : digitalSeconds;
  const amPm = digitalHours >= 12 ? 'PM' : 'AM';

  digitalClock.textContent = `${formattedHours % 12 || 12}:${formattedMinutes}:${formattedSeconds} ${amPm}`;
}

// Update the clock every 1000ms (1 second)
setInterval(updateClock, 1000);

// Initialize the clock immediately
updateClock();
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: linear-gradient(to bottom, #f4f4f4, #ccc);
  font-family: 'Arial', sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.clock {
  position: relative;
  width: 350px;
  height: 350px;
  border: 8px solid black;
  border-radius: 50%;
  background: white;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

.center {
  position: absolute;
  width: 12px;
  height: 12px;
  background: black;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.hand {
  position: absolute;
  width: 50%;
  height: 6px;
  background: black;
  top: 50%;
  left: 50%;
  transform-origin: 0%;
  /* Ensure the hand rotates from the center */
  transform: translate(-50%, -50%);
  transition: transform 0.05s ease-in-out;
}

.hand {
  position: absolute;
  width: 50%;
  height: 6px;
  background: black;
  top: 50%;
  left: 50%;
  transform-origin: 0% 50%;
  /* Rotates around the base of the hand */
  transform: translate(-50%, -50%);
  transition: transform 0.05s ease-in-out;
}

.hour {
  width: 25%;
  height: 6px;
  background: black;
}

.minute {
  width: 40%;
  height: 4px;
  background: black;
}

.second {
  background: red;
  height: 2px;
}

.numbers {
  position: absolute;
  width: 100%;
  height: 100%;
}

.number {
  position: absolute;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  font-size: 1.2em;
  font-weight: bold;
  color: black;
  transform-origin: center;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(calc(var(--i) * 30deg)) translateY(-140px);
}

.number:after {
  content: attr(data-number);
  display: block;
  transform: rotate(calc(var(--i) * -30deg));
}

.digital-clock {
  margin-top: 20px;
  font-size: 2em;
  font-weight: bold;
  color: black;
  text-align: center;
  background: white;
  padding: 10px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
<div class="container">
  <!-- Analog Clock -->
  <div class="clock">
    <div class="numbers">
      <div class="number" style="--i: 1;" data-number="1"></div>
      <div class="number" style="--i: 2;" data-number="2"></div>
      <div class="number" style="--i: 3;" data-number="3"></div>
      <div class="number" style="--i: 4;" data-number="4"></div>
      <div class="number" style="--i: 5;" data-number="5"></div>
      <div class="number" style="--i: 6;" data-number="6"></div>
      <div class="number" style="--i: 7;" data-number="7"></div>
      <div class="number" style="--i: 8;" data-number="8"></div>
      <div class="number" style="--i: 9;" data-number="9"></div>
      <div class="number" style="--i: 10;" data-number="10"></div>
      <div class="number" style="--i: 11;" data-number="11"></div>
      <div class="number" style="--i: 12;" data-number="12"></div>
    </div>
    <div class="hand hour" id="hour"></div>
    <div class="hand minute" id="minute"></div>
    <div class="hand second" id="second"></div>
    <div class="center"></div>
  </div>
  <!-- Digital Clock -->
  <div class="digital-clock" id="digital-clock">
    00:00:00 AM
  </div>
</div>

Why an array don’t be considered as an array in my $.ajax function [closed]

I am facing a problem when trying to print key values of objects which stored
in an array that itself a response from a url api when calling by $.ajax function.

Simply the problem array don’t be considered as an array but just normal variable.

My $.ajax function code

      $.ajax({
      url:'get_rooms_classes.php',
      type:'post',
      data:{Classnum:Classnum},

      datatype:'json',

      success:function(  response )
      {
      console.log(response)
      for (var  i=0;i<response.length;i++)
      {
      Room_Name = response[i] ;
      console.log(Room_Name)
      } 

This is the array response.

[{"Room_Id":"1","Room_Name":"java"},{"Room_Id":"1","Room_Name":"java"},{"Room_Id":"1","Room_Name":"java"},{"Room_Id":"1","Room_Name":"java"},{"Room_Id":"1","Room_Name":"java"},{"Room_Id":"3","Room_Name":"php"},{"Room_Id":"3","Room_Name":"php"},{"Room_Id":"3","Room_Name":"php"},{"Room_Id":"3","Room_Name":"php"},{"Room_Id":"3","Room_Name":"php"}]

The output from looping through the array as following

[ 
{ 
" 
R 
o   
m 
_ 
I 
d 
... etc

While I looping through it as standalone javascript code it works perfectly.

for(var i =0;i<response.length;i++)
{
alert(response[i]['Room_Name']);
}

I hope someone helps me to know what is the problem with jquery ajax function.

Angular 19: ‘imports’ is only valid on a component that is standalone

I am migrating my angular library from v18 to v19.

Before upgrade components looked like following:


@Component({
    selector: "custom-component",
    templateUrl: "./custom.component.html",
    styleUrls: ["./custom.component.scss"],
    standalone: true,
    imports: [
        MatIconModule,
        CommonModule,
        ... other imports
    ],

Since after upgrade standalone: true is removed in migration process referred here in official Angular Docs.

Now after upgrade I am getting error:

'imports' is only valid on a component that is standalone.(-992010)

my component after automatic upgrade looks like this:


@Component({
    selector: "custom-component",
    templateUrl: "./custom.component.html",
    styleUrls: ["./custom.component.scss"],
    imports: [
        MatIconModule,
        CommonModule,
        ... other imports
    ],

Any help is appreciated.

I have updated angular-language-service and also restarted vs-code but nothing helped.

CORS Issue with YouTube API During Resumable Upload

I’m working on a resumable video upload feature to YouTube using their API, and I’m encountering a specific problem with CORS (Cross-Origin Resource Sharing).
Context:

Frontend: My frontend is written in JavaScript (using the Fetch API) and initializes the uploads.
Backend: My backend (Symfony) generates the resumable upload URL by calling the YouTube API and returns this URL to the frontend.
Upload: The frontend uses this URL to upload chunks directly to YouTube. Everything works perfectly until about 96% of the upload is completed.

Problem:

During the last chunk (around 96% progress), I receive a CORS-related error:

The response body is not accessible to scripts (reason: CORS Missing Allow Origin).

This seems to indicate that the YouTube API is not returning the expected Access-Control-Allow-Origin headers.
Observations:

When I handle everything on the frontend (initializing the upload and sending chunks), it works perfectly until the end.

When I use the URL generated by my backend, the issue arises only during the last request (finalizing the upload).

Note: I chose to handle the upload on the frontend to avoid overloading my server with potentially large files.
Suggestions Needed:

Do you have any suggestions to work around or resolve this issue, please?
Another Small Question:

The YouTube API allows only 10,000 quota units per day, but video uploads consume 1,600 units each. This quickly becomes a bottleneck during development, as I don’t have much room to test.

Do you know of any solutions to test uploads without consuming units, if possible?

Problem:

During the last chunk (around 96% progress), I receive a CORS-related error:

The response body is not accessible to scripts (reason: CORS Missing Allow Origin).

This seems to indicate that the YouTube API is not returning the expected Access-Control-Allow-Origin headers.
Observations:

When I handle everything on the frontend (initializing the upload and sending chunks), it works perfectly until the end.

When I use the URL generated by my backend, the issue arises only during the last request (finalizing the upload).

execute something on resolve and reject of a promise

I am trying to implement a Promise for the first time. The code I have here works meaning that when beforeRemoveTag is triggered I see the confirm expected and if I hit ‘OK’ it resolves the promise while with ‘Cancel’ it reject the promise. So far so good.

new Tagify(input,{
    hooks:{
        beforeRemoveTag: tags => {
            //tags[0].node.classList.add('tagify__tag--loading');
            return new Promise((resolve, reject) => {
                confirm(`Remove ${tags[0].data.value} ?`) ? resolve() : reject()
            })
        }
    }
});

Now I’d like to add an alert when the promise is resolved and another when the promise is rejected.
So as a pseudocode:

new Tagify(input,{
    hooks:{
        beforeRemoveTag: tags => {
            //tags[0].node.classList.add('tagify__tag--loading');
            return new Promise((resolve, reject) => {
                confirm(`Remove ${tags[0].data.value} ?`) ? resolve(alert('Removed!') : reject(alert('not removed!')
            })
        }
    }
});

How to do it?

Alpinejs xtext performance in magento project

I’m new to working on a Magento project with Hyvä Theme and Alpine.js.

On the product page, I have a JSON containing product models that I’ll receive from Typesense. My plan is to use PHP for the initial rendering (prioritizing SEO) and Alpine.js to manage HTML updates dynamically when selecting a different model using a selector.

I’m considering using x-text to bind the JavaScript object to the necessary html tags, and updating the variable holding this object when the selector changes. Could this approach cause any issues with SEO or performance? Would it be better to manage the updates using a function that modifies the necessary HTML elements with .innerHTML instead of x-text?

Here’s a small example of what I’m trying to do:

> $products = json_decode(json with models);
>  $defaultProduct = $products[0];
>  <div x-data="initProductPage()">
>          <select id="model-selector" @change="updateModel($event)" >
>           <option value="Model1">Model1</option>
>           <option value="Model2">Model2</option>
>          </select>
>         <h1 id="example" class="flex" x-text="currentProduct?.name"><?= $escaper->escapeHtml(__($defaultProduct['name']))?></h1>
>  </div>
>  <script>
function initProductPage() {
products: <?= json_encode($products) ?>,
currentProduct: <?= json_encode($defaultProduct) ?>,
updateModel(event) {
this.currentProduct = this.products.find(product => product.model === event.target.value);
other option
document.getElementById("example").innerText = this.currentProduct.name;
>                 }
>       }
>  </script>

Thank you all!

Clicking is not working on whole of model in Mapbox, using Threebox to render the models

I have a map using mapbox, I am rendering GLTF models using Threebox.
I have a click event on the map, which then using raycasting to check if a model is being clicked.
The problem I have is that the whole model isn’t clickable, for example only half is, especially while zoomed out.

Here’s how I initialise a model:

            const options = {
                obj: '/scene.gltf',
                type: 'gltf',
                units: 'scene',
                anchor: 'center',
            };

            return new Promise<void>((resolve) => {
                tb.loadObj(options, (model: any) => {
                    const carModel = model.setCoords(coords);

                    const boundingBoxHelper = new THREE.BoxHelper(carModel, 0xff0000);
                    tb.add(boundingBoxHelper);

                    tb.add(carModel);
                    this.models.push(carModel);
                    resolve();
                });
            });

And here’s my onClick on the map:

clickFunc(event: mapboxgl.MapMouseEvent) {
        const tb = (window as any).tb;
        const camera = tb.camera;
        const scene = tb.scene;

        const mouse = new THREE.Vector2();
        const rect = this.getCanvas().getBoundingClientRect();
        mouse.x = ((event.point.x - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.point.y - rect.top) / rect.height) * 2 + 1;

        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(mouse, camera);

        let clickedObject = null;
        let intersectionPoint: THREE.Vector3 | null = null;

        scene.traverse((child) => {
            if (child.isMesh) {
                if (!child.geometry.boundingBox) {
                    child.geometry.computeBoundingBox();
                }

                const boundingBox = child.geometry.boundingBox.clone();
                boundingBox.applyMatrix4(child.matrixWorld); // Apply object's transformations

                if (raycaster.ray.intersectsBox(boundingBox)) {
                    console.log('Ray intersects bounding box');

                    intersectionPoint = new THREE.Vector3();
                    raycaster.ray.intersectBox(boundingBox, intersectionPoint);

                    clickedObject = child;
                }
            }
        });

        if (clickedObject) {
            console.log('Clicked object:', clickedObject);
        } else {
            console.log('No objects intersected.');
        }
    }

I want my whole bounding box to be clickable, but it seems to only be clickable from certain angles/zooms..

enter image description here

Here’s a view from the top of the area thats clickable, when I zoom in the problem disappears but when I zoom out it gets worse.

Someone pls help me

Playwright giving error ‘Cant locate this in playwright’

I am getting the error:

await page.locator(‘.MuiGrid-root.MuiGrid-item.MuiGrid-grid-xs-12.MuiGrid-grid-md-3.css-87nszj’).nth(1).click(); Can’t locate this in palywright-JS

When I start to headed test it just stuck on this. But while running a test when I click on this the test passed. I tried various locators but all ends up in error.

import { test } from '@playwright/test';

test("Kayana Eats Order", async ({ page }) => {
  await page.goto('https://kayanaeats.com');  
  await page.locator('#location_autocomplete').click();
  await page.locator('#location_autocomplete').fill('WIJ Hertford');
  await page.locator('#location_autocomplete-option-0').click();
  await page.locator('.MuiGrid-root.MuiGrid-item.MuiGrid-grid-xs-12.MuiGrid-grid-md-3.css-87nszj').nth(1).click();
  await page.locator('img[alt="Munch Box"]').click();
});

Cloud Function in Firebase to check the age of users

I am writing an app in Flutter with a Firebase Backend. My App needs to check if a user turnt 18, and if they did it should make their attribute “hasAgreedToTerms” to false because I want them to re-agree to the Terms and Conditions after they turn 18. I have looked around online and asked ChatGPT and it seems like I need to add a Cloud Function to Firebase that checks their age. I have tried implementing a function but I do not have any experience with JS, therefore I have trouble writing the function. Additionally, when I try to deploy my function, an error occurs.

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.checkUserAgeAndUpdateTerms = functions.firestore
    .document("users/{userId}")
    .onUpdate(async (change, context) => {
      const userId = context.params.userId;
      const newData = change.after.data(); // Get the updated data

      // Check if the birthdate exists
      if (!newData.birthdate) {
        console.log("No birthdate found for user:", userId);
        return null;
      }

      const birthdate = new Date(newData.birthdate);
      const age = calculateAge(birthdate);

      // Check if the user is 18 or older
      if (age >= 18) {
        // Update the 'hasAgreedToTerms' field to false
        await admin.firestore().collection("users").doc(userId).update({
          hasAgreedToTerms: false,
        });
        console.log("User ${userId} turnt 18. Updated hAtT to false.");
      }

      return null;
    });

/**
 * Function
 * @param {Date} birthdate
 * @return {boolean} Description of the return value
 */
function calculateAge(birthdate) {
  const today = new Date();
  let age = today.getFullYear() - birthdate.getFullYear();
  const monthDiff = today.getMonth() - birthdate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 &&
  today.getDate() < birthdate.getDate())) {
    age--;
  }
  return age;
}

I tried updating my firebase-functions version and using 2nd gen cloud functions, but I have no experience and could not write something working.

How to convert snippets of a word file into HTML in the browser using Mammoth (or another library)?

I have the following snippet of a word document (as XML)

<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" w14:paraId="5A36C390" w14:textId="77777777" w:rsidR="00B709F1" w:rsidRDefault="00FE05EA" w:rsidP="00056A13">
  <w:pPr>
    <w:keepNext/>
    <w:tabs>
      <w:tab w:val="left" w:pos="1985"/>
    </w:tabs>
    <w:spacing w:after="330" w:line="220" w:lineRule="auto"/>
    <w:jc w:val="center"/>
  </w:pPr>
  <w:r>
    <w:rPr>
      <w:rFonts w:ascii="Cambria" w:hAnsi="Cambria"/>
      <w:b/>
    </w:rPr>
    <w:t>Proof</w:t>
  </w:r>
</w:p>

I want to use Mammoth to convert this snippet into HTML so that I could render it in the browser.

Here’s the code that I have.

const encoder = new TextEncoder();
const uint8Array = encoder.encode(snippet); // The snippet is available as a string

const doc = await mammoth.convertToHtml({ arrayBuffer: uint8Array.buffer });

However, I run into the following error when I try to use this code

Uncaught (in promise) Error: Can't find end of central directory : is this a zip file ?

Any suggestions on how I can use mammoth to convert this snippet into an HTML?

How to implement a hotel room booking calendar view using Canvas in React? [closed]

I’m trying to create a hotel room booking calendar view in React using Canvas that looks similar to this:

enter image description here

  • I specifically want to use Canvas for better performance with large datasets and smooth scrolling.

    Requirements:
    – Use Canvas for rendering the calendar grid and bookings
    – Show room numbers on the Y-axis
    – Display dates on the X-axis
    – Need to show bookings as colored blocks spanning multiple days
    – Must support showing room categories/types
    – Ability to show room status (occupied, available, maintenance, etc.)
    – Smooth scrolling for large datasets
    – Interactive elements (clicking/hovering on bookings)

useEffect(() => {
  const canvas = canvasRef.current;
  const ctx = canvas.getContext('2d');
  
  // Basic grid drawing
  ctx.beginPath();
  // Draw grid lines
  // Draw room numbers
  // Draw dates
  // Draw bookings
}, []);