Unauthorized access Transformer.js even when i am authenticated using huggingface-cli

I was trying to experiment with transformers.js with microsoft phi-3

import { pipeline } from "@xenova/transformers";

const generator = await pipeline(
  "text-generation",
  "microsoft/Phi-3-mini-4k-instruct"
);

const response = await generator(
  "Instruction: Explain quantum computing in simple termsnResponse:",
  {
    max_new_tokens: 150,
    temperature: 0.3,
  }
);

console.log("response", response);

Although I’m authenticated using huggingface-cli with the access token, I get this error.

file:///Users/vignesh/projects/yt-mate/node_modules/@xenova/transformers/src/models.js:5526
            throw Error(`Unsupported model type: ${config.model_type}`)
                  ^

Error: Unsupported model type: phi3
    at AutoModelForCausalLM.from_pretrained (file:///Users/vignesh/projects/yt-mate/node_modules/@xenova/transformers/src/models.js:5526:19)
    at async Promise.all (index 1)
    at async loadItems (file:///Users/vignesh/projects/yt-mate/node_modules/@xenova/transformers/src/pipelines.js:3279:5)
    at async pipeline (file:///Users/vignesh/projects/yt-mate/node_modules/@xenova/transformers/src/pipelines.js:3219:21)
    at async file:///Users/vignesh/projects/yt-mate/src/utils/summarize.js:3:19

Node.js v20.18.1

Am I missing anything?

Auto delete unverified user after certain hours

I have a condition where unverified users will be automatically deleted after 8 hours, starting from after signing in.

The question is, How to make a trigger from that condition in AuthJs (NextAuth)?

P.S.: I’m using Mongoose, MongoDb, AuthJs (NextAuth), and NextJs

My AuthJs (NextAuth) config:

export const { auth, handlers, signIn, signOut } = NextAuth({
    adapter: MongoDBAdapter(client),
    session: { strategy: "jwt" },
    callbacks: {
        async session({ session, token, user }) {
            // `session.user.address` is now a valid property, and will be type-checked
            // in places like `useSession().data.user` or `auth().user`
            return {
                ...session,
                user: {
                    ...session.user,
                },
            }
        },

    },

    ...authConfig,
})

My User Schema:

import { Schema, Model, Types, Document, model, models } from 'mongoose';

export interface Users extends Document {
    name: string
    email: string
}

const UserSchema = new Schema<Users>({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
})

export default models.User || model<Users>('User', UserSchema)

React Vite Project on Hostinger Showing “Failed to Load Module Script” Error

I am hosting a React Vite project on Hostinger and using GitHub for version control. My repository is structured with two main folders: frontend (where my React project resides) and backend. By default, Hostinger serves files from the public_html directory, but I needed to serve the files from the frontend folder instead.

To achieve this, I created an .htaccess file inside public_html with the following content:

# Redirect to frontend folder
RewriteEngine on
RewriteCond %{HTTP_HOST} ^wactechx.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.wactechx.com$
RewriteCond %{REQUEST_URI} !frontend/
RewriteRule (.*) /frontend/$1 [L]

This allows me to reach my React project when accessing my domain. However, nothing renders on the webpage except the page title. When I check the console, I encounter this error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/plain”. Strict MIME type checking is enforced for module scripts per HTML spec.

Here is my main.jsx file:

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 suspect this is a MIME type issue, but I am unsure how to resolve it. I would appreciate any insights or solutions to ensure my React app loads correctly.

I tried redirecting to the frontend folder by modifying the .htaccess file to ensure Hostinger serves files from there instead of public_html. I expected the React Vite project to load properly when accessing the domain. However, the page only shows the title, and the console returns a MIME type error, preventing the app from rendering.

Number Format from react-number-format throws a 0. How to fix

I’m building a Currency component. Here when the default value is not 0, and if I enter 0, it throws a 0 below the Currency component. Similarly, if the default value is 0, it throws a 0 below the Currency component.
enter image description here
enter image description here

How can I make sure that it doesn’t throw the 0 below the input field( Currency) in both the cases.

import { TextFieldProps } from "@material-ui/core";
import React, { FC } from "react";
import { UseControllerOptions, UseFormMethods } from "react-hook-form";
import { NumberFormatProps } from "react-number-format";
import NumberTest from "./NumberTest";

export type FormInputBase<T> = {
  label: string;
  name: string;
  methods: UseFormMethods;
  typeOptions?: T;
  index?: number;
  predicator?: string;
};

export type CurrencyProps = UseControllerOptions &
  FormInputBase<TextFieldProps & NumberFormatProps>;

const CurrencyTest: FC<CurrencyProps> = ({ ...props }) => {
  function handleFocus(event: React.FocusEvent<HTMLInputElement>) {
    event.target.select();
  }
  return (
    <NumberTest
      {...props}
      typeOptions={{
        fixedDecimalScale: true,
        onFocus: handleFocus,
        decimalScale: 2,
        thousandSeparator: true,
        ...props.typeOptions,
        prefix: "$ ",
      }}
    />
  );
};

export default CurrencyTest;
import { TextField, TextFieldProps } from "@material-ui/core";
import { FC } from "react";
import {
  Controller,
  DeepMap,
  FieldError,
  UseControllerOptions,
  UseFormMethods,
} from "react-hook-form";
import NumberFormat, {
  NumberFormatProps,
  NumberFormatValues,
} from "react-number-format";

export const getErrorItem: any = ({
  methods,
  index = -1,
  ...props
}: Pick<FormInputBase<any>, "methods" | "index" | "name" | "predicator">) => {
  // hold vars
  let errors: DeepMap<Record<string, any>, FieldError> | undefined = undefined;
  let errorItem = undefined;
  // if a predicator exists, pull errors from it
  if (props.predicator) {
    errors = methods.errors ? methods.errors[`${props.predicator}`] : undefined;
  } else {
    errors = methods.errors;
  }
  // if a index exists, pull errors from it
  if (errors) {
    if (Array.isArray(errors) && index >= 0) {
      if (errors[index]) {
        if (errors[index][props.name]) {
          errorItem = errors[index][props.name];
        }
      }
    } else if (errors[props.name]) {
      errorItem = errors[props.name];
    }
  }
  return errorItem;
};

export type FormInputBase<T> = {
  label: string;
  name: string;
  methods: UseFormMethods;
  typeOptions?: T;
  index?: number;
  predicator?: string;
};

export type NumberProps = UseControllerOptions &
  FormInputBase<
    Pick<
      TextFieldProps,
      "size" | "margin" | "fullWidth" | "color" | "style" | "InputProps"
    > &
      Partial<NumberFormatProps>
  >;

const NumberTest: FC<NumberProps> = ({ methods, children, ...props }) => {
  // hold vars
  let errorItem = getErrorItem({
    methods: methods,
    index: props.index,
    name: props.name,
    predicator: props.predicator,
  });

  return (
    <Controller
      defaultValue={""}
      {...props}
      name={`${props.predicator ? props.predicator : ""}${
        props.index !== undefined ? `[${props.index}].` : ""
      }${props.name}`}
      control={methods.control}
      render={(control) => {
        const { onChange, ...controlProps } = control;
        return (
          <NumberFormat
            fullWidth
            margin="normal"
            variant="filled"
            label={props.label}
            {...props.typeOptions}
            {...controlProps}
            customInput={TextField}
            error={errorItem}
            helperText={errorItem && errorItem.message}
            value={control.value}
            onValueChange={(v: NumberFormatValues) => {
              control.onChange(v.floatValue);
            }}
          />
        );
      }}
    />
  );
};

export default NumberTest;

How to execute a playwright component test without the playwright test runner?

I’m interested in trying Component Testing with playwright.

Because of my setup, I cannot use the playwright test runner, so I’d like to produce a Node executable that I can just run.

For regular (non component) tests, this can be done like this but component tests have this mount parameter that I don’t know how to produce without the runner.

test('event should work', async ({ mount }) => {
  let clicked = false;

  // Mount a component. Returns locator pointing to the component.
  const component = await mount(
    <Button title="Submit" onClick={() => { clicked = true }}></Button>
  );

  // As with any Playwright test, assert locator text.
  await expect(component).toContainText('Submit');

  // Perform locator click. This will trigger the event.
  await component.click();

  // Assert that respective events have been fired.
  expect(clicked).toBeTruthy();
});

Can I use a React Component as a Keycloak call back?

I would like to use a Keycloak server to secure my React application.

I am using the keycloak-js package in my React Application.

The server redirected the browser to the dedicated URL(i.e. http://localhost:3000/testCallBack#state=b7db9a8c-9eae-4046-bf3c-b3ef1f7e0ec4&session_state=a203e7e0-fd17-43c1-97ef-6b0d12a6f514&code=3d2a8e8e-0507-42ae-93cf-05fc3cabe574.a203e7e0-fd17-43c1-97ef-6b0d12a6f514.4c1ce54a-3b50-4473-a147-b6acf131fac0).

However, I don’t know how to get the “code” in my React component.

Here is my code:

App.jsx

import './App.css';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import TestLogin from './TestLogin.jsx';
import TestCallBack from '../TestCallBack.jsx';
export default function App() {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<TestLogin />} />
        <Route path='/testCallBack' element={<TestCallBack />} />
      </Routes>
    </Router>
  )
}

TestLogin.jsx

import { useEffect } from 'react';
import Keycloak from 'keycloak-js';
export default function TestLogin(){
  const keycloak = new Keycloak({
        onLoad: 'check-sso',
        url: "keycloak.servers",
        realm: "master",
        clientId: "myAppId"
      });
      useEffect(() => {
        let doLogin = async () => {
          try {
            const authenticated = await keycloak.init();
            const link=await keycloak.login({
                redirectUri:"http://localhost:3000/testCallBack"
            });
            
            if (authenticated) {
              console.log('User is authenticated');
            } else {
              console.log('User is not authenticated');
            }
          } catch (error) {
            console.error('Failed to initialize adapter:', error);
          }
        }    
        doLogin();
      });
    return <div></div>
}

TestCallBack.jsx

export default function TestCallBack(){
    return <span>Hi</span>
}

navigator.geolocation.getCurrentPosition not working on localhost with Firefox, but it does on Chrome

I have a SUPER simple script that I am testing locally (127.0.0.1):

window.addEventListener('load',()=>{
    if("geolocation" in navigator){
        navigator.geolocation.getCurrentPosition(successFunction, failureFunction, null);
    } else {
        console.log("Error");
    }
});

successFunction(successObject){
    console.log(successObject);
}

failureFunction(failureObject){
    console.log(failureObject);
}

When I execute this in Chrome, the successFunction gets hit and the GeolocationPosition object gets printed to the console.

However, if I try this with Firefox 128.5.0esr (64-bit) on Debian 12, the failureFunction gets hit and the GeolocationPositionError gets printed to the console with this:

GeolocationPositionError {
    code: 2,
    message: "Unknown error acquiring position"
}

With code: 2 being “POSITION_UNAVAILABLE”

This seems to be a recent development with Firefox, as I haven’t had issues with this not too long ago.

I have given “Access your location” permission in Firefox, and I have no issues with this on sites on the open internet.

Google Maps JavaScript API – How to add hover effects to POIs?

Using maps.google.com, if I hover over a POI (point of interest), the cursor changes to indicate a clickable item, the text changes color, and a pop-up is shown. For instance, consider the case of me hovering over “BCD Tofu House”:

Screenshot of maps.google.com hover effect

How can I accomplish this with the JS Maps API? This seems like it should be a relatively simple thing to do, but I can’t find anything in documentation or online examples on how this can be done.

For instance, the onMouseover events in the Map API only trigger when the Map is moused over, not individual POIs, so it doesn’t help at all.

I’ve managed to implement a custom pop-up on click using the onClick property, like this (this is in React, but same principle applies to the JS API in general):

    onClick={(e) => {
      // disable default pop-up when clicking Google markers
      e.stop();

      const {
        detail: { placeId },
      } = e;

      if (placeId) {
        // use placesService to get details like name, address, and trigger state updates
        getPlaceByPlaceID(placesService, placeId, onPlaceSelect);
      }
    }} 

but there doesn’t seem to be an equivalent way of doing so with mouse hovering/movement.

Honestly, just changing the text color of the POI on hover (like Google Maps browser already does) without the pop-up on hover would be enough for my use case to help indicate clickability.

How to capture mutiple VueDatePicker data into single object in Vue3?

HTML Code:

<div v-if="isPlanDetailsAvailable">
        <div class="nav nav-tabs mb-3" id="nav-tab" role="tablist">
          <button v-for="(plan, index) in selectedPlans" :key="index" class="nav-link"
                  :class="{ active: index === 0 }" :id="'nav-tab-' + index" data-bs-toggle="tab"
                  :data-bs-target="'#nav-content-' + index" type="button" role="tab"
                  :aria-controls="'nav-content-' + index" :aria-selected="index === 0">
            {{ plan.name }}
          </button>
        </div>
      </nav>
      <div class="tab-content" id="nav-tabContent">
        <div v-for="(plan, index) in selectedPlans" :key="index" :id="'nav-content-' + index"
             class="tab-pane fade" :class="{ show: index === 0, active: index === 0 }" role="tabpanel"
             :aria-labelledby="'nav-tab-' + index">
          <div class="row">
            <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-6 mb-3">
              <label for="" class="label">Enrollment Date <span class="dim-light">(Optional)</span></label>
              <VueDatePicker
                  v-model="plan.enrollmentDate"
                  placeholder="MM/DD/YYYY"
                  :format="(date) => enrollmentDateFormat(date, plan)"
              />
            </div>
            <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-6 mb-3">
              <label for="" class="label">Effective Date</label>
              <VueDatePicker
                  v-model="plan.effectiveDate"
                  placeholder="MM/DD/YYYY"
                  :format="(date) => effectiveDateFormat(date,plan)"
                  @click="clearEffectiveDateError(index)"
              />
              <div class="error-msg text-danger">
                {{
                  this.effectiveDateErrors.length > 0 && this.effectiveDateErrors[index]
                      ? this.effectiveDateErrors[index]
                      : ""
                }}
              </div>
            </div>
            <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-6 mb-3">
              <label for="" class="label">Termination Date <span class="dim-light">(Optional)</span></label>
              <VueDatePicker
                  v-model="plan.terminationDate"
                  placeholder="MM/DD/YYYY"
                  :format="(date) => terminationDateFormat(date, plan)"
              />
            </div>
</div>
</div>
</div>

Functions:

enrollmentDateFormat(date, plan) {
  return plan.enrollmentDate = this.handleDateChange(date);
},
effectiveDateFormat(date, plan) {
  return plan.effectiveDate = this.handleDateChange(date);
},

terminationDateFormat(date, plan) {
  const terminationDate = this.handleDateChange(date);
  plan.terminationDate = terminationDate;

  if (plan.effectiveDate) {
    this.isTerminationDateLessThanEffectiveDate(plan.effectiveDate, plan);
  }

  return terminationDate;
},

handleDateChange(date) {
  if (!date) return "";
  const day = date.getDate();
  const month = date.getMonth() + 1;
  const year = date.getFullYear();
  return `${month.toString().padStart(2, "0")}/${day
      .toString()
      .padStart(2, "0")}/${year}`;
},

isTerminationDateLessThanEffectiveDate(date, plan) {
  const effectiveDate = new Date(date);
  const terminationDate = new Date(plan.terminationDate)

  return terminationDate < effectiveDate;
}

Here I have multiple tabs and I am trying to capture each tab index multiple VueDatePicker value into same object what the problem that I am facing is whenever I select one date value in one input(i.e. enrollment date) field it displays on that input field but as soon as I select next date in another input field (i.e. effective date) or the next tab enrollment date the selected data vanishes in previous tab input field as well.

How can I solve this?

These are my UI images:

enter image description here
enter image description here

How do I access the development tools and change the default type?

I would like to know if there is any way to change the default state of an ECHARTS chart with developer tools. For example, it would be something like:

        document.addEventListener("DOMContentLoaded", () => {

            // Access type:'gauge' defaultOption
            echarts.extendSeriesModel({
                type: 'gauge',
                defaultOption: {
                    startAngle: 180,
                    endAngle: 0,
                    radius: '75%',
                    axisLine: {
                        lineStyle: {
                            color: [[1, "#333"]]
                        }
                    },
                    itemStyle: {
                        color: '#f00'
                    }
                }
            });

            // init
            const chart = echarts.init(document.getElementById('chart'));

            // option
            const option = {
                series: [
                    {
                        type: 'gauge', // new defaultOption (does not work)
                        data: [{ value: 50, name: 'Speed' }]
                    }
                ]
            };

            // setOption
            chart.setOption(option);
        });
<head>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
    <title>Custom Gauge</title>
</head>

<div id="chart" style="width: 100%; height: 100vh;"></div>

My intention (which is certainly incorrect) is to access the type of a chart internally (e.g. type:'gauge') and change its default settings for each type:'gauge' created.

Note that I prefer to use something related to these methods.

Why does my .then execute before the prior one is finished?

The following page fetches an array of database rows from a php page, then instantiates each row as an object.
After the rows have been instantiated and added to an array, I want to build my html table from the array of objects using the buildTable function.
However, the buildTable function executes prior to the array of objects being populated even though it is in .then.
What am I doing wrong?
Thanks,

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
        <meta content="utf-8" http-equiv="encoding">
        <script src="jquery-3.3.1.min.js" type="text/javascript"></script>
        <script>
            var lotID; var counter=0;
            $(document).ready(function() {
                getQCDims(12346);
            })
            var QCDims=[];
            class QCDim{
                ID; Bal; Name;
                constructor(row){
                    this.ID=row.QCDimID;
                    this.Bal=row.QCDimBalloon;
                    this.Name=row.QCDimDisplayName;
                    console.log("Bal" +row.QCDimBalloon );
                }
            }

            function getQCDims(lotID){
                    let params = new URLSearchParams();
                    params.append("operation", "getQCDim");
                    params.append("lotID", lotID);

                    fetch("datarequests_QCDisplay.php", {
                        method: "POST", 
                        mode: "cors", 
                        cache: "no-cache", 
                        credentials: "same-origin", 
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                        },
                        redirect: "follow", 
                        referrer: "no-referrer", 
                        body: params, 
                    })
                    .then((response) => response.json() )
                    .then(data => {
                        if(data.status > 0 ) throw data.reason;
                        return data.rows;
                    })
                    .then(rows => {
                        for(var i=0; i < rows.length-1; i++){ 
                            QCDims.push(new QCDim(rows[i]))
                        }
                    })
                    .then(buildTable())
                    .catch(error => {console.log(error);})
            }

            function buildTable(){
                console.log("Build Table");
                console.log("QCDims.length="+ QCDims.length);
                let newHTML='';
                for (let i = 0; i < QCDims.length-1; i++) {
                    newHTML = newHTML + "<th>"+ QCDims[i].Bal +"</th>";
                }
                $("#mythead").html(newHTML);
            }
        </script>
        
    </head>
    <body>
        <table><thead id="mythead"></thead><tbody></tbody></table>
    </body>
</html>

AWS Lambda. Returning Empty Response

I’m following a tutorial for putting info into a DynamoDB and after initializing a variable the code returns an empty response and I can’t seem to figure out how it makes sense at all. Code is in JavaScript

import { DynamoDBClient, GetItemCommand, PutItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall } from "@aws-sdk/util-dynamodb";

export const handler = async (event) => {
  const cognitoIdentityProviderClient = new CognitoIdentityProviderClient( { region: process.env.REGION } );
  const dynamoDBClient = new DynamoDBClient( { region: process.env.REGION } );

  try{
    const adminGetUserInput = {
      Username: event.username, 
      UserPoolId: process.env.USER_POOL_ID
    };

    const adminGetUserCommand = new AdminGetUserCommand(adminGetUserInput);
    const adminGetUserResponse = await cognitoIdentityProviderClient.send(adminGetUserCommand);

    const sub = adminGetUserResponse.UserAttributes.find(attribute => attribute.Name === "sub").Value;
    const email = adminGetUserResponse.UserAttributes.find(attribute => attribute.Name === "email").Value;

    const getItemInput = {
      TableName: "Players",
      Key: marshall({ databaseid: sub })
    };

    const getItemCommand = new GetItemCommand(getItemInput);
    let statsFromDB = await dynamoDBClient.send(getItemCommand);

    const eventMatchStats = event.matchStats;

    for (const key in eventMatchStats) {
      if (statsFromDB[key] !== undefined){
        statsFromDB[key] += eventMatchStats[key];
      } else{
        statsFromDB[key] = eventMatchStats[key];
      }
    }

    const putItemInput = {
      TableName: "Players",
      Item: marshall( { ...statsFromDB } )
    };

    const putItemCommand = new PutItemCommand(putItemInput);
    const putItemResponse = await dynamoDBClient.send(putItemCommand);

    return {
      statusCode: 200,
      body: `Updated match stats for ${event.username}`
    };

  } catch(error){
    return error;
  }
};```

Status: Succeeded
Test Event Name: testRecordMatchStats

Response:
{}

Function Logs:
START RequestId: 382102d2-599c-4e65-bc47-7cb94c9ed356 Version: $LATEST
END RequestId: 382102d2-599c-4e65-bc47-7cb94c9ed356
REPORT RequestId: 382102d2-599c-4e65-bc47-7cb94c9ed356 Duration: 698.78 ms Billed Duration: 699 ms Memory Size: 128 MB Max Memory Used: 105 MB

Request ID: 382102d2-599c-4e65-bc47-7cb94c9ed356“`

This is what I end up getting with the current code but if I put the return above the

const putItemInput = {
  TableName: "Players",
  Item: marshall( { ...statsFromDB } )
};

it outputs correctly.

Redux Store – Access entire slice

Objective: Access the latest data from a slice in my Redux store in response to user input.
Problem: I’ve tried const mySliceSelector = useSelector((state) => state.mySlice);, but when the user input triggers my callback function, the actual state of mySlice is not accessible via my selector. I tested this by doing console.log(JSON.stringify(mySliceSelector)), and it just prints the initial state of the slice. If I make a change to the file that contains this code and save it, everything works correctly after the hot reload.

Here is a snippet of my code, for better context:

    const mySliceSelector = useSelector((state) => state.mySlice);
    
    const handleClick = async () => {
        console.log(JSON.stringify(mySliceSelector));
    }

The arrays and data inside the slice are empty when printed, except after a hot reload.

Which is the best working combination of versions for eslint, eslint-config-next, next, react and react-dom? [closed]

which is the best working combination of versions for Eslint, Eslint-config-next, Next, React and React-dom?

Present combination of Eslint (9.17.0), Eslint-config-next (15.1.3), Next (15.1.3), React (18.3.1) and React-dom (18.3.1) gives me headaches with simple ‘hello world’ homepage.

I’m a newbie with these technologies.

They give me an error with ‘npm run build’ exited with code 1.

I tried suggestions from other threads like to delete node-modules and package-lock.json file and the ‘npm install’ again but… no luck for me.

So I guess it could also be underlying problems with different versions of above mentioned tech.

Thanks very much in advance.