When trying to push the result from local am getting uploading test results to azure dev ops: Request failed with status code 404

I have set up a feature file along with its corresponding step definitions. The tests are running successfully, and I am able to generate a test-result.xml file.(Using Playwright + type script with cucumber)

Now, I’m trying to push the test results from my local environment to an Azure DevOps Test Plan that I’ve created (Test Plan ID: 341345 – dummy number).

Here’s what I’ve done so far:

Generated a Personal Access Token (PAT) in Azure DevOps with full permissions.
checked the company and project both are correct

Feature file

@341472 ----(Test case id in azure devops)
  Scenario: @341472 Validate log in the user module
    When End User navigates to user module and checks Subsection presence
    Then End User add a log in release log under user and checks Whether the added data reflects in about module
    And End User deletes the record in log and check the presence in user module

test-result after running the code by “@cucumber/pretty-formatter”

<?xml version="1.0"?>
<testsuite name="Cucumber" time="151.271" tests="1" skipped="0" failures="0" errors="0" timestamp="2025-05-11T14:37:06.272Z">
  <testcase classname="regression in user module" name="@341472 Validate log in the user module" time="136.713">

        <system-out><![CDATA[When End User navigates to user module and checks Subsection presence......................passed
    When End User navigates to user module and checks Subsection presence.............................passed
    Then End User add a log in release log under user and checks Whether the added data reflects in about module......passed
    And End User deletes the record in log and check the presence in user module..passed]]></system-out>
      </testcase>
    </testsuite>

Created a upload-result.js script to upload the test results.

    const fs = require('fs');
const xml2js = require('xml2js');
const axios = require('axios');

const xmlPath = 'test-results.xml'; // Path to your test results XML file
const testPlanId = '341345'; // Dummy number
const suiteId = '341456'; // dummy
const organization ='companyA'; //Dummy company
const project ='ProjectB'; // Dummy project
const pat = process.env.AZURE_DEVOPS_EXT_PAT; // Ensure this is set in your environment

if (!pat) {
  throw new Error('AZURE_DEVOPS_EXT_PAT is not set in environment variables');
}

const apiVersion = '7.1-preview.6';
const baseUrl = `https://dev.azure.com/${organization}/${project}/_apis/test`;

const authHeader = {
  headers: {
    Authorization: `Basic ${Buffer.from(':' + pat).toString('base64')}`,
    'Content-Type': 'application/json'
  }
};

async function parseResults() {
  console.log('Starting to parse the XML file...');
  const xml = fs.readFileSync(xmlPath, 'utf8');
  const result = await xml2js.parseStringPromise(xml);
  console.log('Successfully parsed XML file...');

  const testCases = result.testsuite.testcase;
  if (!testCases) throw new Error('No test cases found in XML');

  return testCases.map(tc => {
    const name = tc.$.name;
    const classname = tc.$.classname;
    const outcome = tc.failure ? 'Failed' : 'Passed';
    const durationInMs = parseFloat(tc.$.time) * 1000;

    // Extract tag like @TC1234 to map to Azure DevOps test case
    const tagMatch = name.match(/@(d+)/);
    const automatedTestName = tagMatch ? tagMatch[1] : null;

    if (!automatedTestName) {
      console.warn(`No @xxxx tag found in "${name}". Test case will be skipped.`);
      return null; // skip test cases without a valid tag
    }

    return {
      automatedTestName: automatedTestName,
      outcome,
      automatedTestType: 'Cucumber',
      durationInMs,
      testCaseTitle: `${classname} - ${name}`
    };
  }).filter(Boolean); // remove any null entries
}
async function uploadToAzureDevOps() {
  console.log('Starting the upload process...');
  const results = await parseResults();

  try {
    const createRunUrl = `${baseUrl}/runs?api-version=${apiVersion}`;
    console.log('Making a POST request to create a test run...');
    console.log('Create Run URL:', createRunUrl);

    const runPayload = {
      name: 'Automated Test Run',
      plan: { id: testPlanId },
      automated: true,
      state: 'InProgress'
    };

    console.log('Payload for creating test run:', JSON.stringify(runPayload, null, 2));

    const runResponse = await axios.post(createRunUrl, runPayload, authHeader);

    if (!runResponse || !runResponse.data || !runResponse.data.id) {
      throw new Error(`No testRunId returned. Response: ${JSON.stringify(runResponse.data)}`);
    }

    const testRunId = runResponse.data.id;
    console.log(`Created test run with ID: ${testRunId}`);

    const resultsUrl = `${baseUrl}/runs/${testRunId}/results?api-version=${apiVersion}`;
    console.log('Uploading test results to:', resultsUrl);

    await axios.post(resultsUrl, results, authHeader);
    console.log('Uploaded test results');

    const completeUrl = `${baseUrl}/runs/${testRunId}?api-version=${apiVersion}`;
    console.log('Marking test run as completed at:', completeUrl);

    await axios.patch(completeUrl, { state: 'Completed' }, authHeader);
    console.log('Marked test run as completed');
  } catch (err) {
    console.error('Error uploading test results:', err.message);
    if (err.response) {
      console.error('Response data:', JSON.stringify(err.response.data, null, 2));
    }
  }
}


// Execute the upload
uploadToAzureDevOps();

However, when I run the command node src/upload-result.js, I encounter an error in console when trying to upload the result.Please note i have added console.log to get the where error is happening so that why any to see the messages

Making a POST request to create a test run...

    Create Run URL: https://dev.azure.com/companyA/ProjectB/_apis/test/runs?api-version=7.1-preview.6
    Payload for creating test run: {
      "name": "Automated Test Run",
      "plan": {
        "id": "341345"
      },
      "automated": true,
      "state": "InProgress"
    }
    Error uploading test results: Request failed with status code 404
    Response data: "Page not found"

Any help is much appreciated .if any additional details are required, please ask away. This is the first time trying this

Componenet has an invalid “default” export: Props Type is not valid

I am using these versions

"next": "14.2.3",
"react": "18.2.0",
"react-dom": "18.2.0"

Now This is the props type of my TimeLine componenet in my NextJS 14 app.Now I am trying to send the id and a setState function in my componenet as the Props in this code.

{
          activeTab === 'Timeline' && (
            id && (
              <TimeLine
              id={id}
              setIsModalNewTaskOpen={setIsModalNewTaskOpen}
            >
            </TimeLine>
            )
          )
        }

This is the whole Component, which is a client component.

"use client";

import { useAppSelector } from "@/app/redux";
import { DisplayOption, Gantt, ViewMode } from "gantt-task-react";
import "gantt-task-react/dist/index.css";
import React, { useMemo, useState } from "react";
import { Project } from "../state/types";
import Header from "../(components)/Header";
import { useGetProjectsQuery } from "../state/api";
import { TimeLineProps } from "../project/types";

type TaskTypeItems = "task" | "milestone" | "project";

const Timeline : React.FC<TimeLineProps> = () => {
  const isDarkMode = useAppSelector((state) => state.global.isDarkModeOn);
  const { data: projects , isLoading, isError } = useGetProjectsQuery();

  const [displayOptions, setDisplayOptions] = useState<DisplayOption>({
    viewMode: ViewMode.Month,
    locale: "en-US",
  });

  const ganttTasks = useMemo(() => {
    console.log(projects)
    return (
      Array.isArray(projects) && projects.length > 0 &&
      projects?.map((project : Project) => ({
        start: new Date(project.startDate as string),
        end: new Date(project.endDate as string),
        name: project.name,
        id: `Project-${project.id}`,
        type: "project" as TaskTypeItems,
        progress: 50,
        isDisabled: false,
      })) || []
    );
  }, [projects]);

  const handleViewModeChange = (
    event: React.ChangeEvent<HTMLSelectElement>,
  ) => {
    setDisplayOptions((prev) => ({
      ...prev,
      viewMode: event.target.value as ViewMode,
    }));
  };

  if (isLoading) return <div>Loading...</div>;
  if (isError || !projects)
    return <div>An error occurred while fetching projects</div>;

  return [
    <div className="max-w-full p-8">
      <header className="mb-4 flex items-center justify-between">
        <Header name="Projects Timeline" />
        <div className="relative inline-block w-64">
          <select
            className="focus:shadow-outline block w-full appearance-none rounded border border-gray-400 bg-white px-4 py-2 pr-8 leading-tight shadow hover:border-gray-500 focus:outline-none dark:border-dark-secondary dark:bg-dark-secondary dark:text-white"
            value={displayOptions.viewMode}
            onChange={handleViewModeChange}
          >
            <option value={ViewMode.Day}>Day</option>
            <option value={ViewMode.Week}>Week</option>
            <option value={ViewMode.Month}>Month</option>
          </select>
        </div>
      </header>

      <div className="overflow-hidden rounded-md bg-white shadow dark:bg-dark-secondary dark:text-white">
        <div className="timeline">
          {
            Array.isArray(ganttTasks) && ganttTasks.length > 0 &&
            <Gantt
            tasks={ganttTasks}
            {...displayOptions}
            columnWidth={displayOptions.viewMode === ViewMode.Month ? 150 : 100}
            listCellWidth="100px"
            projectBackgroundColor={isDarkMode ? "#101214" : "#1f2937"}
            projectProgressColor={isDarkMode ? "#1f2937" : "#aeb8c2"}
            projectProgressSelectedColor={isDarkMode ? "#000" : "#9ba1a6"}
          />
          }
        </div>
      </div>
    </div>
  ]
};

export default Timeline;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>

Now on running this command of npm run build I am getting this error:

Linting and checking validity of types …Failed to compile.src/app/timeline/page.tsx
Type error: Page “src/app/timeline/page.tsx” has an invalid “default” export:
Type “TimeLineProps” is not valid.

What should I lean to start coding [closed]

I have learnt javascript for a long time and still struggling how to become succesfull

What should I tried to learn. I have learnt javascript for a long time and still struggling how to become succesfull

What should I tried to learn I have learnt javascript for a long time and still struggling how to become succesfull

What should I tried to learn

Performance Discrepancy in Image Pixel Comparison Across Browsers Using Canvas

I am using the Canvas NPM library to perform a delta comparison between two images. Both images have the same dimensions (equal width and height). The Method takes two images as base64 string and I am comparing every pixel of the two images. In Chrome and Edge, the loop takes about 20–50ms to execute, whereas in Firefox, it takes approximately 700–800ms. Could this be due to Firefox having slower memory management compared to Chrome and Edge?

async function createDeltaImageFromBase64(currentImageBase64, previousImageBase64) {

    if(currentImageBase64 == null || previousImageBase64 ==null){
        return previousImageBase64;
    }
    // Load images using base64 data URIs
    const currentImage = await loadImage(currentImageBase64);
    const previousImage = await loadImage(previousImageBase64);

    // Ensure the dimensions match
    const width = Math.min(currentImage.width, previousImage.width);
    const height = Math.min(currentImage.height, previousImage.height);

    // Create a canvas for the delta image
    const canvas = createCanvas(width, height);
    const ctx = canvas.getContext('2d');

    // Draw the current image on the canvas
    ctx.drawImage(currentImage, 0, 0, width, height);
    const currentImageData = ctx.getImageData(0, 0, width, height);

    // Draw the previous image on a temporary canvas
    const tempCanvas = createCanvas(width, height);
    const tempCtx = tempCanvas.getContext('2d');
    tempCtx.drawImage(previousImage, 0, 0, width, height);
    const previousImageData = tempCtx.getImageData(0, 0, width, height);

    // Create the delta image
    const deltaImageData = ctx.createImageData(width, height);
    const { data: currentData } = currentImageData;
    const { data: previousData } = previousImageData;
    const { data: deltaData } = deltaImageData;

    for (let i = 0; i < currentData.length; i += 4) {
        // Compare RGBA channels
        const isDifferent =
            currentData[i] !== previousData[i] ||
            currentData[i + 1] !== previousData[i + 1] ||
            currentData[i + 2] !== previousData[i + 2] ||
            currentData[i + 3] !== previousData[i + 3];

        if (isDifferent) {
            // Copy current image pixel
            deltaData[i] = currentData[i];       // Red
            deltaData[i + 1] = currentData[i + 1]; // Green
            deltaData[i + 2] = currentData[i + 2]; // Blue
            deltaData[i + 3] = currentData[i + 3]; // Alpha
        } else {
            // Set to transparent
            deltaData[i] = 0;
            deltaData[i + 1] = 0;
            deltaData[i + 2] = 0;
            deltaData[i + 3] = 0;
        }
    }

    // Put the delta image data back on the canvas
    ctx.putImageData(deltaImageData, 0, 0);

    // Return the delta image as a base64 string
    return canvas.toDataURL(); // Returns a base64 data URI
}

How to select the currently active / most recently focused video on a page with multiple videos?

On a page with multiple videos the currently active / most recently focused video reacts to standard keyboard actions like Space to play/pause the video or F to toggle full screen mode. This is already the case after initially selecting/clicking the respective video. But how to select this video to be able to perform custom keyboard actions like S to access the settings?

I tried an click event listener on the document body taking advantage of event delegation to select the closest video wrapper along with its containing video element. This, of course, only works if the video is clicked with the mouse and not if it is selected with the keyboard. But most importantly, it only works after the second click, because the first one apprently only activates the video in the first place.

So how does the browser do this and how can I mimic this behavior?

Understanding Javascript [closed]

I could really use some helpright now. I’m currently learning JavaScript . I started from HTML and CSS, and now I’m working my way through JS. Honestly, I spend over 4 hours a day studying, but it still feels overwhelming. I’m wondering will I ever truly get it? Is there a better way or technique to learn JavaScript effectively?

HTML5 Twitching Audio Progress Bar in Safari/Orion, Smooth in Chrome/Firefox

Problem Description:

About half a second after audio playback starts (in Safari and Orion), the progress bar “twitches”, jumping back towards the start momentarily before continuing to progress. The audio itself plays fine.

Below is a stripped down reproduction of the issue:

<head>
    <title>Audio Progress Twitch Test</title>
    <style>
        /* Basic body for display */
        body {
            font-family: sans-serif;
            padding: 20px;
        }

        /* Paragraph Container - simplified */
        .paragraph-group {
            padding: 10px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            position: relative;
        }

        /* Audio Controls - simplified positioning */
        .audio-controls {
            position: absolute;
            right: 10px;
            top: 15px;
        }

        /* Play Button - basic styling */
        .play-btn {
            width: 32px;
            height: 32px;
            border: 1px solid #aaa;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f0f0f0;
        }
        .play-btn.playing {
            /* Simple visual feedback for playing state */
            background-color: #ccf2ff;
        }

        /* Progress Bar - core styles */
        .progress-container {
            margin-top: 10px;
            height: 12px;
            cursor: pointer;
            background-color: #eee; /* Background for the container */
        }

        .progress-bar {
            /* This is the track */
            height: 4px;
            width: 100%;
            background: #d0d0d0;
            border-radius: 2px;
            position: relative; /* For the indicator */
            margin-top: 4px; /* To center it a bit in the 12px container */
        }

        .progress-indicator {
            /* This is the moving part */
            position: absolute;
            height: 100%;
            width: 0%; /* Initial state */
            background: #007bff;
            border-radius: 2px;
            transition: none !important; /* Explicitly disable CSS transitions */
        }
    </style>
</head>
<body>
    <div class="paragraph-group" data-audio="sample.m4a">
        <!-- Replace with your audio file -->
        <p>Sample Audio Track</p>
        <div class="audio-controls">
            <button class="play-btn">▶</button>
        </div>
        <div class="progress-container">
            <div class="progress-bar">
                <div class="progress-indicator"></div>
            </div>
        </div>
    </div>

    <script>
        let currentAudio = null;
        let currentParagraph = null; // The div containing the current audio
        let isPlaying = false;
        const audioElements = {};

        // Web Audio API setup (as in the original, potentially relevant)
        const audioContext = new (window.AudioContext ||
            window.webkitAudioContext)();

        // Initialize audio elements
        document
            .querySelectorAll(".paragraph-group")
            .forEach((paraGroupDiv) => {
                const audioSrc = paraGroupDiv.getAttribute("data-audio");
                if (audioSrc) {
                    const audio = new Audio(audioSrc);
                    audioElements[audioSrc] = audio;

                    // Connect to Web Audio API
                    try {
                        const source =
                            audioContext.createMediaElementSource(audio);
                        source.connect(audioContext.destination);
                    } catch (e) {
                        console.error("Error creating MediaElementSource: ", e);
                    }
                }
            });

        // Play button event listener
        document.querySelectorAll(".play-btn").forEach((btn) => {
            btn.addEventListener("click", function () {
                if (audioContext.state === "suspended") {
                    audioContext
                        .resume()
                        .catch((e) =>
                            console.error("AudioContext resume error:", e)
                        );
                }

                const paragraphDiv = this.closest(".paragraph-group");
                const audioSrc = paragraphDiv.getAttribute("data-audio");
                const audio = audioElements[audioSrc];

                if (!audio) return;

                if (
                    currentAudio &&
                    currentAudio !== audio &&
                    !currentAudio.paused
                ) {
                    currentAudio.pause();
                    if (currentParagraph) {
                        const prevPlayBtn =
                            currentParagraph.querySelector(".play-btn");
                        if (prevPlayBtn) {
                            prevPlayBtn.textContent = "▶";
                            prevPlayBtn.classList.remove("playing");
                        }
                    }
                }

                if (audio.paused) {
                    if (
                        audio.ended ||
                        (audio.duration > 0 &&
                            Math.abs(audio.currentTime - audio.duration) < 0.01)
                    ) {
                        audio.currentTime = 0;
                        const progressIndicator = paragraphDiv.querySelector(
                            ".progress-indicator"
                        );
                        if (progressIndicator) {
                            progressIndicator.style.transition = "none"; // Ensure no transition during reset
                            progressIndicator.style.width = "0%";
                        }
                    }

                    audio
                        .play()
                        .catch((e) => console.error("Audio play error:", e));
                    this.textContent = "⏸";
                    this.classList.add("playing");
                    currentAudio = audio;
                    currentParagraph = paragraphDiv;
                    isPlaying = true;
                    requestAnimationFrame(updateProgress);

                    audio.onended = () => {
                        isPlaying = false;
                        this.textContent = "▶";
                        this.classList.remove("playing");
                        const progressIndicator = paragraphDiv.querySelector(
                            ".progress-indicator"
                        );
                        if (progressIndicator)
                            progressIndicator.style.width = "0%";
                    };
                } else {
                    audio.pause();
                    isPlaying = false;
                    this.textContent = "▶";
                    this.classList.remove("playing");
                }
            });
        });

        // Progress bar seeking
        document
            .querySelectorAll(".progress-container")
            .forEach((container) => {
                container.addEventListener("click", function (e) {
                    const paragraphDiv = this.closest(".paragraph-group");
                    const audioSrc = paragraphDiv.getAttribute("data-audio");
                    // Fallback to currentAudio if the click is on the active player's bar but audio not found by src
                    const audio =
                        audioElements[audioSrc] ||
                        (currentParagraph === paragraphDiv
                            ? currentAudio
                            : null);

                    if (!audio || isNaN(audio.duration) || audio.duration <= 0)
                        return;

                    const rect = this.getBoundingClientRect(); // 'this' is the progress-container
                    const seekPos =
                        Math.min(
                            Math.max(0, e.clientX - rect.left),
                            rect.width
                        ) / rect.width;

                    audio.currentTime = seekPos * audio.duration;

                    const indicator = paragraphDiv.querySelector(
                        ".progress-indicator"
                    );
                    if (indicator) {
                        indicator.style.width = `${seekPos * 100}%`;
                    }
                    // If paused and seek, update immediately but don't start animation loop unless playing
                    if (!isPlaying && currentAudio === audio) {
                        // Manually call updateProgress once to show the new position if paused
                        const safeDuration = audio.duration || 0.1;
                        const progress =
                            (audio.currentTime / safeDuration) * 100;
                        if (indicator) {
                            indicator.style.transition = "none";
                            indicator.style.width = `${Math.min(
                                100,
                                Math.max(0, progress)
                            )}%`;
                        }
                    }
                });
            });

        // updateProgress function
        function updateProgress() {
            if (!isPlaying || !currentAudio || !currentParagraph) {
                return;
            }

            // This line is suspected to be problematic if currentAudio.duration is unstable initially
            const safeDuration = currentAudio.duration || 0.1;
            const progress = (currentAudio.currentTime / safeDuration) * 100;

            const indicator = currentParagraph.querySelector(
                ".progress-indicator"
            );

            if (indicator) {
                indicator.style.transition = "none"; // Reinforce no transitions
                indicator.style.width = `${Math.min(
                    100,
                    Math.max(0, progress)
                )}%`; // Clamp progress
            }

            if (isPlaying) {
                requestAnimationFrame(updateProgress);
            }
        }
    </script>
</body>

So essentially I’m looking for a way to fix this to be smooth and not jumpy for WebKit-based browsers. It works perfectly in firefox and chrome, so that seems to be the source of this debacle. Thank you in advance for any help!

Get the timestamp as unix timestamp (QuestDB)

Right now, when I make a query, I get the time column in this format 2021-06-08T15:45:45.123456Z.

But I need the time as unix timestamp (long – miliseconds).

I have in my mind 2 idea:

  1. Date.parse(time) – in javascript.
  2. SELECT time::long / 1000 – in the query

I don’t know which way is better as performances (I have no idea how to compare).

I query every 250ms with results between 1_000 and 100_000 of rows.

There can be a better way?

P.S.: I use javascript with postgresql to query from questdb

What is the recommended way to access the true first element of a JavaScript array?

Say I have an array initialized like this:

let a = [];
a[1000] = 1;

this will result in an array whose first 1,000 elements are undefined, and the true first element is the 1,001st (index 1,000). If I don’t know how many elements are undefined before the first one, how do I access the true first element?

I can interate through every element in an array and look for the first one that is not undefined, but this will give me O(n) time complexity. I would like to have an O(1) method.

After some messing around I found out I can use the for ... in syntax to do achieve this, and it seems to be O(1), as it seems to be reasonably fast even when the first index is extremely large (1e9):

let index, value;
for(idx in a) {
    index=idx;value=a;
    break;
}

But I have read that it is not recommended to use for ... in for iterating through arrays (as it can mess up other libraries). So what would be the recommended way to achieve what I’m trying to do? is for ... in the only way?

Why does page.name return undefined in InDesign UXP plugin?

I’m developing a UXP plugin for Adobe InDesign and trying to access the name of each page using page.name. However, when I run the following code, page.name consistently returns undefined, even though doc.pages.length is valid and returns the correct number of pages.

Here’s the relevant code snippet:

document.getElementById("collectTextFramesBtn")?.addEventListener("click", async () => {
  try {
    if (!app.documents || app.documents.length === 0) {
      console.warn("⚠️ No document is open.");
      return;
    }

    const doc = app.activeDocument;

    for (let i = 0; i < doc.pages.length; i++) {
      const page = doc.pages[i];
      console.log(`➡️ Iterating page ${i + 1}`);
      console.log("page.name:", page?.name); // returns undefined
      console.log("documentOffset:", page?.documentOffset); // works fine
    }

  } catch (err) {
    console.error("❌ Error accessing page data:", err);
  }
});

What might cause page.name to return undefined even though other properties like documentOffset or textFrames work properly?

I’ve tested on InDesign 19+ with UXP and confirmed that page itself is valid and not null.

Why does Intl.NumberFormat round large numbers differently in Node.js vs browsers?

I’m observing inconsistent rounding behavior with Intl.NumberFormat` between Node.js (v20+) and modern browsers (Chrome/Firefox) for very large numbers.

Example:

const formatter = new Intl.NumberFormat('en-US', {
  maximumFractionDigits: 0
});
console.log(formatter.format(9999999999999999.5)); // Output differs!`

- Browser (Chrome 120+): Returns "10,000,000,000,000,000" (rounds up)
- Node.js (v20): Returns "9,999,999,999,999,999" (rounds down)

What I’ve tried:

Verified the spec (ECMA-402) but found no explicit guidance for this edge case.

Tested with different locales/options – same inconsistency.

Optional parent property in Alpine.js nested scope

In a scoped / nested Alpine.js structure, I need data from an outer x-data in an inner one.

This works:

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js" defer></script>

<div x-data="{ foo: 'hello' }">
  <div x-data="{ get foo() { return foo } }">
    <span x-text="foo"></span>
  </div>
</div>

The property foo exists in the outer scope, so is usable in the inner one.

But in my use case, the outer scope is a page and the inner scope is a separate widget. Sometimes foo exists in the outer scope, sometimes not, and sometimes there is no outer scope.

So this doesn’t work:

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js" defer></script>

<div>
  <div x-data="{ get foo() { return foo || 'world' } }">
    <span x-text="foo"></span>
  </div>
</div>

How do I make foo optional (and provide a default value)?

Please help me with the nestjs schedule

I am using the schedule of nestjs to process the cron so that it works every specific time.

However, even though the cron that was first created for testing has been removed, it continues to go back every 0 o’clock.

the cron that was made for the test is not confirmed even if the entire contents are searched.

The following is the code I wrote.

// app.module.ts

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import ConfigModule from './config';
import { LoggingMiddleware } from './common/middleware/logging.middleware';
import { ScheduleModule } from '@nestjs/schedule';
import { BatchService } from './batch.service';

@Module({
  imports: [
    ConfigModule(),
    ScheduleModule.forRoot(),
  ],
  providers: [BatchService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggingMiddleware).forRoutes('*');
  }
}

Test batch.service.ts was used and deleted only when testing.

// TEST batch.service.ts
 
import { Injectable, Logger } from '@nestjs/common';
import { ClientAuthService } from './routes/client/auth/auth.service';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { PracticeService } from './routes/client/practice/practice.service';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
    private schedulerRegistry: SchedulerRegistry
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

The file below is the actual contents of your current operation.

// REAL batch.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT, {
    name: 'attendance',
  })
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

When viewed from getCronJobs, the following logs are displayed.

[Nest] 646445  - 05/11/2025, 00:00:00 PM LOG job: attendance -> next: Mon May 12 2025 00:00:00

From above, like the relevant log content, only one is searched and two are not. However, in reality, two are running. Seeking help on how to delete previously incorrectly written cron.

Have a good day.

Require.js fails to load data-main script (looks into wrong place)

Requirejs library fails to load script defined in data-main attribute for require.js script. According to browser output it looks into wrong place. Can’t sort it out why and how to fix it. Created dumbest way to reproduce it.

I have 3 files (in the root folder):

/dummy.html
/js/dummy-requirejs-config.js
/js/page/dummy-instance.js

Content of dummy.html:

<!DOCTYPE html>
<html lang="en">
    <body>
        <p>Hello World</p>
        <script data-main="/js/page/dummy-instance" src="https://requirejs.org/docs/release/2.3.7/comments/require.js"></script>
        <script src="js/dummy-requirejs-config.js"></script>
    </body>
</html>

Content of dummy-requirejs-config.js file:

require.config({
    baseUrl: 'js'
});

Content of dummy-instance.js file:

define({
    a: "a",
    b: "b"
});

My expectation was: page loads without any error. But it loads with error, browser console output is:

require.js:1962 
           GET http://localhost:8000/js/dummy-instance.js net::ERR_ABORTED 404 (Not Found)
req.load @ require.js:1962
load @ require.js:1686
load @ require.js:835
fetch @ require.js:825
check @ require.js:857
enable @ require.js:1177
enable @ require.js:1558
(anonymous) @ require.js:1162
(anonymous) @ require.js:135
each @ require.js:60
enable @ require.js:1114
init @ require.js:789
(anonymous) @ require.js:1461
setTimeout
req.nextTick @ require.js:1816
localRequire @ require.js:1450
configure @ require.js:1388
requirejs @ require.js:1795
(anonymous) @ require.js:2145
(anonymous) @ require.js:2146Understand this error
dummy.html:1 Refused to execute script from 'http://localhost:8000/js/dummy-instance.js' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.Understand this error
require.js:169 Uncaught Error: Script error for "dummy-instance"
https://requirejs.org/docs/errors.html#scripterror
    at makeError (require.js:169:17)
    at HTMLScriptElement.onScriptError (require.js:1739:36)

Note that url it is looking for does not contain /page part anymore (sorry for trace ai was asking for).