Uncaught ReferenceError: uploadFile is not defined

Working through a firebase tutorial and keep getting the error that uploadFile is not defined. this is the code snippet in my index.html file

<body>
    <h3>Storage Uploads</h3>
    <input type="file" onchange="uploadFile(this.files)" />
    <hr />
    <img id="imgUpload" src="" width="100vw" />
  </body>

this is my app.js function

document.addEventListener("DOMContentLoaded", (event) => {
  const app = firebase.app();
  console.log(app);
});
function uploadFile(files) {
  const storageRef = firebase.storage().ref();
  const horseRef = storageRef.child("horse.jpg");

  const file = files.item(0);
  const task = horseRef.put(file);

  task.then((snapshot) => {
    console.log(snapshot);
    const url = snapshot.downloadURL;
    document.querySelector("#imgUpload").setAttribute("src", url);
  });
}

ive tried clearing the cache, ending the firebase serve, tried firebase deploy and am still getting that the function is undefined. Any help would be appreciatted

Blank screen appearing rather than popup when trying to use Facebook login in my Vite React app

So, I am trying to implement Facebook oAuth in React. I have already created an app and provided the following permissionsMyApp’s permissions

When I click on the Login via Facebook button, I get redirected to a blank page:
Blank Page

https://www.facebook.com/v19.0/dialog/oauth?app_id={app_id}&cbt=1708623988568&channel_url=https%3A%2F%2Fstaticxx.facebook.com%2Fx%2Fconnect%2Fxd_arbiter%2F%3Fversion%3D46%23cb%3Df321eccf78467bd5a%26domain%3Dlocalhost%26is_canvas%3Dfalse%26origin%3Dhttp%253A%252F%252Flocalhost%253A3000%252Ffe2f7254840790489%26relation%3Dopener&client_id=1082613119655352&display=popup&domain=localhost&e2e=%7B%7D&fallback_redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&locale=en_US&logger_id=f8d48aafad08478f2&origin=1&redirect_uri=https%3A%2F%2Fstaticxx.facebook.com%2Fx%2Fconnect%2Fxd_arbiter%2F%3Fversion%3D46%23cb%3Df91b0ff47a1eb9d27%26domain%3Dlocalhost%26is_canvas%3Dfalse%26origin%3Dhttp%253A%252F%252Flocalhost%253A3000%252Ffe2f7254840790489%26relation%3Dopener%26frame%3Df15b4e394597d51bd&response_type=token%2Csigned_request%2Cgraph_domain&scope=email&sdk=joey&version=v19.0

The link is something like above.

Here’s my code:

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : '1082613119655352',
          cookie     : true,
          xfbml      : true,
          version    : 'v19.0'
        });
          
        FB.AppEvents.logPageView();   
          
      };

      (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));
    </script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

App.jsx

import React from 'react';
import { FacebookProvider, LoginButton } from 'react-facebook';

function App() {
    function handleSuccess(response) {
      console.log(response.status);
    }
  
    function handleError(error) {
      console.log(error);
    }
  
    return (
      <FacebookProvider appId="1082613119655352">
        <LoginButton
          scope="email"
          onError={handleError}
          onSuccess={handleSuccess}
        >
          Login via Facebook
        </LoginButton>
      </FacebookProvider>
  );
}

export default App;

There aren’t any console errors either. Idk what’s the issue. Please help.

Algorithm to find the path with the least number of changes in an arrow matrix

I have been working on a school project and have been trying to make some puzzles for kids.
The task is to create many conveyor belt type scenarios where kids are supposed to spot the most efficient(shortest and least changes(higher priority)) conveyor to the end point.

I decided to come up with a random arrow matrix generator so that I can churn out the puzzles. However, solving them seems to be a pinch for me. The matrix looks something like this:

**Example of matrix
**
{See first image}enter image description here

I then proceeded to try and follow djikstra’s algorithm to solve but i hit some problems.
Firstly revisiting the node seems to be needed. Unsure of how to go about this.

Secondly how do i ensure the arrows are rotated to the correct direction/most efficient direction(I understand right and down arrows might be heavier in weightage but still there may be instances where a longer path has the least changes)

This is what i have so far. Im very confused T.T

{see image} Code i have done so far

The Result i want is the path with the least changes(higher priority) and is shortest. My code is probably awful but pls do help.

How to transcribe audio blob using API in a Nextjs browser application?

I am working on creating a web app in Next.js and Typescript. For a specific functionality, I must grab browser or desktop audio from the client side and store it for transcription. I have been able to get user audio through Chrome’s APIs (although this feature is not supported on Firefox). After getting the audio, I have made a simple HTML audio player that can play that recorded audio. Everything works. Now, I want to send this audio file to an online API like OpenAI so that I can receive a transcription of this audio. I have tried several ways to do this, but the OpenAI API always gives back an error saying that the file format is not supported although I am capturing audio in WAV format. I have also tried using the OpenAI node module., but that didn’t work either.:

// Component to capture user audio

import { useEffect, useRef, useState } from 'react';
import transcribe from '@/API/transcribe';

const AudioCaptureButton = () => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const [chunks, setChunks] = useState<BlobPart[]>([]);

  const captureAudio = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getDisplayMedia({
        video: true, // This is required, even though we are not capturing video. Setting this to false throws an error.
        audio: true
      });

      const recorder = new MediaRecorder(mediaStream);
      setMediaRecorder(recorder);

      recorder.ondataavailable = (e) => {
        setChunks((prev) => {
          const updatedChunks = [...prev, e.data];
          const blob = new Blob(updatedChunks, { 'type' : 'audio/wav' });
          const audioURL = window.URL.createObjectURL(blob);
          if (audioRef.current) {
            audioRef.current.src = audioURL;
          }

          transcribe(blob);
          
          return updatedChunks;
        });
      };

      // recorder.ondataavailable = (e) => {
      //   setChunks((prev) => [...prev, e.data]);
      // };
  
      // recorder.onstop = async () => {
      //   const audioBlob = new Blob(chunks, { type: 'audio/wav; codecs=opus' });
      //   await transcribe(audioBlob);
      // };

      // Instead of providing a "Stop Capture" button, we can just stop the capture when the mediaStream ends.
      mediaStream.getTracks().forEach(track => {
        track.onended = () => {
          if (recorder.state !== 'inactive') {
            recorder.stop();
          }
        };
      });

      recorder.start();
    } catch (err) {
      console.error('Error capturing audio', err);
    }
  };


  return (
    <div>
      <button onClick={captureAudio}>Start Capture</button>
      <audio ref={audioRef} controls />
    </div>
  );
};

export default AudioCaptureButton;

And this is the API code:



import OpenAI from "openai";
import fs from "fs";


const openai = new OpenAI({
    apiKey: "MY API KEY",
    dangerouslyAllowBrowser: true
});


const transcribe = async (audio: Blob) => {
    /* Function that will use OpenAI's Whisper API to transcribe audio. */

    const file = new File(, "audio.wav", { type: 'audio/wav' });
    const response = new Response(audio);
    console.log(response);

    const transcription = await openai.audio.transcriptions.create({
        file: response,
        model: "whisper-1",
    }).then((res) => {
        console.log(res);
        return res;
    }).catch((err) => { console.error(err); });

    // const audioBlobWithType = new Blob(, { type: 'audio/wav' });

    // const formData = new FormData();
    // formData.append("file", audioBlobWithType, "audio.wav")
    // formData.append("model", "whisper-1")

    // const transcription = await fetch("https://api.openai.com/v1/audio/transcriptions", {
    //     method: "POST",
    //     headers: {
    //         "Authorization": "Bearer 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",
    //     },
    //     body: formData,
    // });

    // console.log(await transcription.json())
}

export default transcribe;

In the transcribe function, I am currently trying to use the OpenAI package to get the transcription. However, as mentioned, it says that the file format is not supported. In the transcribe function, I have also commented-out the code that used the API instead of the library to send the audio file. That too resulted in a file format not supported error.

I would appreciate any help in this matter. I have been stuck on this issue for more than a week now. If there is something wrong with the blob file itself, like, I am sending it at the wrong time, I would like to know that as well. Thank you!

why jpg images can’t be imported in vite for React?

I wanted to import a .jpg file to my React file but when I wanted to do that, an error popped up, so I don’t have this problem with .png or .svg files, so I was wondering why this error pops up for .jpg files and how should we fix that?

error:

Failed to parse source for import analysis because the content contains 
invalid JS syntax. You may need         to install appropriate plugins 
to handle the .JPG file format, or if it's an asset, add "**/*.JPG" to       
`assetsInclude` in your configuration.

How to send the jwt token to the frontend through headers on nodejs?

Okay so i have simple application. When the user logs in, i create a token with jwt. I have been using res.cookie() to send the token to the frontend but due to reasons, i can no longer use cookies, How do i use headers to achieve the same goal?

Basically, this is what i want to achieve:

//Login function

const login = async (req, res) => {
    const {email, password} = req.body
    
    const user = await User.findOne({email})
    if(!user){
        throw new UnauthenticatedError('Invalid credentials')
    }

    const isPasswordCorrect = await user.comparePassword(password)
    if(!isPasswordCorrect){
        throw new UnauthenticatedError('Invalid credentials')
    }

    const token = user.createJWT()
    res.cookie("token", token).json(user)     //send token here to the frontend through headers instead of cookies
}

//Auth middleware to verify the token:

const authMiddleware = async (req, res, next) => {
    const {token} = req.cookies    //get the token here from the headers instead of cookies

    if(token){
        try{

            const {userId, name} = jwt.verify(token, process.env.JWT_SECRET)
            req.user = {userId, name}  
            next()
        }
        catch(error){
            throw new UnauthenticatedError('Authentication invalid')
        }
    }else{
        throw new UnauthenticatedError('no token')
    }
}

//Login component on the frontend

const handleLogin = async (e) => {
        e.preventDefault()
        try {
            const {data} = await axios.post('/auth/login', {email,password})
            successfulNotification('login successful')
            setUser(data)
            setRedirect(true)
        } catch (error) {
            errorNotification('login unsuccessful, please try again later')
            return error
        }        
    }

Problem with finding out if the first element of an array is different from the rest of the identical elements in that array (due to a typo)

I am attempting to solve this challenge:

This function receives an array of fruits (orchard), where all fruits are spelled correctly except for one. The function is tasked with identifying the index position of the misspelled fruit. For instance, in the given example, the function should return 0.

['graep', 'grape', 'grape', 'grape']

This is what I have so far:

function findWrongWayFruit(orchard) {
  if (orchard.length < 3) {
    return 0;
  }

  const firstFruit = orchard[0];
  for (let i = 1; i < orchard.length; i++) {
    if (firstFruit !== orchard[i]) {
      return i;
    }
  }
  return 0;
}


console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));

However, when I try to run this code, the only test case that failed was this: Should return the correct index when the wrong-way fruit is at start’ (AssertionError: expected 1 to equal +0)

why do i get a 404 when i import in js

im new to javascript and im trying to make a simple web app, when making the login page i wanted to make the script that is directly running in the browser call another script to do the back end

now i got frustrated and deleted the code but here is a simple example of how it works…

login.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Login into to your account!</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    
    <body>
        <div id="login">
    <label>Username:</label>

    <input type="text" id="userNameF">
    <br>

    
    <label>Password: </label>
    <input type="password"id="passwordF">
        <br>


    <input type="button" id="submit" value="Login">

        <h1 id="warning">H</h1>
            </div>
    

    <div id="page">

        <h1 id="balance"></h1>


            <input type="text" id="amount" placeholder="Amount">
            <input type="text" id="receptor" placeholder="Receptor">
            <input type="button" value="Send" id="sendBtn">
            <h1 id="warning2">H</h1>
    </div>

    <script src="./dist/login.js" type="module"></script>
    </body>
    </html>

login.js

import { yes } from "./ye";

ye.js

export function d(yes){
    console.log(yes)
}

i was expecting no error and proceeding with the code normally,

what i got was

GET http://127.0.0.1:5500/dist/ye net::ERR_ABORTED 404 (Not Found)

Clear input search box and refresh data

In this code, the #searchInpForm search box gets cleared but the data that is called by my getAllPersonnel() function doesn’t refresh. It refreshes if I don’t include the line about emptying the search box.

Also, the function gets called but the data just doesn’t. I have the same issue if I set the search input field to an empty string as well. What should I look at next to fix this?

$("#refreshBtn").click(function () {
  if ($("#personnelBtn").hasClass("active")) {
    // console.log("Button was clicked");
    $("#searchInpForm")[0].reset();
    getAllPersonnel();

    // $("#searchInp").val("");
  } else if ($("#departmentsBtn").hasClass("active")) {
    // console.log("Button was clicked");
    getAllDepartments();
  } else if ($("#locationsBtn").hasClass("active")) {
    getAllLocations();
  }
});

Hash classnames nextJS v14

How do you hash CSS classnames for nextJS v14

The old way you used to was something like:

const path = require("path");
const loaderUtils = require("loader-utils");

const hashOnlyIdent = (context, _, exportName) =>
  loaderUtils
    .getHashDigest(
      Buffer.from(
        `filePath:${path
          .relative(context.rootContext, context.resourcePath)
          .replace(/\+/g, "/")}#className:${exportName}`
      ),
      "md4",
      "base64",
      6
    )
    .replace(/[^a-zA-Z0-9-_]/g, "_")
    .replace(/^(-?d|--)/, "_$1");

module.exports = {
  experimental: { appDir: true },
  webpack(config, { dev }) {
    const rules = config.module.rules
      .find((rule) => typeof rule.oneOf === "object")
      .oneOf.filter((rule) => Array.isArray(rule.use));
    if (!dev)
      rules.forEach((rule) => {
        rule.use.forEach((moduleLoader) => {
          if (
            moduleLoader.loader?.includes("css-loader") &&
            !moduleLoader.loader?.includes("postcss-loader")
          )
            moduleLoader.options.modules.getLocalIdent = hashOnlyIdent;
        });
      });

    return config;
  },
};

But this currently gives some errors. Like: getLocalIdent is not found

You can directly use className={styles.flag} inside of your jsx file but this doesnt hash it to a short code in production (like vercel)

So I want as a result, to have my css classnames look like this: 9pt5S instead of the current navbar_flag__9pt5S (by using: className={styles.flag}

How to use C# function inside a JavaScript

I have a razor page in my MVC project.

Now iam trying to render a table row from javascript. I intend to use a C# function currentAccount.ConvertToAccountTimeZone() which would take javascript var as a parameter. Can this be possible ?

tableRow += `<td class="submission-date-col">${currentAccount.ConvertToAccountTimeZone(r.SubmissionDate)}</td>`;

currentAccount.ConvertToAccountTimeZone is C# function.
r.SubmissionDate is my javascript variable.

If I use ‘@’ in my script like

tableRow += `<td class="submission-date-col">${@currentAccount.ConvertToAccountTimeZone(r.SubmissionDate)}</td>`;

It puts an error on r.SubmissionDate saying The name ‘r’ does not exist in the current context.

Error when npm install private github repository as a dependency

When I add the private repository to package.json, I get an error when I try to install it with the npm install command. I don’t get any errors when I run this error with the yarn install command.

package.json:

"repo-name": "git+https://github_pat_***:[email protected]/company/repo-name.git"

log:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /Users/username/.npm/_cacache/tmp/git-cloneXObG5S/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/Users/username/.npm/_cacache/tmp/git-cloneXObG5S/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in: /Users/username/.npm/_logs/2024-02-22T15_22_06_508Z-debug-0.log

Input Color Dialog bigger than Container

I’m having a strange problem with a in a Chrome extension. As you can see in the attached image the dialog where you can choose the color is cut and I’m unable to change color tone.

Color picker dialog on click

I’m using bootstrap as css framework and working with react. Yesterday it was working fine.

This should be the normal Dialog for a color input

I’ve tried to change display, container, using as standalone input but nothing worked

to select the dropdown list via javascript in python selenium

I wrote a code to select a drop-down list. Once I run a programme, the UI of the dropdown appears in the desktop window, so I got one JavaScript to choose a dropdown element. It selects a list from a dropdown, but the element shows a sign that I need to select a dropdown list to proceed further.

I tried this code:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(""https://example.com"")

'dropdown_id' with the actual ID of the dropdown element
dropdown_element = driver.find_element_by_id(""dropdown_id"")

'option_value' with the value of the option you want to select
option_value = ""desired_option_value""

Execute JavaScript to select the option
driver.execute_script(""arguments[0].value = arguments[1]"", dropdown_element, option_value)

Close the browser
driver.quit()

This code selects the right option but in the web shows you have select a list from the dropdown to proceed further

How to spy on an object not created in the test code with Jest

In the code I’m trying to test I have the following:

const redisClient = redis.createClient({ url: `redis://${process.env.REDIS_ADDRESS}:${process.env.REDIS_PORT}` })
    .on('error', (err) => {
        logging.error(`Redis Client Error ${utils.getErrorJson(err)}`)
    });

The test function looks like this:

it('should log error when creating redit client fails', async () => {
        redis.createClient = jest.fn().mockImplementation(() => {
            throw new Error('test error');
        });

        jest.spyOn(redisClient, 'on');
    });

Is there any way to spy on the ‘on’ function in the SUT code so I can verify it was called? Obviously the restClient object is not declared in a scope that the test code can see. So is there some