Is there a command in vscode that will strongly type your variable declarations?

Let’s say you want to convert your JavaScript into Typescript and you want to strongly type all your variable declarations. Is there a command that does this? Or for example, you have a javascript snippet you found online or class and now you want to use Typescript. Now you want that code to have types. Is there a way to automatically type javascript code?

For example, if you have the following code the tool will upgrade it from example one to example two:

// before
var x = 10;

// after
var x: number = 10;

// before
var myDate = new Date();

// after
var myDate: Date = new Date();

// before
var response = await fetch("test");

// after
var response: Promise<Response> = await fetch("test");

We all know there is a format command that will format your code but is there one that will add the correct types the javascript that you now want to be valid typescript?

Why? Because I have a lot of and I mean gazillions of lines of code in javascript and I want to see the types now that I’m using typescript.

How would I be able to use javascript in order to overlay an explosion gif as a callable function?

I have a countdown timer on my website, and I want it to overlay a generic explosion GIF when the timer runs out. I have a function call when it runs out, now I just need to know what will go in that function.

I’m really new to JavaScript and web dev as a whole, so I don’t have any idea how to go about this.

I’ve tried looking online but all of the docs I’ve found don’t provide any help or don’t make any sense.

This is the code that I have so far:

window.onload = function () {
    var time = 299, // your time in seconds here
        display = document.querySelector('#timer');
    startTimer(time, display);
};

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            
            // This is the part that will call the explosion function.
        }
    }, 1000);
}

How do I validate on change but only after submitting in this React Hook Form?

Right now, I’m using isSubmitted to control whether shouldValidate should be activated in onChange. I want that validation to happen only after the form has been submitted. After that, the validation should happen on each change.

// JS:

const {
  setValue,
  getValues,
  formState: { isSubmitted },
} = useForm<FormData>({
  resolver: zodResolver(schema),
  defaultValues: {
    customFields: []
  },
});

// JSX:

<CustomFields
  fields={getValues('customFields')}
  keysOnly
  onChange={(fields) => {
    setValue('customFields', fields, {
      shouldDirty: true,
      shouldValidate: isSubmitted,
    });
  }}/>

Does React Hook Form have an option that does this automatically? I don’t want to rely on isSubmitted.

Get audio.duration with JavaScript from URL

I am trying to set the position of an audio source to the remainder of the time since the UNIX epoch divided by the duration of the audio in milliseconds. audio0.duration and the other two return a value of NaN. How can I get the audio duration to be an integer that I can use?

JavaScript code is below.

function PlaySample (file) {  
  const audio0 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a0.mp3');
  const audio1 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a1.mp3');
  const audio2 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a2.mp3');

  audio0.pause();
  audio1.pause();
  audio2.pause();
  
  switch (file) {
    case 0:
      audio0.currentTime = PlayheadPos(audio0.duration * 1000);
      audio0.play();
      break;
    case 1:
      audio1.currentTime = PlayheadPos(audio1.duration * 1000);
      audio1.play();
      break;
    case 2:
      audio2.currentTime = PlayheadPos(audio2.duration * 1000);
      audio2.play();
      break;
    default:
      break;
  }
}

function PlayheadPos (audioLen) {
  alert(Date.now() % audioLen);
  return Date.now() % audioLen;
}

Thanks in advance.

VideoPlayer.jsx:34 GET http://localhost:3001/public/test/output.m3u8 404(not found)

I want to stream videos to the site so that users don’t wait for the entire video to load, but I’m stuck with an error that says: Video Player.jsx:34 GET http://localhost:3001/public/test/output.m3u8 (Not found)
I did everything right, but I can’t get around the problem. Help please,my code is supposed to split the video into parts and then have to play it back.

videoplayer.jsx

import React, { useEffect, useRef, useState } from 'react';
import Hls from 'hls.js';

const VideoPlayer = () => {
    const videoRef = useRef(null);
    const [videoUrl, setVideoUrl] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchVideo = async () => {
            try {
                const response = await fetch('http://localhost:3001/');
                if (!response.ok) {
                    throw new Error(`Сервер вернул статус: ${response.status}`);
                }
                // Установите URL для HLS
                setVideoUrl('http://localhost:3001/public/test/output.m3u8');

            } catch (error) {
                console.error('Ошибка при получении видео:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchVideo();
    }, []);

    // Воспроизведение HLS
    useEffect(() => {
        if (videoUrl && videoRef.current) {
            if (Hls.isSupported()) {
                const hls = new Hls();
                hls.loadSource(videoUrl);
                hls.attachMedia(videoRef.current);
                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                    videoRef.current.play();
                });
            } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
                videoRef.current.src = videoUrl;
                videoRef.current.addEventListener('loadedmetadata', () => {
                    videoRef.current.play();
                });
            }
        }
    }, [videoUrl]);

    return (
        <div>
            {loading ? <p>Загрузка видео...</p> : (
                <video ref={videoRef} controls width="640" height="360"></video>
            )}
        </div>
    );
};

export default VideoPlayer;

converted.js

import express from 'express';
import cors from 'cors';
import { spawn } from 'child_process';
import fs from 'fs';
import path from 'path';

const app = express();
const PORT = 3001;

app.use(cors());
app.get('/test-file', (req, res) => {
    const testFilePath = path.join('C:/Users/fomic/vite-project/public/test/test.txt');
    
    fs.readFile(testFilePath, 'utf8', (err, data) => {
        if (err) {
            console.error('Ошибка при чтении файла:', err);
            return res.status(500).send('Ошибка при чтении файла.');
        }
        res.send(data);
    });
});

app.get('/', (req, res) => {
    const inputVideo = path.join('C:/Users/fomic/vite-project/public/videoplayback.mp4');
    const outputPlaylist = path.join('C:/Users/fomic/vite-project/public/test/output.m3u8');

    console.log('Проверка входного файла:', inputVideo);
    if (!fs.existsSync(inputVideo)) {
        console.error('Ошибка: входной файл не найден.');
        return res.status(404).send('Входной файл не найден.');
    }
    
    // Проверка существования входного файла
    console.log('Проверка входного файла:', inputVideo);
    if (!fs.existsSync(inputVideo)) {
        console.error('Ошибка: входной файл не найден.');
        return res.status(404).send('Входной файл не найден.');
    }

    // Проверка существования выходной директории
    const outputDir = path.dirname(outputPlaylist);
    console.log('Проверка директории для выходных файлов:', outputDir);
    if (!fs.existsSync(outputDir)) {
        console.log('Директория не найдена. Создаю новую директорию...');
        fs.mkdirSync(outputDir, { recursive: true });
    }

    console.log('Запуск FFmpeg для конвертации...');
    const ffmpegProcess = spawn('ffmpeg', [
        '-i', inputVideo,
        '-c', 'copy',  // Исправлено здесь
        '-start_number', '0',
        '-hls_time', '10',
        '-hls_list_size', '0',
        '-f', 'hls',
        outputPlaylist
    ]);

    ffmpegProcess.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });

    ffmpegProcess.stderr.on('data', (data) => {
        console.error(`stderr: ${data.toString()}`);
    });

    ffmpegProcess.on('close', (code) => {
        if (code === 0) {
            res.send('Конвертация завершена!');
        } else {
            console.error(`Ошибка при выполнении FFmpeg, код: ${code}`);
            res.status(500).send(`Ошибка при конвертации видео, код: ${code}`);
        }
    });
});

// Запуск сервера
app.listen(PORT, () => {
    console.log(`Сервер запущен на http://localhost:${PORT}`);
});
  

app.jsx

import { useState } from 'react'
import Release from './components/Release/Release'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import Header from './components/Header/Header'
import Podcaster from './components/Podcaster/Podcaster'
import TabsSection from './components/TabsSection/TabsSection'
import LentaSection from './components/LentaSection/LentaSection'
import SubscribesSection from './components/SubscribesSection/SubscribesSection'
import PlayListSection from './components/PlayListSection/PlayListSection'
import { Registration } from './components/Forms/Registration'
import { Auth } from './components/Forms/Aurh'
import { BrowserRouter as Router, Route,  Routes } from 'react-router-dom'; 

function App() {
  const [count, setCount] = useState(0)


  return (
    <>
    <Router> 
            
                <Header/>  

                <Routes>
                <Route path="/auth" element={<Auth />} />
                <Route path="/release" element={<Release />} />
                <Route path="/podcaster" element={<Podcaster />} />
            </Routes>

                  
            
        </Router> 
    
    </>
  )
}

export default App

Why `[1, 2, 3]` is not showing as an `Array(3)` in Console?

When I inspect an instance of an array (like const arr = [1, 2, 3];), the prototype chain for that array will point to Array.prototype.

However, I am not able to understand why Array.prototype is displayed as an empty array (Array(0)) in Chrome console.log()?

enter image description here

I have gone through post1 and post2 but still not able to understand this basic concept.

Why [1, 2, 3] in the console in not showing as an Array(3)?

How to subscribe with Twurple to Twitch Api Channel Points Redemption as normal user?

I’m using Twurple for a chat app and I’m wanting to get information about channel point redemptions that the user sends along with their message.

Using Twurple chat client i can get the reward id from the msg but no other details come along with it. So i was thinking that i can get information on redemptions using PubSub but it seems i need to be the broadcaster or mod of the channel in order to do that.

Chatterino is able to get channel point redemptions being logged into a channel as a regular user so i am confused about this process. Can anyone enlighten me on how to accomplish this?

Example Code:

const { StaticAuthProvider } = require('@twurple/auth');
const { PubSubClient } = require('@twurple/pubsub');

const twitchClientID = "xxx"
const accessToken = "xxx"

function getTwitchChannelPubSub(channelId) {
    twitchAuthProvider = new StaticAuthProvider(twitchClientID, accessToken);
    const twitchPubSubClient = new PubSubClient({ authProvider: twitchAuthProvider });

    const handleOnRedemption = twitchPubSubClient.onRedemption(channelId, message => {
        console.log(`Received redemption: ${message}`);
    });

    const handleOnListenError = twitchPubSubClient.onListenError(error => {
        const errorMessage = {
            topic: error._topic,
            userId: error._userId,
            callback: error._callback,
        }
        console.error('Error listening to events:n', errorMessage);
    });
}

getTwitchChannelPubSub("23161357") // error sub to lirik
getTwitchChannelPubSub("YOUR_CHANNEL_ID") // no errors

Console Output:

Error listening to events:
{
  topic: 'channel-points-channel-v1.2982838',
  userId: '2982838',
  callback: [Function (anonymous)]
}

Markdown hyperlink

I have these function which work well to convert general markdown to hyperlink:

const parseMarkdownToHTML = (markdownText) => {
    const markdownItems = markdownText.split(';').filter(item => item.trim() !== '');

    return markdownItems.map(item => {
        const regex = /[([^]]+)](([^)]+))/g;
        return item.replace(regex, (match, text, link) => {
            return `<a href='${link}'>${text}</a>`;
        }).trim();
    }).join('; ');
}

console.log(parseMarkdownToHTML(
    "[hyperlink text](https://example.com); [[text] hyperlink text](https://example.com)"
));

My issue is when there’s something like [[text] hyperlink text](https://example.com) it fails to compile into <a href='https://example.com'>[text] hyperlink text</a>;

Any idea what should be improved for the function?

In js, is there any feature can implement callable instance, like __call__ method in python

In python, you can make an instance become a callable obj, like below shows:

# py code snippet

class Demo:
    def __call__(self):
        print("Demo's instance callable")

Demo()()  # Demo's instance is callable

In js, is there the same feature like shown above?

// js code snippet

function Demo1() {}
const d1 = new Demo1();

class Demo2 {}
const d2 = new Demo2();

// can I make d1 or d2 become a callable instance? like d1() or d2() to run some function logic.

Hesapli Bozum ile Nakite Çevirmeler

Bozum Hizmetlerinde 2 yılı aşkın süredir buradayız.
Yaptığımız işlemler;
Pokus bozum,pokus nakite çevirme,hopi dijital bakiye nakite çevirme,yemek kartları nakite çevirme,yemek kartları bozum,kredim bozum,kredim nakite çevirme,hopi bozum,hopi nakite,hopi nakite çevirme,a101 hadi bozum,hadi bozum,hadi veresiye bozum,hadi veresiye nakite çevirme,setcard bozum,setcard nakiye çevirme,multinet bozum,multinet nakiye çevirme,sodexo bozum,sodexo nakite çevirme,paycell bozum,paycell nakite çevirme
pokus bozum
pokus dijital bakiye nakite çevirme

How does the React hook useCallback recognize the function?

I’m learning about React hooks and I have a question about the useCallback hook.

From what I understand, useCallback is useful for creating functions that you want to cache and reuse when the component re-renders (as opposed to creating the function again on every re-render). This is useful when you want to pass the function to a child component as a prop without causing the child component to re-render every time the parent re-renders.

If that’s correct, then here’s my question:

What happens in this scenario:

const handlerFunction = useCallback(() => console.log('I am memoized'), []);

const handlerFunction2 = useCallback(() => console.log('I am memoized'), []);

In the second call to useCallback(), will it recognize the function as the same as that passed to the first call and return the memoized function?

If not, how would it compare the function passed to useCallback() to the memoized function in the cache upon re-rendering?

next-auth CredentialsProvider returning strange error

so I’ve been using next-auth for a couple years now and am trying to dive into using the CredentialsProvider option for email/password authentication. I’m relatively new to import x from "y" as opposed to const x = require("y") so I’m not sure if it’s an error there or what, but I’m receiving the following error –

⨯ pages/api/auth/[...nextauth].js (12:9) @ CredentialsProvider
 ⨯ TypeError: next_auth_providers_credentials__WEBPACK_IMPORTED_MODULE_1__ is not a function
...  10 |     },
  11 |     providers: [
> 12 |         CredentialsProvider({
     |         ^
  13 |             name: 'Credentials',
  14 |             credentials: {
  15 |                 email: { label: "Email", type: "email" },

My code for reference:

import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { connect } from '../../../utils/db/connect';
import { verifyPassword } from '../../../utils/hashing/verifyPassword';

export default NextAuth({
    session: {
        jwt: true,
        maxAge: 30 * 24 * 60 * 60
    },
    providers: [
        CredentialsProvider({
            name: 'Credentials',
            credentials: {
                email: { label: "Email", type: "email" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const { email, password } = credentials;
                const { db  } = await connect();

                const users = db.collection('users');
                const user = await users.findOne({ email });

                if (!user) {
                    throw new Error('No user found');
                }

                const isValid = await verifyPassword(password, user.password);

                if (!isValid) {
                    throw new Error('Invalid email or password');
                }

                return { id: user._id, name: user.name, email: user.email };
            }
        })
    ],
    pages: {
        signIn: '/auth/login',
    },
    callbacks: {
        async jwt(token, user) {
            if (user) {
                token.id = user.id;
            }

            return token;
        },
        async session(session, token) {
            session.user.id = token.id;
            return session;
        }
    }
})

If you’ve got any idea what I’m doing wrong, please let me know!

Next.js won’t update the page after changes to script

I am following the Next.js tutorial. On chapter 1, I am supposed to add “import ‘@/app/ui/global.css'” to the top of the layout.tsx script. I did this and after running pnpm dev it would only show the previous version and not the newly updated page. After tinkering with visual studio code for about an hour I got it to update to have the CSS in it when I ran pnpm dev again. I thought this would be the end but once again when I made changes to the script and it did not update. This time I tried adding a black triangle to the page, I also had a log in my layout.tsx file saying “DO YOU WORK” before to check if the page updated. I removed this log when I added the triangle and its still printing “DO YOU WORK” in the console so I know the page isn’t updating. Note: I do not know how I got the page to update for the global.css, I was just repeatedly opening and closing visual studio code until something worked.

I have tried restarting my computer, using npm run dev instead of pnpm dev, deleting the .next folder. None of these things have done anything to fix the issue. When I got the global.css to update I ran pnpm dev in the parent of the root directory by accident, which expectedly caused an error. After that I changed to the root directory and did pnpm run dev and it updated. However I believe that it was a coincidence since I am not able to replicate it.