can’t connect mongodb to node js

I have just started learning about MongoDB and I am trying to host my Node.js application locally via MongoDB Server 6.0 (without using Mongoose or Atlas).

I copied the async JavaScript code given in the MongoDB documentation. I made sure to run mongod before executing the code app.js

this is when i run mongod

this is when i run mongod

and then when i run node app.js in my terminal nothing is being shown in my terminal.

this is my app.js code

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);
  
  // Call the function to insert documents after connecting
  insertDocuments(db, function() {
    // Close the client after finishing database operations
    client.close();
  });
});

const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('fruits');
  // Insert some documents
  collection.insertMany([
    {a : 1},
    {a : 2},
    {a : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
}

and this is what’s happening when i run node app.js:

node app.js

it is not getting connected

Graph.js does not apply my options setting

I have tried using lots of suggested things but nothing is working
I am trying to start y-axis from 0 but if there is only one data (one label and one data) it gives value on axis from example image -1 to 1 Which I am trying to avoid. If there is multiple data See Image still it is not starting from 0

Below jsDelivr I am using
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>

I have also tried below CDN it did not work
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.min.js

My frontend is in ejs

Below is the function I am using to create and manipulate chart

function updateChart(lables, data, id, datasetLbl) {
    let date = moment();
    date = date.format('YYYY/MM/DD');

    const ctx = document.getElementById(id).getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: lables.length < 1 ? [date] : lables, // Assuming each data point has a label
            datasets: [
                {
                    label: datasetLbl,
                    data: !data.length ? [0] : data, // Assuming each data point has a value
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1,
                },
            ]   ,
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                    suggestedMin: 0,
                    stepSize: 1
                },
                x: {
                    display: true,
                },
            },
        },
    });
}

I have tried lots of things

options: {
            scales: {
                y: {
                    beginAtZero: true,
                    // min: 0,
                    //suggestedMin: 0,
                    ticks:{
                        //here also I have tried to define suggestedMin and min but did not work
                    },
                },
                x: {
                    display: true,
                },
            },
        },

Nothing is affecting not stepsize not min every option has no effect on my chart

I don’t know how to solve it

What is the point of appending “g “elements to svg when only one attribute is being chained in the grouping?

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

How does this differ from

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

My understanding is that “g” is supposed be a grouping of different svg elements. But what’s the point of appending g when there’s only one proceeding attribute (“transform,”translate”)

Uncaught ReferenceError: getChecked is not defined using Webpack Bundler

I am using the Webpack bundler to bundle my code, but I get an error saying my getChecked() function is not defined when I run my html page in a browser even though getChecked() is defined and included in the bundle. Uncaught ReferenceError: getChecked is not defined at HTMLButtonElement.onclick ((index):36:71)

Here is how my project is organized: I have one file “getAPIToken.js” which gets an API token through a function called fetchToken(). I have another file “fetchSymptoms.js” which imports fetchToken() and uses it to get the token and display some data. “fetchSymptoms.js” defines the function getChecked(), which executes when a button is clicked. “fetchSymptoms.js” is the entry point to my webpack bundler.

I’m not sure how to make getChecked() be recognized in my browser. Do I need some sort of html plugin included in my webpack.config file? I have been super stuck on this for the past two weeks, so any help would be greatly appreciated!

The function getChecked() is defined in fetchSymptoms.js as follows:

 import { fetchToken } from './getAPIToken.js';
    

    fetchToken()
    .then(token => {
        fetchAdultMaleSymptoms(token);
        //fetchSymptoms(token);
    })
    .catch(error => {
        console.error('Error in fetchSymptoms ', error);
    });


function getChecked(){ //displays symptoms from checked checkboxes
    //alert("hello!");
    const checkboxes = document.getElementsByName("symptom"); //items contains nodelist with the checked symptoms
    const array=[]; //create empty array

    for (var i = 0; i < checkboxes.length; i++){ //run through the nodelist
        if (checkboxes[i].type == "checkbox" && checkboxes[i].checked == true){
            if (!array.includes(checkboxes[i].value)){ //if the symptom is not already in array, then push
                array.push(checkboxes[i].value); //add checked items to array
            }
        }
    }

    const jsonArray = JSON.stringify(array); //converts to json string
    sessionStorage.setItem("checked", jsonArray); //will disappear when browser window closed, can use localStorage
}

So the function is defined, and then eventually bundled since fetchSymptoms.js is the entry point. Here is how I use getChecked() in index.html. When run in my browser, index.html gives me errors saying uncaught getChecked() not defined.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/css/index.css" rel="stylesheet">
    <title>Prognosis Pal</title>
   
    <script src="bundle.js"></script>
    <script src="/js/fetchSymptoms.js"></script>

    <script src="/js/displayCategories.js"></script>
    <!-- <script src="/js/diagnosisSymptoms.js"></script> -->
    
</head>

<body>
    <a href="/you"><button class="you-button">You</button></a>

    <h1>PrognosisPal</h1>

    <div>Select all symptoms that apply</div>

    <div class="symptoms-container">
        <form action="#" id="symptomForm">  
            <div id="ul-container"></div>
            <!-- Symptoms used come from API -->
        
        </form>
    </div>

    <!-- getChecked() gets the values that the user selects for symptom checkboxes-->
    <a href="/diagnosis"><button type="submit" onclick="getChecked()">Diagnosis Me!</button></a>
</body>
</html>

And finally, here is my webpack.config file:

const path = require('path');
//require('dotenv').config({ path: './functions/.env' }); 
const Dotenv = require('dotenv-webpack');


module.exports = {
  entry: './public/js/fetchSymptoms.js', //entry point of your application ./public/js/getAPIToken.js
  output: {
    filename: 'bundle.js', //output bundle filename, where result is going to go
    path: path.resolve('public'), //output directory
  },
  mode: 'none',
  module: {
    rules: [
      {
        test: /.js$/, // Match JavaScript files
        exclude: /node_modules/, // Exclude node_modules
        use: {
          loader: 'babel-loader', // Use Babel to transpile JavaScript
          options: {
            presets: ['@babel/preset-env'] // Use the preset for modern JavaScript
          }
        }
      }
    ]
  },
  plugins: [
    new Dotenv(),
  ],
  resolve: {
    extensions: ['.js'],
    alias: {
      'crypto-js': path.resolve(__dirname, 'node_modules/crypto-js'),
    },
  },
};

I’m not sure how to make getChecked() be recognized in my browser. Do I need some sort of html plugin included in my webpack.config file? I have been super stuck on this for the past two weeks, so any help would be greatly appreciated!

Uncaught TypeError: (0 , _contexts_AuthContext__WEBPACK_IMPORTED_MODULE_4__.useAuth) is not a function

I’m trying to call the useAuth() function from AuthContext.tsx in my Navigation.tsx but I get an error saying my useAuth is not a function. Here are the steps I have taken to debug:

  • Wrapping/Scope: AuthProvider is put where Navigation will be placed within (layout.tsx)
  • Import/Export: useAuth is imported using curly brackets and is exported as a function.

I’m not sure where this issue is coming from.

// AuthContext.tsx
"use client"
import { createContext, useContext, useState, ReactNode } from "react";

interface AuthProviderProps {
    children: ReactNode;
}

interface AuthContextType {
    isAuthenticated: boolean;
    login: () => void;
    logout: () => void;
}

// Create context
const AuthContext = createContext<AuthContextType | undefined>(undefined)

export const useAuth = () => {
    const context = useContext(AuthContext)
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }: AuthProviderProps) => {
    const [isAuthenticated, setIsAuthenticated] = useState(false)

    const login = () => {
        setIsAuthenticated(true)
    }

    const logout = () => {
        setIsAuthenticated(false)
    }

    return (
        <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
            {children}
        </AuthContext.Provider>
    );
};
// Navigation.tsx
import React from 'react';
import Link from 'next/link';
import { navCategories } from '../config/navData';
import { useAuth } from '@/contexts/AuthContext';

export default function Navigation() {
    console.log(useAuth)
    const {isAuthenticated, login, logout} = useAuth();

    return (
        <nav className='bg-white border-b border-gray-200 py-4 shadow-sm'>
            <ul className='flex justify-center space-x-10'>
                {navCategories.map((category) => (
                    <li key={category.label} className='text-gray-600 hover:text-blue-600'>
                        <Link href={category.href}>
                            <span className='text-md font-semibold tracking-wide transition-colors duration-300'>
                                {category.label}
                            </span>
                        </Link>
                    </li>
                ))}
            </ul>
        </nav>
    )
}
// layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Navigation from "../components/Navigation"
import { AuthProvider } from "@/contexts/AuthContext";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
    title: "Create Next App",
    description: "Generated by create next app",
};

export default function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <AuthProvider>
            <html lang="en">
                <body className={inter.className}>
                    <Navigation />
                    {children}
                </body>
            </html>
        </AuthProvider>
    );
}

HTML: Display only loading spinner for and hide other controls when specify controls attribute

I’m writing a custom video player that have custom play/pause/next button, etc. I want to display a loading spinner for my player but the only way I could come up with is to use controls attribute. Doing so my video can display a loading spinner but the other controls will be shown together with the spinner.
Is there a way to show only the spinner?

UNABLE TO CONNECT TO Database in netbeans :Unable to load class: org.gjt.mm.mysql.Driver from ClassLoader:ParallelWebappClassLoader

I transfered a netbeans project from my server to my local laptop .
When I am trying to run the project, it is giving this error. I have connected the db manually in netbeans too and it got connected.But while running the project it is giving this error. plz help me.
HTTP Status 500 – Internal Server Error
Type Exception Report

Message An exception occurred processing [/modules/dboardMgmt/prodList.jsp] at line [24]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing [/modules/dboardMgmt/prodList.jsp] at line [24]

21: String sql = “select PRODUCT_NAME,ID from TOTDASHB_PRODUCTS ”
22: + “where TECHNOLOGY_ID in (select ID from TOTDASHB_TECHNOLOGIES where TECHNOLOGY_NAME='” + TechName + “‘)”;
23: System.out.println(“sql is ::” + sql);
24: ArrayList<ArrayList> result = database.read(sql);
25:
26: int counti = 0, i = 0;
27: int count = result.size();

Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:605)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:488)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:383)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:331)
javax.servlet.http.HttpServlet.service(HttpServlet.java:583)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
Root Cause

javax.servlet.ServletException: DBError : Error getting database connection : Unable to load class: org.gjt.mm.mysql.Driver from ClassLoader:ParallelWebappClassLoader
context: TOTDashboard
delegate: false
———-> Parent Classloader:
java.net.URLClassLoader@20c684
;ClassLoader:ParallelWebappClassLoader
context: TOTDashboard
delegate: false
———-> Parent Classloader:
java.net.URLClassLoader@20c684

org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:907)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:833)
org.apache.jsp.modules.dboardMgmt.prodList_jsp._jspService(prodList_jsp.java:405)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:583)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:383)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:331)
javax.servlet.http.HttpServlet.service(HttpServlet.java:583)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

Root Cause

DBError : Error getting database connection : Unable to load class: org.gjt.mm.mysql.Driver from ClassLoader:ParallelWebappClassLoader
context: TOTDashboard
delegate: false
———-> Parent Classloader:
java.net.URLClassLoader@20c684
;ClassLoader:ParallelWebappClassLoader
context: TOTDashboard
delegate: false
———-> Parent Classloader:
java.net.URLClassLoader@20c684

com.cdot.nms.csmp.MYSQLDBManager.connect(MYSQLDBManager.java:428)
com.cdot.nms.csmp.MYSQLDBManager.read(MYSQLDBManager.java:463)
com.cdot.nms.csmp.MYSQLDBManager.read(MYSQLDBManager.java:439)
org.apache.jsp.modules.dboardMgmt.prodList_jsp._jspService(prodList_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:583)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:383)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:331)
javax.servlet.http.HttpServlet.service(HttpServlet.java:583)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

Plz help me to remove this internal server error

confirm route button not working but cancel button is

I am struggling to solve, what might be a simple problem.

Working in JS and using leaflet framework. In the routeConfirmationDialog box I have two buttons “Confirm route” and “cancel”. Cancel button works. Confirm route does not work.

When I inspect in Firefox , I get an error like “undefined”.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Emergency Services Simulation</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <link rel="stylesheet" href="ambulance.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine/dist/leaflet-routing-machine.css" />
</head>

<body>

<div id="mapid"></div>

<div id="routeConfirmationDialog">
    <p id="routeDetails">Route details will appear here.</p>
    <button onclick="confirmRoute()">Confirm Route</button>
    <button onclick="cancelRoute()">Cancel</button>
</div>

<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-routing-machine/dist/leaflet-routing-machine.js"></script>
<script src="ambulance.js"></script>

</body>
</html>

.JS section:

// Adjusted addRoute function to manage routes more dynamically
function addRoute(fromLatlng, toLatlng) {
    // Remove the previous route from the map if it exists
    if (currentRouteControl) {
        mymap.removeControl(currentRouteControl);
    }

    currentRouteControl = L.Routing.control({
        waypoints: [
            L.latLng(fromLatlng),
            L.latLng(toLatlng)
        ],
        routeWhileDragging: false,
        createMarker: function() { return null; }, // No markers at waypoints
        router: L.Routing.osrmv1({
            serviceUrl: `https://router.project-osrm.org/route/v1`
        }),
        lineOptions: {
            styles: [{color: '#ff615f', opacity: 1, weight: 5}] // Customize the route appearance
        },
        show: false, // Initially don't show route instructions
    }).addTo(mymap);

    currentRouteControl.on('routesfound', function(e) {
        var routes = e.routes;
        var summary = routes[0].summary;
        // Update the route details in the custom UI
        document.getElementById('routeDetails').innerHTML = `Distance: ${Math.round(summary.totalDistance / 1000 * 100) / 100} km, Time: ${Math.round(summary.totalTime / 60)} minutes. Confirm this route?`;
        // Show the custom UI
        document.getElementById('routeConfirmationDialog').style.display = 'block';
    });
}

function confirmRoute() {
    // Proceed with route animation
    animateMarkerAlongRoute(currentRouteControl.getWaypoints()[0].latLng, 10000); // Adjust as needed
    document.getElementById('routeConfirmationDialog').style.display = 'none';
}

function cancelRoute() {
    // Remove the current route from the map
    if (currentRouteControl) {
        mymap.removeControl(currentRouteControl);
        currentRouteControl = null;
    }
    document.getElementById('routeConfirmationDialog').style.display = 'none';
}

// Mockup function to animate marker along route - adjust based on actual data structure
function animateMarkerAlongRoute(coordinates, duration) {
    // This example assumes 'coordinates' is an array of [lat, lng] pairs
    var index = 0;
    var ambulanceMarker = L.marker(coordinates[0], {icon: emergencyIcon}).addTo(mymap); // Use an appropriate icon
    var interval = setInterval(function() {
        if (index < coordinates.length) {
            ambulanceMarker.setLatLng(coordinates[index]);
            index++;
        } else {
            clearInterval(interval);
        }
    }, duration / coordinates.length);
}

I first choose an Emergency then the hospital. Then confirm or cancel route.

I have tried to find this specific error online but nothing pops up. Is the error the actual button or is it th fact that my OSRM is just a demo.

Change div opacity in Angular

So I’m trying to do an animation that moves the divs and fades them based on the scroll distance. I’ve got the transform working,but the opacity change only appears to work on desktop. When viewing it from my mobile device (iOS safari, and iOS firefox) the opacity doesn’t change, and I cannot figure out why. These animations also appear choppy when scrolling on mobile, but not on desktop.

@HostListener('window:scroll', ['$event'])
@HostListener('window:touchmove', ['$event'])
onScroll(): void {
  if (this.isEffectActive) {
    /* get position of the bottom of the component */
    const introductionContainerBottomPos =
      this.elementRef.nativeElement.offsetTop +
      this.elementRef.nativeElement.offsetHeight;
    const scrollPos = window.scrollY;
    const distance =
      introductionContainerBottomPos -
      this.clamp(scrollPos, 0, introductionContainerBottomPos);
    const val = this.lerp(0, 1, distance / introductionContainerBottomPos);

    this.fadeValue = Math.round(val * 100) / 100;

    window.requestAnimationFrame(() => {
      this.container.nativeElement.style.opacity = this.fadeValue;
      this.container.nativeElement.style.transform = `translateY(${this.getTranslation()}px)`;

      this.container2.nativeElement.style.opacity = this.fadeValue;
      this.container2.nativeElement.style.transform = `translateY(${this.getTranslation()}px)`;
    });
  }
}

Anyone know a better solution?

I’ve tried changing the filter: alpha but that didn’t work. I tried inlining the opacity, but that doesn’t work either.

Browser – How to get the original RGB values from a RGBA image?

Background

As of now, whenever browser load a RGBA image, it corrupts RGB channels if alpha is not 255;
the original RGB values would be completely lost in case alpha is 0.

This weird behavior would apply to all img and canvas elements, and most browser implement image loading in this way. It seems that this was some sort of web standard, although I could not find where states such standard.

Problem Formulation

I am working on a simple web tool that removes background from a image then outputs transplant RGBA image using opencv-js. The background removing algorithm from opencv would require heavily manual annotations, thus I plan to support loading images with alpha channel so that user could load work-in-progress images from the previous output.

The problem is the loading process. I am following opencv-js guide and load images via:

document.getElementById("image").src = file; // Load image file to a <img> element.
cv.imread(document.getElementById("image")); // Load image from the <img> element.

However, this only works when there is no alpha channel in the image. Because of the weird behavior that how browser loads the image, some pixels could lose their RGB values if the image contains an alpha channel.

My problem is that:

  • Is there any way to get the original RGB values from a loaded file without writing an external image loader?
  • Is there any way to ignore the alpha channel of the loaded file?

Many thanks.

How to send the firebaseConfig file to deploy on Vercel?

I created a project integrated with Firebase but I don’t know how to send the private settings to deploy on Vercel.

I want to send these configurations to deploy on vercel:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: ""
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth(app);

I tried using environment variables but they didn’t work. I believe it was the way I configured it.

const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID
};

After leaving the firebaseConfig file like this, I configured the environment variables in Vercel by passing the real values.

Environment Variables Vercel – Image

When I go to do something Firebase-related, I get this error on the console:

@firebase/firestore: Firestore (10.8.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: Permission denied: Consumer ‘project:undefined’ has been suspended.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

How to fix countdown

how to fix bug in this code?

  const cek: any = localStorage.getItem("detail");
  const [dataUjian, setDataUjian] = useState<any>(JSON.parse(cek));
 
  const initialTime = Number(moment.utc(dataUjian.startTime).local()) * 60;
  const durasi = dataUjian.duration * 60000;
  const currentTime = Date.now();
  const timeDifference = initialTime + durasi - currentTime;
  const [time, setTime] = useState<number>(
    timeDifference > 0 ? Math.floor(timeDifference / 60) : 0
  );

  console.log(moment(time).format("HH:mm:ss"), "time");


const [isActive, setIsActive] = useState(true);
  let countdownInterval: NodeJS.Timeout | undefined;
  const formatTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;

    console.log(`${hours}h ${minutes}m ${remainingSeconds}s: formatTime`);
    return `${hours}h ${minutes}m ${remainingSeconds}s`;

  };

  const resetCountdown = () => {
    setIsActive(false);
    setTime(initialTime);
  };

  useEffect(() => {

    if (isActive) {
      countdownInterval = setInterval(() => {
        if (time > 0) {
          setTime((prevTime) => prevTime - 1);
        } else {
          setIsActive(false);
          clearInterval(countdownInterval);
          resetCountdown();
          navigate(-1);
        }
      }, 1000);
    } else {
      if (countdownInterval) {
        clearInterval(countdownInterval);
      }
    }

    return () => {
      if (countdownInterval) {
        clearInterval(countdownInterval);
      }
    };
  }, [isActive, time]);

I want the countdown to function properly, namely by counting backwards, but in my code it still doesn’t work well, I’ve tried various methods, such as asking chatgpt and Google still haven’t found a bright spot.

Inquirer doesn’t wait for input after prompt

For some reason, after prompting, inquirer does not wait for user input and directly moves to the next command line. Here’s my code:


import inquirer from 'inquirer';

var link;
// const inquirer= require('inquirer');

inquirer
  .prompt([
    {message:"add link", name:"URL"}
  ])
  .then((answers) => {
    console.log(answers);
    // Use user feedback for... whatever!!
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });

import qr from 'qr-image'
import fs from 'fs'
var qr_svg = qr.image(link, { type: 'svg' });

fs.writeFile('user_input.txt',link,(err)=>{
    if(err){throw err;}
})

How do I fix this? This is happening even in the node terminal, and vs code. All my packages including node and npm are latest, even the modules are latest. What is causing the issue?

I was trying to generate a prompt, to which the user would reply with a link which would then be printed on screen. Instead, the prompt is generated, and instead of waiting for the input, the control jumps to the new command line.

Slides Transition using Javascript and Python

I have a database table with images and I want to display it using slides. The problem I encountered here is that it only shows one image and then just fades away. How can I display the other images too?

views.py

def dashboard(request):
    image = Events.objects.all()
    return render(request, 'dashboard-events.html', {'image': image})

dashboard-events.html

<div class="slider" role="listbox">
    <div class="slider-inner">
        {% for slides in image %}
        <div class="slides {% if forloop.first %} active{% endif %} fade">
            <img src="{{ slides.image.url }}">
            <div class="slide-caption">
                 {{ slides.title }}
            </div>
        </div>
        {% endfor %}
   </div>
   <div class="slider-buttons">
       <button class="prev" type="button" onclick="plusSlides(-1)">
       <button class="next" type="button" onclick="plusSlides(1)">
   </div>
</div>

script

var timer;
var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("slides");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  slides[slideIndex-1].style.display = "block";

  clearTimeout(timer);
  timer = setTimeout(() => plusSlides(1), 2000);
  }