Error: Cannot find module ‘node:events’ on Render || Discord.JS V.14

So, I’m facing a problem with my Discord.JS V.14 Bot. I use Render as a Hoster. I have a repository of my bot on GitHub and I linked it to Render but when I try to run it (Install Command: npm install & Start Command: node app.js), it returns this error:

==> Starting service with 'node app.js'
  internal/modules/cjs/loader.js:888
    throw err;
    ^
  
  Error: Cannot find module 'node:events'
  Require stack:
  - /opt/render/project/src/node_modules/discord.js/src/client/BaseClient.js
  - /opt/render/project/src/node_modules/discord.js/src/index.js
  - /opt/render/project/src/index.js
  - /opt/render/project/src/app.js
      at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15)
      at Function.Module._load (internal/modules/cjs/loader.js:730:27)
      at Module.require (internal/modules/cjs/loader.js:957:19)
      at require (internal/modules/cjs/helpers.js:88:18)
      at Object.<anonymous> (/opt/render/project/src/node_modules/discord.js/src/client/BaseClient.js:3:22)
      at Module._compile (internal/modules/cjs/loader.js:1068:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
      at Module.load (internal/modules/cjs/loader.js:933:32)
      at Function.Module._load (internal/modules/cjs/loader.js:774:14)
      at Module.require (internal/modules/cjs/loader.js:957:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
      '/opt/render/project/src/node_modules/discord.js/src/client/BaseClient.js',
      '/opt/render/project/src/node_modules/discord.js/src/index.js',
      '/opt/render/project/src/index.js',
      '/opt/render/project/src/app.js'
    ]
  }

App.js File:

// import required modules
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config.json');
const startServer = require('./index.js');

console.log(startServer); // make sure that startServer is imported correctly

// create an instance of express
const app = express();

// use body-parser middleware
app.use(bodyParser.json());

// define routes
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

// start the server
const PORT = process.env.PORT || config.port;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

This happens only when I include this line of code here: const startServer = require('./index.js');. When I remove it, the console does not return any error and it logs this:

  ==> Starting service with 'node app.js'
  Server started on port 3000

But it doesn’t start the index.js file so the rest of the bot remains deactivated! I need a way to launch the app.js and index.js without returning any errors. Thanks in advance.

Recaptcha causes duplicated form to fail

Can someone assist me with the issue I’m facing with the web forms on my landing page? I have added a Salesforce-generated form in the first section, and I duplicated the same form at the bottom of the page. However, only the first form is functioning correctly as it has a Google recaptcha validation associated with it. The second form is not working, and I believe I need to change some IDs to rectify this issue. Can anyone guide me on which IDs need to be changed for the second form to function correctly?

Here is the code:

    <script>
    function submitUserForm() {
      var response = grecaptcha.getResponse();
      if(response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span>Click the checkbox above to verify that you are not a robot.</span>';
        return false;
      }
      return true;
    }
    function verifyCaptcha() {
      document.getElementById('g-recaptcha-error').innerHTML = '';
    }
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
  function timestamp() { var response = document.getElementById("g-recaptcha-response"); if (response == null || response.value.trim() == "") {var elems = JSON.parse(document.getElementsByName("captcha_settings")[0].value);elems["ts"] = JSON.stringify(new Date().getTime());document.getElementsByName("captcha_settings")[0].value = JSON.stringify(elems); } } setInterval(timestamp, 500);
</script>
<div class="nps-offer-form">
<form action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" onsubmit="return submitUserForm();">
    <input type=hidden name='captcha_settings' value='{"keyname":"V2_Site_Key","fallback":"true","orgId":"00D80000000cpsm","ts":""}'>
    <input type=hidden name="oid" value="00D80000000cpsm">
    <input type=hidden name="retURL" value="https://google.com">

    <label for="email">Email</label><input  id="email" maxlength="80" name="email" size="20" type="text" required /><br>


    <div class="g-recaptcha" data-sitekey="6LcfhwokAAAAAKDe6-N1YyU4njEVUPnV8uZY_8bD" data-callback="verifyCaptcha"></div>
    <div id="g-recaptcha-error" class="g-recaptcha-alert"></div>
    <input type="submit" class="btn-30-trial" value="Get 30 Days Free Trial" name="submit">
</form>
</div>

Multiple Video Streams over RTCPeerConnection

I am using rtsotowebrtc from DeepEch to stream my IP cameras over WebRTC. My client code is as follows:

var webrtc_con = new RTCPeerConnection({
              iceServers: [{
                  urls: ["stun:stun.l.google.com:19302"]
              }],
              sdpSemantics: 'plan-b'
          })
          webrtc_con.ontrack = function (event) {

              videoEl.srcObject = event.streams[0]

              if (videoEl.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
                  videoEl.play().catch(() => {
                  });
              } else {
                  videoEl.oncanplay = () => {
                      videoEl.play().catch(() => {
                      });
                  };
              }

          }
          webrtc_con.addTransceiver('video', {direction: 'sendrecv'})
          webrtc_con.onnegotiationneeded = async function handleNegotiationNeeded() {
              const offer = await webrtc_con.createOffer()

              await webrtc_con.setLocalDescription(offer)

              try {
                  fetch(url, {
                      method: 'POST',
                      body: new URLSearchParams({data: btoa(webrtc_con.localDescription.sdp)})
                  })
                      .then(response => response.text())
                      .then(data => {
                          try {
                              webrtc_con.setRemoteDescription(
                                  new RTCSessionDescription({type: 'answer', sdp: atob(data)})
                              )
                          } catch (e) {
                              console.warn(e)
                              console.warn(`Stream ${url} Not Found!`)
                          }
                      })
              } catch (e) {
                  console.warn('Server maybe offline?')
              }
          }

I am currently only able to get one stream per WebRTC connection. How can I get multiple video streams over one connection? Thank you for your help.

Grey out entire body using CSS

I’m trying to apply greyscale to the entire body element whenever there is an event triggered. Say for example, if a button is hovered/clicked, entire screen will grey out first followed by showing a text on top of the page. I am able to display a dialog on top of the page but prior displaying dialog box, greying out must be done.

enter image description here

I’d appreciate your help on this.

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
   document.body.classList.add('grey');
}
</script>

grey{
   filter: gray; 
  -webkit-filter: grayscale(1); 
  -moz-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  -o-filter: grayscale(100%);
   filter: grayscale(100%);
}

How to send json data from events sent from server in Django?

I’m looking for an answer to my question, how do I send “JSON data”?
For example, if I wanted to submit a discussion, it would be sent as a string, not “JSON”

This is what I’m sending but I really want to send the discussion but I count the number of discussions and send it and if the number the user has is different from this number it updates the data and I see it’s a bad way

views.py

def stream(request):
    def event_stream():
        discussion = Discussion.objects.all()
        count = discussion.count()    
        
        while True:
            time.sleep(3)
            yield 'data: %inn' % count

    return StreamingHttpResponse(event_stream(), content_type='text/event-stream')

template


if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("stream/");
  source.onmessage = function(event) {
    console.log(event.data);
    };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}

How to add css background styles using vanilla-lazyload

I’m looking at using vanilla lazyload to improve the performance of the website. However, I am struggling to find a way to lazyload background images with styles.

The background images I have on the website have the following syntax:

<section class="ptb-100 gradient-overly-bottom" style="background: url('assets/img/hero-2.jpg')no-repeat center center / cover fixed">

Using vanilla lazyload, the syntax changed to the following:

<section class="ptb-100 gradient-overly-bottom lazy" data-bg="assets/img/hero-2.jpg">

Output from vanilla lazyload:

<section class="ptb-100 gradient-overly-bottom lazy entered loaded" data-bg="assets/img/hero-2.jpg" data-ll-status="loaded" style="background-image: URL("assets/img/hero-2.jpg");">

As you can observe, the output doesn’t include a background URL attribute, it replaces with a background image.

Is there a way to add styles after the background image URL?

javascript onclick open specific item in gallery not working in mobile devices

i have created a custom gallery in html using javascript, the gallery is a single gallery with 32 images, i have 4 categories, when any of the four categories are clicked gallery should open with respective image, so i did the following code:

<img src="amb.jpg" onclick="galopenModal();currentSlide(1)" class="hover-shadow cursor">
    <img src="foo.jpg" onclick="galopenModal();currentSlide(9)" class="hover-shadow cursor">
<img src="sha.jpg" onclick="galopenModal();currentSlide(17)" class="hover-shadow cursor">
<img src="fra.jpg" onclick="galopenModal();currentSlide(25)" class="hover-shadow cursor">
function galopenModal() {
  document.getElementById("galmyModal").style.display = "block";
  document.getElementById("masthead").style.zIndex = "99";
}

function currentSlide(n) {
  galshowSlides(slideIndex = n);
}

function galshowSlides(n) {
  var i;
  var slides = document.getElementsByClassName("galmySlides");
  var dots = document.getElementsByClassName("galdemo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}

this is working fine in desktop devices, i mobile devices whichever category is clicked, the gallery starts from 1st image and not opening from respective image, can anyone please tell me what is wrong in here, thanks in advance.

zrender didn’t work after i build a project

at devlopment eviroment ,zrender can do the render operate, when i build the project , the zrender didn’t work.
They’s doc said ,use zrender.min.js for build version.
enter image description here
this is my code
enter image description here
i want konw ,what’s wrong with this?

i tried install the zrender.js, like this: npm i zrender, and import it in my vue profile.
but it doesn’t work too.

Cannot retrive DN from searchEntry when I update ldapjs to v3

I recently upgraded the package ldapjs from v2 to v3. When I search for a user with searchEntry, I get an empty object, but all others functions worked without a problem, this is my code:

    let resp = { errorMessage: '', ldap: 0, sd: '', dd: '', name: '' };
    const ldapconfig: any = config.get('ldap');

    let myPromise = new Promise<any>((resolve, reject) => {
      const adSuffix = ldapconfig.server.searchBase;
      const password = ldapconfig.server.bindCredentials;

      const client = ldap.createClient({
        url: ldapconfig.server.url,
      });

      client.bind(ldapconfig.server.bindDN, password, async (err: any) => {
        if (err) {
          console.log('Error in new connetion ' + err);
        } else {
          const searchOptions: {} = {
            scope: 'sub',
            filter: '(sAMAccountName=' + username + ')',
            attributes: ['sAMAccountName']
          };

          client.search(adSuffix, searchOptions, async (err: any, res: any) => {
            assert.ifError(err);
            await res.on('searchEntry', async (entry: any) => {
             //
             //this part was working normaly with ldapjs v2
             //
             console.log("entry.objectName ",entry.sAMAccountName);
             console.log("entry.dn ",entry.dn);
             //but now i get an empty object
             
              if(Object.keys(entry.objectName).length === 0){
                console.log("Erreur nom de l'utilisateur invalid !");
                //reject(false)
              }else{
                const dn = entry.objectName.split(',OU=');
                resp.sd = dn.length === 7 && dn[3].includes('RD') ? dn[3] : '';
                resp.dd = dn.length === 7 && dn[2].includes('DD') ? dn[2] : '';
                const cn = dn[0].split('CN=');
                resp.name = cn ? cn[1] : '';
                resp.ldap = 1;
              }
            });

            await res.on('end', (result: any) => {
              resp.ldap === 0
                ? (resp.errorMessage = "Cet utilisateur n'existe pas dans ldap")
                : null;

              resolve(resp);
            });
          });
        }
      });
    });
    return myPromise;

Did someone had the same issue ? or know how to fix it ?

find if a word exists in an api response

I made a query to an api, and with the response from the api I created a for each as follows

  var id_todos_pcs = response.data

            id_todos_pcs.forEach(element => {
               var nombres = element.name
               
               console.log(nombres)
        
            });

in which I extract the part I need, which is “names”. I need to check if between those two names there is one that I have stored in another variable.

I have tried with indexOf, find, filter…in fact I added them to an array but that array does not return the names but the IDs, how can I do this?

React router, refreshing the page result in 404 page live server

I have built my react app with npm run build. Now in the live server navigating the link is working properly, but without the homepage page, https://www.nayeemriddhi.info/authapp/, and other pages while refreshing the page it gives me a 404 page, like https://www.nayeemriddhi.info/authapp/register page. The code of my react app is given below

index.js code

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter, HashRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store/Store";
import { PersistGate } from "redux-persist/integration/react";
import { persistStore } from "redux-persist";

let persistor = persistStore(store);

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <BrowserRouter basename="/authapp">
          <App />
        </BrowserRouter>
      </PersistGate>
    </Provider>
  </React.StrictMode>
);

App.js code

import { Navigate, Route, Routes } from "react-router-dom";
import "./admin/css/Back-Css-Inc";
import Login from "./admin/pages/Login";
import Register from "./admin/pages/Register";
import Contents from "./admin/components/Contents";
import EmailVerify from "./admin/EmailVerify/EmailVerify";
import ProtectedRoute from "./admin/components/ProtectedRoute";
import NotFoundPage from "./admin/components/404-Page";
import ForgotPassword from "./admin/pages/ForgotPassword";
import ResetPassword from "./admin/pages/ResetPassword";

function App() {
  return (
    <>
      <Routes>
        {["/", "/login"].map((path) => (
          <Route path={path} element={<Login />} />
        ))}
        <Route path="/forget-password" element={<ForgotPassword />} />
        <Route path="/register" element={<Register />} />
        <Route path="/users/:id/verify/:token" element={<EmailVerify />} />
        <Route path="/users/:id/reset/:token" element={<ResetPassword />} />
        <Route element={<ProtectedRoute />}>
          <Route path="/admin-dashboard" element={<Contents />} />
        </Route>
      </Routes>
    </>
  );
}

export default App;

Package.json code

{
  "name": "auth",
  "homepage": "https://www.nayeemriddhi.info/authapp/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "dotenv": "^16.0.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.6.0",
    "react-redux": "^8.0.5",
    "react-router-dom": "^6.10.0",
    "react-scripts": "5.0.1",
    "react-toastify": "^9.1.1",
    "reactstrap": "^9.1.5",
    "redux-persist": "^6.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Is there any fix for it? Thank you

I am expecting routing other pages should render while refreshing the pages too.

How can fit the center of leaflet map in center of polygon in React JS?

I have a map that is created by leafletJS. I fitBounds the map to polygon area and my pointer is fixed in center of the map but in the special case like below my polygon is in a shape that the pointer does not fits in the polygon bounds although I fitBounds to polygon bound.

what shall I do for the polygons which the centered pointer does not place in polygon area in first load?

enter image description here

 const selectedPoint = point([mapCenter.lat, mapCenter.lng])
              const poly = polygon([polygonCoords])
              const isPointInPolygon = booleanPointInPolygon(selectedPoint, poly)

              if (isPointInPolygon) {
                // onDragEnd && onDragEnd({ latitude: mapCenter?.lat, longitude: mapCenter?.lng })
              } else {
                toast({ content: formatMessage(strings.selectInPolygonError), type: 'error' })
                onDragEnd && onDragEnd(null)
                myMap.fitBounds(mapPolygon.getBounds())
              }

How to avoid decimal truncation in javascript

In my code I have some exp operation with decimals
I did some tests for example this operation

let c = 1.02;
let y = 0.0416666666666664;
let j= Math.pow(c,y); -> 1.000825449967136

enter image description here

But if I do the same thing with the calculator, I get this result instead -> 1.0008254499671359597325523766889
How to make the result of my operation as precise as in the calculator?
I’ve seen a few other similar questions, some recommended using BigInt, but in my case I can’t use external js (or I don’t think I can use it in Adobe Pro related javascript)

How to solve react-native expo app android version compatibility ? App working fine upto android version 12 but not in android version 13

I have upgraded expo sdk and react-native version to the latest version.

and now I have not changed anything except that and when i tried to run the app i faced this error, Even there is no change in my APP.JS
:-

     Error: Element type is invalid: expected a string (for built-in components) or a 
     class/function (for composite components) but got: undefined. You likely forgot to export 
     your component from the file it's defined in, or you might have mixed up default and 
     named imports.

Check the render method of `App`.

These are my dependencies:-

   {
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/samples": "~36.0.0",
    "@expo/vector-icons": "^13.0.0",
    "@react-navigation/web": "~1.0.0-alpha.9",
    "deprecated-react-native-prop-types": "^4.0.0",
    "expo": "^48.0.0",
    "expo-asset": "~8.9.1",
    "expo-constants": "~14.2.1",
    "expo-file-system": "~15.2.2",
    "expo-font": "~11.1.1",
    "expo-media-library": "~15.2.3",
    "expo-web-browser": "~12.1.1",
    "native-base": "^2.13.8",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.71.6",
    "react-native-easy-grid": "^0.2.2",
    "react-native-gesture-handler": "~2.9.0",
    "react-native-htmlview": "^0.15.0",
    "react-native-hyperlink": "0.0.19",
    "react-native-image-pan-zoom": "^2.1.11",
    "react-native-reanimated": "~2.14.4",
    "react-native-screens": "~3.20.0",
    "react-navigation": "~4.0.10",
    "react-navigation-stack": "~1.10.3",
    "react-navigation-tabs": "~2.6.2",
    "recyclerlistview": "^3.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "babel-preset-expo": "^9.3.0",
    "jest-expo": "^48.0.0"
  },
  "private": true
}