Limit line breaks in textarea

I have a text area, where i want to allow users to make line break by pressing enter, but i want to limit that to only one break, because then the users could add as many breaks they want, creating huge white space in the output.

  <textarea maxLength={3000} onChange={(e) => setPersonBio(e.target.value)} value={personBio} type="text" rows="5" className="bio-content" placeholder="Enter something about yourself..."></textarea>

And then i display it in <p> tag with white-space: pre-line;

My question is how to limit the amount of breaks user can enter, or delete the additional ones after submitting.

Code review request: Finding duplicates in array of objects with javascript

Hope everyone is having a good Christmas.

First of all, this is working code in a production environment.

I recently wrote some code for work.

The goal is to find users that contain more than one role. On the frontend, if a user has more than one role, the person using the program will see a message suggesting that they remove one of these roles.

Here is the code that I wrote. Mind you, I have changed some of the values so that anything sensitive is removed:

usersWithMultipleRoles() {
      /**
       * Make a flat map of all the users from each role.
       * Each entry is an object with a roleId
       */
      const users = this.roles.flatMap(r => {
        return r.users.map(value => {
          return { roleId: r.id, user: value }
        })
      })

      /**
       * Use reduce to create an array of objects.
       * Each object is keyed by the user's ID,
       * and its value is the roles that each user is in.
       */
      const lookup = users.reduce((acc, value) => {
        acc[value.user.id] = acc[value.user.id] || []
        acc[value.user.id].push(value.roleId)
        return acc
      }, [])

      /**
       * Finally, return an array of users that have
       * multiple roles.
       */
      const usersWithManyRoles = []

      lookup.forEach((value, key) => {
        if (value.length > 1) {
          usersWithManyRoles.push({
            userId: key,
            userInfo: users.find(value => value.user.id === key).user,
            roles: value,
          })
        }
      })

      return usersWithManyRoles
    },

The following is what I would expect if a user has more than one role assigned.

[
  {
    userId: 127,
    userInfo: { User Object },
    roles: [2, 6],
  },
  ...

]

Just so you know, there is nothing wrong with this code. It returns exactly what I’m looking for.

What I would change

The only thing I can think about changing is the structure of the response from the first mapping function, the flatMap function.

My question to you

How would you write this function? How can I improve it? And what should I read to make better functions in the future?

A bit about me

Ignore if you want, this is just to give you background about why my knowledge isn’t the best, and I’m sure the above question is simple for a lot of you XD

I’m a 39 y/o self-taught software developer. I’ve been working in the industry for about 3 years now ( about 1 1/2 years in a geospatial company, and now almost two years in a health care company from Tokyo ). So I’m not the smartest dude on the block, and I learn slow but I’m learning.

I want to get better at what I do so that I can potentially find more remote work in the future, and hopefully secure a more stable future for my wife and I. Currently getting pretty confident with my frontend skills, and learning some php / Laravel in the backend for the company I work with currently.

Although I still feel like a total imposter when I compare myself to my boss, who has a Masters in computer science and has taught me a lot about programming. Forever grateful to this guy.

I got a wrong result when i want to update user status(online/offline) when the user connect or disconnect to the server with socket io

the wrong is that the updated user in MongoDB is not the right one, because the altered user is the last one connected or disconnected to the server ,
here is the server side.

> routes/socket.js

      module.exports = function (io) {
      var array_of_connection = [];
      let senderTokent;
      const userIds = [];
    
      io.sockets.use(function (socket, next) {
        if (socket.handshake.query && socket.handshake.query.token) {
          jwt.verify(socket.handshake.query.token, "lol", function (err, decoded) {
            if (err) return next(new Error("Authentication error"));
            senderToken = decoded;
            next();
          });
        } else {
          next(new Error("Authentication error"));
        }
      }).on("connection", async function  (socket) {
        socket._id = senderToken.user._id;
        if (!userIds.includes(senderToken.user._id)) {
          userIds.push(senderToken.user._id);
          array_of_connection.push(socket);
        } else {
          console.log('user already opened socket');
        }
        
        let user = await db.userSchema.findOneAndUpdate({_id: senderToken.user._id}, {$set:{online: true}}, {new: true})
        for (let i = 0; i < array_of_connection.length ; i++) {
          if (array_of_connection[i]._id !== senderToken.user._id) {
           array_of_connection[i].emit('online-users', user._id);
          }
        }
       socket.on('disconnect', async () => {
      const userIndex = userIds.indexOf(senderToken.user._id);
      userIds.splice(userIndex, 1);
      const socketIndex = array_of_connection.indexOf(socket);
      array_of_connection.splice(socketIndex, 1);
        let user = await db.userSchema.findOneAndUpdate({_id: senderToken.user._id}, {$set:{online: false}}, {new: true})
        for (let i = 0; i < array_of_connection.length; i++) {
          if (array_of_connection[i]._id !== senderToken.user._id) {
            array_of_connection[i].emit('friend-leave2', senderToken.user._id)
          }
        }
  });
});

How to see what url javascript is requesting in the Chrome Network Activity Panel

I’m using this page as an example.
In the network tab of the console, if I block requests from the url “https://www.premierleague.com/resources/prod/f4af34b-3761/widgets/pl_player-image.min.js”, the player image does not load, so I assume this is what is getting the image of the player.
However, what should I do to find out the url that the javascript is requesting to get that image? (besides right clicking and opening the picture in a new tab)

How to change filename on Files array using java script? [duplicate]

How can i change the uploading file name of files array. What i want is to remove any empty spaces from file name if exists, i have tried with this code but it doesn’t change the file name as expected, how can i update the file name for the files array.

async function formatFileName(inp) {
    var fileName = inp.files[0].name
    inp.files[0].name = "TEST1"
    console.log(inp.files[0].name)
}

async function saveFile(inp) {
    await formatFileName(inp)
    let formData = new FormData();
    formData.append("file", inp.files[0]);
    await fetch('{{ file_upload_api }}', { method: "POST", body: formData }).then(() => {
        $('#file_name').html(inp.files[0].name);
        alert("File Upload Succefully")
    }).catch((err) => {
        $('#file_name').html("Something went wrong uploading " + inp.files[0].name).css('color', 'red');
        alert(err)
    });
}

Thanks in advance.

How to get the javascript on-change function value in html template to Django views

Here is my script in html template

”’function yesnoCheck() {

  if (document.getElementById('yesCheck').checked) {
      siv=document.getElementById('ifYes').style.display = 'block';
      // siv = document.getElementById("yesCheck").value;
      document.getElementById('ifNo').style.display = 'none';
      alert(siv);

  }
  if (document.getElementById('noCheck').checked) {
      document.getElementById('ifYes').style.display = 'none';
      srv=document.getElementById('ifNo').style.display = 'block';
      alert(srv); 

  }

}”’

Below is my views code

      '''if request.method =='POST':
           if request.POST.get('basis1')=='here i need the data from alert(siv)' 

                return render(request,'stockissue2.html')
           elif request.POST.get('basis2')=='here i need the data from alert(srv)':
         
                    messages.success(request,'Record Saved Successfully...!')
                    return render(request,'stockissue2.html')
           else:
                 messages.info(request,'Material Not Available or Transaction No. wrong') 
                 return render(request,'stockissue2.html')'''

Please help me out..

ReactJS Route function isn’t working for me

I started learning ReactJS yesterday using Academind’s crash course for beginners on it. There is a part where he teaches about react-router-dom. I tried using it on App.js and index.js as such:

App.js:

import { Route } from "react-router-dom";

import AllMeetupsPage from "./pages/AllMeetups";
import FavouritesPage from "./pages/Favourites";
import NewMeetupsPage from "./pages/NewMeetups";

function App() {
  return (
    <div>
      <Route path='/'>
        <AllMeetupsPage />
      </Route>
      <Route path='/favourites'>
        <FavouritesPage />
      </Route>
      <Route path='/new-meetups'>
        <NewMeetupsPage />
      </Route>
    </div>
  );
}

export default App;

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'

import './index.css';
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

There shouldn’t be any error since I have fixed the syntax and imported the right files given in the video. Yet, in localhost:3000 I get this as the result.

If I just use <AllMeetupsPage /> then it works. If I put it in the route function then it doesn’t. How can I fix this?

onload function(this) from onclick in another page

I have a page where there is a button. The button has an onclick function, where it calls the function pop to produce an alert. The alert shows the attribute of the button’s data-message.

I am trying to redirect this function to onload to another page, hence the href.

What I would like to produce is for the alert to be displayed on the 2nd page as well when the body onloads.

I have tried to change and swap my codes between the 2 different HTML, however I often get the error of Uncaught TypeError: e.getAttribute is not a function.

Here are the relevant codes for page 1 where the button needs to be clicked:

<a href="dump2.html"><button type="button" data-message="button1" onclick="pop(this)">click</button></a>

<script>
   function pop(e) {
       alert(e.getAttribute("data-message"));
   }
</script>  ```


------------------


Page 2 where I will onload the attribute I have gotten from the button clicked on Page 1

<body onload="pop(this)"> </body>
<script>
 function pop(e) {
     alert(e.getAttribute("data-message"));
 }
</script>


Any help would be greatly appreciated. Thanks :)

MongoServerError: bad auth : Authentication

Hi im making an app with node js, mongo db and im deploying in vercel, so i made the aplication and i tested on mode dev and was okay but when execute the comand “now” and see the site it appear a error 500 and im seein from vercel and
the page of vercel function log

it say that bad auth but i tried that on mode dev, so i dont know why is the problem, this is the index.json when i connect

const express =require('express')
const mongoose =require('mongoose')
const bodyParser= require('body-parser')
const cors= require('cors')
const meals=require('./routes/meals')
const orders=require('./routes/order')

const app=express()
app.use(bodyParser.json())
app.use(cors())
mongoose.connect(process.env.MONGODB_URI)



app.use('/api/meals',meals)
app.use('/api/order',orders)


module.exports=app;

and i created a file .env and i put this

MONGODB_URI=mongodb+srv://almuerzimaster:[email protected]/myFirstDatabase?retryWrites=true&w=majority

how to create animation using p5.js how create an animation of process of blast furnace

i have loaded images using p5.js but how to perform transition and movement of images for the duration.i am adding up the code here. i have to create a working animation for blast furnace using images.i have used images as variables

var pic2
var pic3
var pic4
var pic5
let posX=0
let posY=0
let size=200
function preload(){
 // pic1=loadImage("blastF1.png")
  pic2=loadImage("iron.png");
  pic3=loadImage("blast3.jpg");
  pic4=loadImage("slag.jpg");
  pic5=loadImage("BLAST2.jpg")
}


function setup() {
  createCanvas(600, 500);
 
}

function draw() {
  background("grey");
 // image(pic1,0,100,100,200)
//  image(pic2,posX,posY,size,size-20)
  image(pic3,posX,400-posY,200,200)
  image(pic5,posX,0,200,300)
  //image(pic4,0,0)
  if(posX>width||posY>height){
    posX=0
    posY=0
    size=100
  }else{
  posX+=1
  posY+=1
  size-=0.15}
  
}

create canvas and msg.content in an outside function (discord.js/nodejs)

this has been bugging me for a while, I’ve created a pipboy like interface to display the condition of the character and built it into a solo functions but now i want to incorporate it into other display cards. The problem is every time i try to take the content out and put them in an external file the “canvas” or “msg” become undefined. This seems like a no brainer to off load to a function but I’m not sure how. i know i also have to pass “paperDollXoffset, paperDollXoffsetShort, paperDollYoffset, paperDollwidth, paperDollwidthShort”, and “paperDollheight” as their configured for the stand alone canvas and would need adjusting on merged canvases.

code follows

        var CanvasW = 625;
        var CanvasH = 500;
        const paperDollXoffset = 0;
        const paperDollXoffsetShort = 187.5;
        const paperDollYoffset = 0;
        const paperDollwidth = 625;
        const paperDollwidthShort = 250;
        const paperDollheight = 500;
        canvas = Canvas.createCanvas(CanvasW, CanvasH);
        context = canvas.getContext('2d');
        background = await Canvas.loadImage('./images/photo-1538370965046-79c0d6907d47.jpg');
        var useShortValuesArms = 0;
        var useShortValuesLegs = 0;
        var useShortValuesBody = 0;
        var useShortValuesHead = 0;
        context.drawImage(background, 0, 0, CanvasW, CanvasH);
        context.strokeStyle = '#0099ff';
        context.strokeRect(0, 0, CanvasW, CanvasH);
        var basePic1URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS1_White.png';
        var basePic2URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS2_White.png';
        var basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Head_White.png';
        var basePic4URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Torso_White.png';
        var basePic5URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS1_White.png';
        var basePic6URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS2_White.png';
        var basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatTail_F_White.png';
        var basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS1_F_White.png';
        var basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS2_F_White.png';

      
        if (msg.content.toLocaleLowerCase().includes('!tail')){
          basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatHead_F_White.png';
          basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatTail_F_White.png';
        };//tail default to cat
        if (msg.content.toLocaleLowerCase().includes('!wing')){
            basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonHead_F_White.png';
            basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonTail_F_White.png';
            basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS1_F_White.png';
            basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS2_F_White.png';
        };//wing default to dragon girl
        if (msg.content.toLocaleLowerCase().includes('!noarm')){
            basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatHead_F_White.png';
            basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatTail_F_White.png';
            basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatWingS1_F_White.png';
            basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatWingS2_F_White.png';
        }//noarms and wing default to bat
        if (msg.content.toLocaleLowerCase().includes('!noleg')){
          basePic1URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerArmS1_F_White.png';
          basePic2URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerArmS2_F_White.png';
          basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerHead_F_White.png';
          basePic4URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerTorso_F_White.png';
          basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerTail_F_White.png';
      };//no leg and tail default to mermaid

      //add/get art for (tail, no arm, no leg) Serpent [Torso, tail, head]
      //add/get art for (tail, arm, no leg, wing) Wyrm [Torso, tail, head, arm, wing]
      //add/get art for (tail, no arm, no leg, wing) feathered serpent [Torso, tail, head, wing]
      //add/get art for (no arm, optional tail) undertale/monster kid [Torso, tail, head, legs]
      //add/get art for (no leg, optional tail) arm monster, tail is a full serpent [Torso, tail, head, arm]
      //add/get art for (no leg, no arm, wing, optional tail) arm monster, tail is a full serpent, arms are wings [Torso, tail, head, wing]

      if (basePic1URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS1_White.png'){
        useShortValuesArms = 1;
      }
      if ((basePic3URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Head_White.png') || (basePic3URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatHead_F_White.png')){
        useShortValuesHead = 1;
      }
      if (basePic4URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Torso_White.png'){
        useShortValuesBody = 1;
      }
      if (basePic5URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS1_White.png'){
        useShortValuesLegs = 1;
      }

        var conditionpic1 = await Canvas.loadImage(basePic1URL);
        var conditionpic2 = await Canvas.loadImage(basePic2URL);
        var conditionpic3 = await Canvas.loadImage(basePic3URL);
        var conditionpic4 = await Canvas.loadImage(basePic4URL);
        var conditionpic5 = await Canvas.loadImage(basePic5URL);
        var conditionpic6 = await Canvas.loadImage(basePic6URL);
        var conditionpic7 = await Canvas.loadImage(basePic7URL);
        var conditionpic8 = await Canvas.loadImage(basePic8URL);
        var conditionpic9 = await Canvas.loadImage(basePic9URL);
        var variableX = paperDollXoffset;
        var variableW = paperDollwidth;

        if (!msg.content.toLocaleLowerCase().includes('!noarm')){
          if (useShortValuesArms == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic1, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic2, variableX, paperDollYoffset, variableW, paperDollheight);
        }//noarms
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (useShortValuesHead == 1){
          variableX = paperDollXoffsetShort;
          variableW = paperDollwidthShort;
        }
        context.drawImage(conditionpic3, variableX, paperDollYoffset, variableW, paperDollheight);
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (useShortValuesBody == 1){
          variableX = paperDollXoffsetShort;
          variableW = paperDollwidthShort;
        }
        context.drawImage(conditionpic4, variableX, paperDollYoffset, variableW, paperDollheight);
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (!msg.content.toLocaleLowerCase().includes('!noleg')){
          if (useShortValuesLegs == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic5, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic6, variableX, paperDollYoffset, variableW, paperDollheight);
        }//nolegs

        variableX = paperDollXoffset;
        variableW = paperDollwidth;
        if (msg.content.toLocaleLowerCase().includes('!wing')){
          context.drawImage(conditionpic8, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic9, variableX, paperDollYoffset, variableW, paperDollheight);
        }//wings
        if (msg.content.toLocaleLowerCase().includes('!tail')){
          if (useShortValuesHead == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic7, variableX, paperDollYoffset, variableW, paperDollheight);
        }//tail