I cannot connect to mongoDB through my college internet that uses a proxy. Help me

enter image description here
My college uses a proxy server and i think it is the reason for me not being able to connect to the server. I have whitelisted my ip address and also added 0.0.0.0 to the network access list. I cannot use a different internet connection as the mobile service is not good. How can i fix it? Please help me as i need it for my college project

Tried adding my ip to mongo DB

getBoundingClientRect function sometimes can not get the true width and height

Like in react dialog component, you set up it’s inner component data with setTimeout 100ms delay, and you use ResizeObserver to get it’s inner component size attribute. The target getBoundingClientRect can not get the true size while offsetWidth can. I run the getBoundingClientRect in the requestAnimationframe and I can see the two results has some difference.

So What lead to this result? I think getBoundingClientRect should stuck the js thread and reflow and return the true result as when we read offsetWidth.

How do you think about that.

regex for list of users except the user fetching it?

Below is the code in which the filter is the query parameter at the endpoint bulk and we use this filter that user has typed in his dashboard, this filter should fetch all the users he filtered through his filter from all users except the user himself but now it fetches all of it(his user including) ???

router.get("/bulk",async (req, res) => {
  const filter = req.query.filter || "";

  const users = await User.find({
    $or: [
      {
        firstName: {
          $regex: filter,
        },
      },
      {
        lastName: {
          $regex: filter,
        },
      },
    ],
  });
  

  res.json({
    user: users.map((user) => ({
      username: user.username,
      firstName: user.firstName,
      lastName: user.lastName,
      _id: user._id,
    }))
  });
});

, tried to use .filter in .map but doesnt work, other regex failed too

What methods exist to copy a gif to the clipboard and post it into other applications?

I want to (programmatically) copy a gif to the clipboard such that I can paste it into modern chats like those of MS Teams or Discord.

There seem to be some “magic” happening in the backgroud when you do a "right-click => copy" that I haven’t yet figured out.

For example, this gif from reddit (also those of tenor) can be copied to both Teams and Discord.
This from giphy works on Teams, but not on Discord. On Discord it’s interpreted as a png object.
If I open a local gif file in the browser and copy it to the clipboard it’s also interpreted as a png by Discord while nothing happens in Teams.

This awesome stackoverflow comment explains how to use different APIs for clipboard access – with ClipboardItem still not being available in Firefox, and document.execCommand('copy') being deprecated.

However, with gifs there seems to be something extra needed to make it work with gifs. Does anyone know what?

Are next.js server-side database connections long-lived?

I have been using Next.js for a while and realized I am missing a core piece of understanding relating to how the framework actually operates under the hood, as it relates to server-side code.

Background

Next.js has three categories of code that runs server side (as far as I know):

  1. Code in Server Components (e.g. a normal async page component). It is possible to fetch external data in these server components. The code will never be executed by the browser.

  2. Code in Route Handlers (previously called API Routes). This code is executed when a machine (typically client side code in the browser) sends a request to the handler’s URL. Route Handlers are executed by app host (e.g. Vercel) on demand, in a node.js server environment. That server is started on-demand, whenever the function runs, thus there is a small lag to run these functions. This way of running functions is called “serverless”, because we do not need to run and manage our own server to execute them. Vercel, for instance, can execute these from a central server (e.g. in the US), or from one of many servers around the world (called the edge) that runs smaller and faster versions of the node.js runtime (called the edge runtime).

  3. Finally, Server Actions also execute server-side, in a node.js environment. They are similar to Route Handlers, in that they are “serverless” (called by client-side code in the browser, resulting in a server booting up to run the code and then shutting down).

As I was looking into Prisma, I read that the Prisma Client either establishes long-lived connections to a database, or short-lived connections. See: https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/databases-connections

Question

It is clear to me that Route Handlers and Server Actions will spawn short-lived node.js servers and thus create a new Prisma Client object per function call. As such, these Prisma database connections are short-lived, meaning the Prisma Client object only lives for the duration of the function call.

Firstly, is my above understanding correct?

Secondly, if we contact our database in a normal server component in a dynamic route (i.e. SSR, not SSG), will that be a short-lived node.js execution, or does that node.js environment persist / live over time (so Prisma Client objects are actually long-lived in that scenario)?

How to preserve scroll position on the first page when navigating back from another page in React.js?

Let’s say I have two pages/two routes. In one I have a <Link> component:

<Link to="/something">
    <Button>
        This is Link
    </Button>
</Link>

In the second, I can go back to the previous route:

const handleGoBack = () => {
    navigate(-1);
};

return (

    <Button onClick={handleGoBack}>
        Back
    </Button>
);

What is the best way to save the position of the first page to where I clicked that <Link> component, so that when I navigate back from another page, I should return to the exact position I clicked the link from?

I tried adding this to the first component:

function storeScrollPosition() {
    sessionStorage.setItem('scrollPosition', window.scrollY.toString());
}

And then I use that in the <Link> as onClick action:

<Link to="/something" onClick={storeScrollPosition}>
    <Button>
        This is Link
    </Button>
</Link>

, while doing all logic in useEffect in the second component:

useEffect(() => {
    const scrollPosition = sessionStorage.getItem('scrollPosition');
    if (scrollPosition) {
        window.scrollTo(0, parseInt(scrollPosition));
        sessionStorage.removeItem('scrollPosition');
    } else {
        window.scrollTo(0, 0);
    }
}, []);

But it seems that it’s not working perfectly. Sometimes it works, sometimes it doesn’t work. I don’t know, but I think it has something to do with page rendering. Is there by chance any better way to do this?

*I use react-router-dom for navigation.

node.js Error. prompt is not defined. How would I fix this?

I was trying to insert a record in the table of employees, then I got this error in node.js(vs code).
So, I googled it and he said, “Prompt and window are not defined in the node environment.”
What does that mean? Can’t I use a prompt in node.js?

This is my code:

const mysql = require("mysql");

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "crud"
});

con.connect((error)=>{
    if(error)
        throw(error);
    console.log("Connected to dataBase");

let id = prompt("Enter id: ");
let name = prompt('Enter employee name: ');
let sal = prompt('Enter sal: ');

var sql = "INSERT INTO employee (e_id, e_name, e_sal) VALUES ("+Number(id)+ ", '"+name+"','" +Number(sal)+ "')";

con.query(sql, (err, result)=>{
    if(err) throw err;
    console.log("1 record successfully inserted in the table.");
});
});

Error: Cannot find module ‘@/lib/validators/query-validator’

I’ve been adhering to a tutorial, and upon completing it, I attempted to run the project one last time. However, I encountered an error. I’ve included the tutorial link for reference: (https://www.youtube.com/watch?v=06g6YJ6JCJU&t=485s). I’ve already attempted restarting the development server, but it hasn’t resolved the issue. Any suggestions on what steps I should take next?

Looking for a specific Prettier option

Looking for a Prettier option.

I’m trying to figure out if there is a possibility to format code like this and not wrap the first attribute to a new line:

<div class="test-class"
     [test-binding]="true"
     (test-binging)="test()"
     any-attr>
</div>

Attributes in one column is a desired behaviour (I suppose it’s “singleAttributePerLine” option), but default behaviour wraps first attribute to a new line:

<div
  class="test-class"
  [test-binding]="true"
  (test-binging)="test()"
  any-attr>
</div>

Haven’t found any options responsible for moving the first attribute to a new line in docs:
https://prettier.io/docs/en/options

I’ve tried several options like “printWidth” and “singleAttributePerLine” but they are about other format stuff

js animate() method not working as expected

I am making a animated wheel for my project and it is supposed to work like this:
the user clicks the next button and with an animation the wheel turns 90 degrees and an item will appear, I must say that each of these 4 items are placed on the wheel and no js code is applied on them, the code’s job is jusr to turn the wheel in the direction that the user clicks on. The code works fine on a single direction, however when you click on the opposingg direction there’s a jump, and with the second click on the same direction the animation plays just as expected.

HTML:

<body>
<div class="drinks-wheel-section">
    <div class="drinks-wheel">
        <div class="drinks-wrapper wrapper1">
            <div class="drink-picture --1"></div>
            <div class="drink-picture --2"></div>
        </div>
        <div class="drinks-wrapper wrapper2">
            <div class="drink-picture --3"></div>
            <div class="drink-picture --4"></div>
        </div>
    </div>
    <div class="name-and-change">
        <span class="previous">< </span>
        <p class="drink-name"></p>
        <span class="next">></span>
    </div>
</div>
    <script src="s.js"></script>
</body>

CSS:


.drinks-wheel-section{
    width: 100%;
    height: 80vh;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 4rem;
    position: relative;
}

.drinks-wheel{
    width: 30rem;
    height: 30rem;
    border-radius: 50%;
    position: relative;
}

.drink-picture{
    width: 7rem;
    height: 7rem;
}
.--1{
    background-color: aqua;
}

.--2{
    background-color: darkblue;
}

.--3{
    background-color: black;
}

.--4{
    background-color: brown;
}

.drinks-wrapper{
    width: 100%;
    height: 7rem;
    position: absolute;
    display: flex;
    justify-content: space-between;
    gap: 1rem;
}


.wrapper1{
    top: 37%;
    left: 0%;
}

.wrapper2{
    rotate: 90deg;
    top: 38%;
    left: 0%;
}

.name-and-change{
    width: 15%;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    position: absolute;
}

.next,.previous{
    font-size: 2rem;
    cursor: pointer;
}

JS:

const $ = document
const previousBtn = $.querySelector(".previous")
const nextBtn = $.querySelector(".next")
const CurrentDrinkName = $.querySelector(".drink-name")
const drinksWheel = $.querySelector(".drinks-wheel")

let rotateAmountFrom = 0
let rotateAmountTo = 0

function showNextOrPreviousDrink (e){
    if(e.target.classList.contains("previous")) {
        rotateAmountFrom = rotateAmountTo
        rotateAmountTo = rotateAmountTo + 90
        let animationRotate = [
            {rotate: rotateAmountFrom + "deg"},
            {rotate: rotateAmountTo + "deg"},
        ]
        drinksWheel.animate(animationRotate,{fill: "forwards",duration:800,})
    
    } else {
        rotateAmountFrom = rotateAmountTo
        rotateAmountTo = rotateAmountTo + 90    
        let animationRotate = [
            {rotate: "-" + rotateAmountFrom + "deg"},
            {rotate: "-" + rotateAmountTo + "deg"},
        ]
        drinksWheel.animate(animationRotate,{fill: "forwards",duration:800,})

    }
    console.log(rotateAmountFrom,rotateAmountTo,)
}
nextBtn.addEventListener("click",showNextOrPreviousDrink)
previousBtn.addEventListener("click",showNextOrPreviousDrink)

React Quiz App: Issue with Displaying Correct Score on Quiz Completion

Question:

I am currently working on a React quiz app where users can answer multiple-choice questions and receive feedback on their answers. The app is functioning well for the most part, but I am encountering an issue with the final score display when the quiz is completed.

Here is the relevant portion of the code:

// ... (Rest of the imports)

function App() {
  // ... (State variables and initializations)

  const handleSubmission = () => {
    if (selectedOption === questions[currentQuestionIndex].correct && currentQuestionIndex < questions.length - 1) {
      setScore((prevScore) => prevScore + 1);
      setFeedback('Correct!');
    } else {
      setFeedback('Incorrect!');
    }

    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    } else {
      setFeedback(`Quiz Complete! You scored ${score} out of ${questions.length}!`);
    }
  };

  // ... (Rest of the component)

  return (
    <div style={style.container}>
      {/* ... (JSX structure) */}
    </div>
  );
}

export default App;

The issue arises when the quiz is completed, and the final feedback displays an incorrect score, even if all the answers were correct. I suspect this is due to the asynchronous nature of the setScore function.

I’ve tried incorporating the useEffect hook to update the feedback after the score changes, and also using the state update callback in setScore, but the problem persists.

Any insights into resolving this issue and ensuring that the final score is accurately displayed would be greatly appreciated.

Code is replacing the dates in date fields, but that isn’t changing the BI webpage table filters

I am trying to write a javascript code to run in Power Automate, to change dates (variables) on a Power BI Report webpage. The date fields do reflect the dates from the code, however they do not seem to ‘work’ and the BI table does not filter accordingly.

I tried the following code, my expectation is to have it update the dates in in date fields in a way that the BI tables get filtered too.

function ExecuteScript() {
//sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}
// Usage of the sleep timer
sleep(100).then(() => {
//assign variables to access iframe elements
var iframe = document.getElementsByTagName('iframe')[0];
var fromdate = iframe.contentWindow.document.querySelectorAll('div input[type="text"]')[0];
var todate = iframe.contentWindow.document.querySelectorAll('div input[type="text"]')[1];
var plant = iframe.contentWindow.document.getElementsByTagName("span")[9];
//enter dates and choose plant
fromdate.value = '%fromdate%';
todate.value = '%todate%';
plant.click();
});
}
<input _ngcontent-tdb-c185="" autocomplete="off" type="text" class="item-fill ng-untouched ng-pristine ng-valid date-slicer-input enable-hover" id="700145b9-c237-22d2-f54c-a617efa32e18" placeholder="" aria-description="Enter date in M/d/yyyy format" aria-label="Start date. Available input range 11/8/2022 to 2/10/2024" style="color: rgb(37, 36, 35); text-decoration: none;">

These are the date fields

Delay before MediaRecorder starts recording audio in Firefox

In a bare-bones demo, I find that there is a 1.5 second delay before MediaRecorder starts recording audio, on Firefox only.

Please find below a snippet that works well with MediaRecorder on Chrome, Opera and Edge. Apparently MediaRecorder is blocked when the snippet runs on Stack Overflow, so you can test it here. You can find the same code on GitHub, with a demo here.

On Safari, there is also a delay, but for a different and more manageable reason: the promise that eventually resolves to a user media stream takes longer than in other browsers, but once the stream is available, recording can begin immediately. It is therefore possible to indicate to the end-user that recording has started.

On Firefox, the user media stream is available immediately, and an icon appears in the menu bar immediately in the menu bar to indicate that the microphone is busy. It seems that the stream starts flowing, but there is no data from the microphone for over a second. Recording only starts after about 1.5 seconds, when a second (yellow) icon appears in the menu bar. The recorded audio begins with 1.5 seconds of silence.

Is this due to a mistake in the way I am using MediaRecorder, or do I need to take some specific action on Firefox?

const startRecording = document.getElementById("startRecording")
const stopRecording = document.getElementById("stopRecording")
const playBack = document.getElementById("playBack")
const feedback = document.getElementById("feedback")

startRecording.addEventListener("click", startRecorder, false)
stopRecording.addEventListener("click", stopRecorder, false)
playBack.addEventListener("click", () => audio.play(), false)


const audio = new Audio()
const streams = []

let startTime
let mediaRecorder
let chunks


async function startRecorder() {
  navigator.mediaDevices
  .getUserMedia({ audio: true })
  .then(onSuccess, onError)
}


function onSuccess(stream) {
  startTime = new Date()
  // The System "recording" icon appears now there is a stream
  streams.push(stream)

  const mimeType = "audio/webm"
  mediaRecorder = new MediaRecorder(stream) //, { mimeType })
  chunks = [];

  mediaRecorder.onstop = saveRecording
  mediaRecorder.ondataavailable = ({data}) => {
    chunks.push(data);
  };

  mediaRecorder.start()
  showStartTime()
};


function onError(error) {
  alert(`An error occured with getUserMedia():
  ${error}`);
};


function stopRecorder() {
  if (!mediaRecorder) {
    return
  }

  mediaRecorder.stop()
  stopAllTracks()
  showEndTime()
}


function stopAllTracks() {
  // Switch off the System "recording" icon
  streams.forEach( stream => {
    stream.getTracks() // get all tracks from the MediaStream
      .forEach( track => track.stop() ); // stop each of them
  })
  streams.length = 0
}


function saveRecording() {
  const type = mediaRecorder.mimeType
  const blob = new Blob(chunks, { type })
  const src = window.URL.createObjectURL(blob)
  // Play the recording
  audio.src = src
  audio.play()
}



function showStartTime() {
  const text = `Started: ${startTime.toLocaleTimeString("en-gb") + "." + startTime.getMilliseconds()}`
  console.log("text:", text);
  feedback.textContent = text
}


function showEndTime(){
  const endTime = new Date()
  const duration = (endTime - startTime) / 1000
  const text = `
Ended:   ${endTime.toLocaleTimeString("en-gb") + "." + endTime.getMilliseconds()}
Duration:       ${duration} seconds`

  feedback.textContent += text
}
  <button id="startRecording">Start Recording</button>
  <button id="stopRecording">Stop Recording</button>
  <button id="playBack">Play Back</button>
  <pre id="feedback"></pre>

Flickering issue with fixed positioning on scroll in React component

I’m encountering a flickering issue in my React component when implementing a fixed positioning effect on scroll. Here’s the scenario:

I have a parent <div> that takes the minimum height of the screen (min-h-screen) and contains three child <div> elements, each taking the full height of the screen (h-screen). The objective is to achieve the following behavior:

  1. When the top of the parent <div> reaches the top of the screen, the first child should be displayed in the viewport.

  2. As the user scrolls, the subsequent children should come into view one after another, with the first child always at the top until the last child is reached.

  3. When the bottom of the parent <div> reaches the bottom of the screen, the parent <div> should move with the scroll and no longer remain fixed.

I’ve implemented this functionality using React hooks (useRef, useState, useEffect) to detect the scroll position and toggle the fixed positioning accordingly. However, I’m encountering a flickering issue specifically when the bottom condition is met.

import { useEffect, useRef, useState } from "react";

export default function WhatWeDo() {
  const ref = useRef<HTMLDivElement>(null);
  const [isFixed, setIsFixed] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      if (ref.current) {
        const divTop = ref.current.getBoundingClientRect().top;
        const divBottom = ref.current.getBoundingClientRect().bottom;
        const screenHeight = window.innerHeight;

        if (divTop <= 0 && divBottom >= screenHeight) {
          setIsFixed(true);
        } else if (divTop > 0 || divBottom < screenHeight) {
          setIsFixed(false);
        }
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <div
      ref={ref}
      className="w-full min-h-screen flex flex-col bg-gray-50 gap-20 items-start justify-start"
    >
      {/* Background text */}

      <div
        className={`${
          isFixed ? "fixed" : ""
        }  w-full max-h-screen h-screen flex justify-center items-center bg-pink-200 left-0 top-0`}
      >
        <span className="text-8xl font-bold text-black">
          WHAT WE DO {isFixed ? "fixed" : "notfixed"}
        </span>
      </div>

      <div className="w-full h-screen"></div>

      <div className="w-1/2 max-h-screen h-screen flex justify-center items-center bg-blue-200 z-10">
        <span className="text-8xl font-bold text-black">WHAT WE DO 1</span>
      </div>
      <div className="w-1/2 max-h-screen h-screen flex justify-center items-center bg-orange-200 z-10">
        <span className="text-8xl font-bold text-black">WHAT WE DO 2</span>
      </div>
      <div className="w-full h-screen"></div>
    </div>
  );
}

Similarities Between Unity 3D and Three.js: Leveraging Unity Experience for Three.js Exploration

I’ve been working extensively with Unity 3D and recently started exploring Three.js. Interestingly, I’ve noticed some apparent similarities between the two frameworks. Has anyone else with Unity experience found Three.js to be quite similar in certain aspects? Are there specific Unity concepts or practices that seem to translate well to Three.js, making the learning curve smoother?

I’d love to hear about your experiences and any insights you’ve gained while transitioning from Unity to Three.js. Thank you for sharing your thoughts!