Loop through array that is dynamic in Angular

I have this array declared in my .ts file

  opt_1=[];
  opt_2=[];
  opt_3=[];
  opt_4=[];

and in .html component there is an outer loop

 <span *ngFor="let list of current_lists[0]; let i = index">
     <div *ngFor="let item of opt_{{i}}">{{ item }}</div>
 <span>

this opt_{{i}} i want to make it dynamic so that i can access all the elements of array

<div *ngFor="let item of opt_{{i}}">{{ item }}</div>

but getting syntax related errors.

Any solution Thanks

How to make pop up disappear when clicked off of pop up?

I am creating a pop-up for my products when an icon is clicked. I want to make it so that the pop-up automatically disappears once the user clicks somewhere outside of the pop-up box. Currently, the only way for the pop-up to close and disappear is to click the same icon button that makes the pop-up appear to begin with. Id appreciate it if you could help me by using the code I provided as I am a beginner and will probably not be able to incorporate general suggestions but I will of course try my best! Thank you guys so much for the help and suggestions in advance.

HTML Pop up Code

<div class="box">
        <div class="icons"> 
            <a href="#contact" class="fas fa-shopping-cart"></a>
            <div class="popup" onclick="myFunction()">
                <span class="popuptext" id="myPopup">RAW Pipe Cleaners are naturally strong and absorbent and wrapped around a flexible banded iron core. These are the natural way to clean your pipe or rig! A RAW Innovation!</span>
            <a href="#" class="fas fa-info">
              </a></div>
            <a href="#" class="fas fa-eye"></a>
        </div>

Pop Up CSS Code

        /* Popup container */
        .popup {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }
        
        /* The actual popup (appears on top) */
        .popup .popuptext {
            visibility: hidden;
            width: 300px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 8px 0;
            position: absolute;
            z-index: 1;
            bottom: -740%;
            left: 50%;
            margin-left: -150px;
            height: 400px;
            font-size: 18px;
            padding: 50%;
        }
        
        
        
        /* Toggle this class when clicking on the popup container (hide and show the popup) */
        .popup .show {
            visibility: visible;
            -webkit-animation: fadeIn 1s;
            animation: fadeIn 1s
        }
        
        /* Add animation (fade in the popup) */
        @-webkit-keyframes fadeIn {
            from {opacity: 0;}
            to {opacity: 1;}
        }
        
        @keyframes fadeIn {
            from {opacity: 0;}
            to {opacity:1 ;}
        }

Pop up JS Code

            // When the user clicks on <div>, open the popup
        function myFunction() {
            var popup = document.getElementById("myPopup");
            popup.classList.toggle("show");
        }

How do I remove old lines when I am adding new ones

I am trying to create a graph using javascript where I will be able to show equations via y = mx + b. I have a few methods that would create the x and y axis and I have a method that draws the line, based on user input (on click of a draw line button). However, I am unable to figure out how to make the previous line disappear whenever I click the draw line button.

Graph.prototype.drawLine = function(slope, yintercept, color, thickness) {

    

    console.log("Inside drawline");

    console.log("this.maxX: " + this.maxX + " this.maxY: " + this.maxY);

    var context = this.context;

    // draw x and y axis
    this.drawXAxis();
    this.drawYAxis();

    //context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    context.save();
    context.save();
    this.transformContext();

    console.log("this.minX: " + this.minX);
    console.log("this.iteration: " + this.iteration);
    console.log("yintercept: " + yintercept);
    console.log("slope:" + slope);

    context.beginPath();
    context.moveTo(this.minX, slope * this.minX + yintercept);

    for(var x = this.minX + this.iteration; x <= this.maxX; x += this.iteration) {
      if (this.iteration % 200 == 0){
       console.log("x: " + x + " y: " + (slope * x + yintercept));
      }
      context.lineTo(x, slope * x + yintercept);
    }

    context.restore();
    context.lineJoin = 'round';
    context.lineWidth = thickness;
    context.strokeStyle = color;
    context.stroke();
    context.restore();
  };

This is my jQuery:

$(“#btnGraph”).click(function(){

  //myGraph.clearCanvas()

    var m1,b1,m2,b2 = 0;

    m1 = parseFloat($("#m1").val());
    b1 = parseFloat($("#b1").val());


   
    var myGraph = new Graph({
     canvasId: 'Graph',
     minX: -10,
     minY: -10,
     maxX: 10,
     maxY: 10,
     unitsPerTick: 1
    });      

    
    myGraph.drawLine(m1, b1, 'blue', 3);
    

    //myGraph.drawEquation(function(x) {
     //return 1 * x;
    //}, 'red', 3);

 
  });

Thank you!

A right way to use uuid as key in React?

I was fetching videos from an API and there were duplicates. So, I applied uuid to generate a key for each – key={uuid()} – until realizing that I was generating a new key for every render.

Below is my fix, but I am not quite sure if it’s really solving the issue.

export default function VideoList({ videos, observedElement }) {
  const location = useLocation();

  const videoList = videos.map((video, index) => {
    video.uuid = uuid();

    return (
      <Link
        to={`/videos/${video.id.videoId}`}
        state={{ backgroundLocation: location }}
        key={video.uuid}
      >
        <VideoListEntry info={video} ref={observedElement} />
      </Link>
    );

  return <div>{videoList}</div>
}

Shift hue of white space on HTML5 canvas

Is it possible to hue shift the white space of a image on a HTML5 canvas. I’ve seen other methods of hue shifting a image but they all don’t hue shift white, they all shift the color black. If this is possible how would I go about doing it?

Thanks!

Getting $_POST variable as empty while getting everything correct with php://input

I have created a react application from which I am calling my server built upon php
Following is how I call my php file

const requestOptions = {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: JSON.stringify({ name, username, password }),
};
console.log(requestOptions);

fetch('http://localhost/crud/requests/signup.php', requestOptions)
  .then(res => res.json())
  .then(data => console.log(data));

Here is what I have in the PHP file

if (isset($_POST) && !empty($_POST)) {
  // do something
}

however when I print the $_POST variable, I get an empty array. Event the $_RESPONSE is empty.

But when I tried to print the input stream like this

print_r(file_get_contents('php://input'));

Everything seems to be fine. Can anyone explain why does this happen.
I tried to read it in the documentation & looked up on some forums and blogs but wasn’t satisfied with the answers.

How to get the same property values based on condition in javascript

I would like to know how to find duplicates in fields in array object using

javascript.

from arrayobj, get same property model,then check

if typecode value is same but not SP, model same return that arrayobject

if typecode value has SP, model same return that arrayobject
else return []

for arrobj,

if model and typecode has same value, return those array object

if model same, any object typecode has value SP return those array

if above two conditions fails, return empty array
var arrobj1=[
   {id:1, model: "interior", name: "lisa", typecode: "FL"},
   {id:2, model: "interior", name: "peter", typecode: "FL"},
   {id:3, model: "exterior", name: "john", typecode: "SP"}
]
var result1=isValid(arrobj1);
Expected Output
// result1
[
  {id:1, model: "interior", name: "lisa", typecode: "FL"},
  {id:2, model: "interior", name: "peter", typecode: "FL"}
]


var arrobj2=[
   {id:1, model: "exterior", name: "lisa", typecode: "FL"},
   {id:2, model: "interior", name: "peter", typecode: "FP"},
   {id:3, model: "interior", name: "john", typecode: "SP"}
]
var result2=isValid(arrobj2);
Expected Output
// result2
[
  {id:2, model: "interior", name: "peter", typecode: "FP"},
   {id:3, model: "interior", name: "john", typecode: "SP"}
]

function isValid(list){
     let result=[];
    let duplicates = list.map((item, index) =>{
    return list.find((x, ind)=> x.model === item.model && index !== ind );
  })
   duplicates.forEach(e=>{
    if(e.typecode !== "SP"){
     result.push(e);
    }
  })
    return result;
}

Why does .setAttribute not work when nested inside a function?

I’ll make it quick. I researched a lot but I’m not sure why this is not working.

I have a textarea tag which I want to set to ‘data-something’ tag using setAttribute(“data-something”,””) command and it works just fine if I just list it out there. However what I’m doing is I”m creating a button that when clicked sets the attribute of the textarea to ‘data-something’, and no matter what it fails to operate when I nest setAttribute inside a myFunction and set button onclick=”myFunction()”. I’d appreciate if someone could explain a workaround that.

Thanks a ton for your patience.

This is what works:

<textarea></textarea>

<script>
textarea.setAttribute("data-something","")
</script>

This is what doesn’t work

<textarea></textarea>

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

<script>
function myFunction(){
textarea.setAttribute("data-something","")
}
</script>

Websocket failed: Invalid frame header

I’m using socket.io with peerjs to create a video conference app it shows me this error in the console of browser :

http://localhost:3000/socket.io/?EIO=3&transport=polling&t=O0Hrv-4&sid=2C_b3aCCfINuuUFNAAAA 400 (Bad Request)
and
WebSocket connection to ‘ws://localhost:3000/socket.io/?EIO=3&transport=websocket&sid=TIij4-ksOm6WI8URAAAA’ failed: Invalid frame header

Can anyone please help?
i have a final soon
#server.js#

const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidv4 } = require('uuid');
const io = require('socket.io')(server);
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
    debug: true
});
app.use(express.static('public'));
app.use('/peerjs', peerServer);
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
    res.redirect(`/${uuidv4()}`);
});
app.get('/:room', (req, res) => {
    res.render('room', { roomId: req.param.room })
});
io.on('connection', socket => {
    socket.on('join-room', (roomId, userId) => {
        socket.join(roomId);
        socket.to(roomId).broadcast.emit('user-connected', userId);
        socket.on('message', message => {
            io.to(roomId).emit('createMessage', message)
        })
    })
})
server.listen(process.env.PORT || 3000)

##room.ejs##
 !DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Zoom-Clone</title>
    <script src="/socket.io/socket.io.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
    <script src="https://kit.fontawesome.com/c939d0e917.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        const ROOM_ID = "<%= roomId %>";
    </script>
</head>
<body>
    <div class="main">
        <div class="main_left">
            <div class="main_videos">
                <div id='video-grid'>

                </div>
            </div>
            <div class="main_controls">
                <div class="main_controls_block">
                    <div onclick="muteUnmute()" class="main_controls_button main_mute_button">
                        <i class="fas fa-microphone"></i>
                        <span>Mute</span>
                    </div>
                    <div onclick="playStop()" class="main_controls_button main_video_button">
                        <i class="fas fa-video"></i>
                        <span>Stop Video</span>
                    </div>
                </div>

                <div class="main_controls_block">
                    <div class="main_controls_button">
                        <i class="fas fa-shield-alt"></i>
                        <span>Security</span>
                    </div>
                    <div class="main_controls_button">
                        <i class="fas fa-user-friends"><              <span>Participants</span>
                    </div>
                    <div class="main_controls_button">
                        <i class="fas fa-comment-alt"></i>
                        <span>Chat</span>
                    </div>
                </div>
                <div class="main_controls_block">
                    <div class="main_controls_button">
                        <span class="leave_meeting">Leave Meeting</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="main_right">
            <div class="main_header">
                <h6>Chat</h6>
            </div>
            <div class="main_chat_window">
                <ul class="messages">

                </ul>
            </div>
            <div class="main_message_container">
                <input id="chat_message" type="text" placeholder="Type message here...">
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html> 
###script.js###
 
const socket = io('/');
const videoGrid = document.getElementById('video-grid');
const myVideo = document.createElement('video');
myVideo.muted = true;
var peer = new Peer(undefined, {
    path: '/peerjs',
    host: '/',
    port: '3001'
});
let myVideoStream;
const addVideoStream = (video, stream) => {
    video.srcObject = stream;
    video.addEventListener('loadedmetadata', () => {
        video.play();
    })
    videoGrid.append(video);
};
const connectToNewUser = (userId, stream) => {
    const call = peer.call(userId, stream);
    const video = document.createElement('video');
    call.on('stream', userVideoStream => {
        addVideoStream(video, userVideoStream);
    })
}
const scrollToBottom = () => {
    let d = $('main_chat_window');
    d.scrollTop(d.prop("scrollHeight"));
}
const setMuteButton = () => {
    const html = `
    <i class="fas fa-microphone"></i>
    <span>Mute</span>`
    $('.main_mute_button').html(html);
}
const setUnmuteButton = () => {
    const html = `
    <i class="unmute fas fa-microphone-slash"></i>
    <span>Ummte</span>`
    $('.main_mute_button').html(html);
}
const muteUnmute = () => {
    const enabled = myVideoStream.getAudioTracks()[0].enabled;
    if (enabled) {
        myVideoStream.getAudioTracks()[0].enabled = false;
        setUnmuteButton();
    }
    else {
        setMuteButton();
        myVideoStream.getAudioTracks()[0].enabled = true;
    }
}
navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true
}).then(stream => {
    myVideoStream = stream;
    addVideoStream(myVideo, stream);
    peer.on('call', call => {
        call.answer(stream)
        const video = document.createElement('video')
        call.on('stream', userVideoStream => {
            addVideoStream(video, userVideoStream)
        })
    })
    socket.on('user-connected', (userId) => {
        connectToNewUser(userId, stream);
    })
})
peer.on('open', id => {
    socket.emit('join-room', ROOM_ID, id);
});
let text = $('input');
$('html').keydown(e => {
    if (e.which == 13 && text.val().length !== 0) {
        socket.emit('message', text.val());
        console.log(text.val());
        text.val('')
    }
});
socket.on('createMessage', message => {
    $('ul').append(`<li class="message"><b>user</b><br />${message}</li>`)
    scrollToBottom();
})
const setPlayVideo = () => {
    const html = `
    <i class="stop fas fa-video-slash"></i>
    <span>PlayVideo</span>`
    $('.main_video_button').html(html);
}
const setStopVideo = () => {
    const html = `
    <i class="fas fa-video"></i>
    <span>Stop Video</span>`
    $('.main_video_button').html(html);
}
const playStop = () => {
    let enabled = myVideoStream.getVideoTracks()[0].enabled;
    if (enabled) {
        myVideoStream.getVideoTracks()[0].enabled = false;
        setPlayVideo();
    }
    else {
        setStopVideo();
        myVideoStream.getVideoTracks()[0].enabled = true;
    }
} 

What is the correct way to update another websocket realtime data?

Server part:

I have an ASR voice recognition AI model, it will generate data like below and use websocket to pass data to my server.

{ id: 1, segment: 1, data: "I am glad", final: false }
{ id: 2, segment: 1, data: "I am glad to": final: false }
{ id: 3, segment: 1, data: "I am glad to see you", final: true },
...
{ id: 50, segment: 3, data: "something other data...", }

On the other hand, my server has a bridge websocket to get and store ASR data then pass data to the clients.


Client Part:

When client get data from my websocket server, it would allow client to update the realtime data. So I use websocket to send back to the bridge websocket server. BTW, I can’t wait ASR segment to be final.

{ update: true, segment: 1, original: "I am glad", replaced: "I am v glad" }
{ update: true, segment: 1, original: "I am glad", replaced: "I am ve glad" }
{ update: true, segment: 1, original: "I am glad to", replaced: "I am ver glad to" }

My question is like how to design the bridge websocket server or there has a 3rd library I can use to handle this situation? Because when I use this pattern trying to update data, it doesn’t work correctly. The main reason is that I can’t handle ASR model generated time.

ex: I send update message to the server, but at the meantime ASR also send message to the client.

On my website, the sequence would be like

  1. I am glad
  2. I am v glad <== typing v send message to the server
  3. I am glad to <== because the ASR send back first, v character disappear ;(
  4. I am v glad to <== next render, it will replace

Below is my code:

let asrWS, timeout;

recordWS.on("connection", async (ws) => {
  console.log("record socket connected");

  ws.on("error", () => {});

  ws.on("message", async (event) => {
    const evt = JSON.parse(event);

    if (evt.status) {
      try {
        if (evt.status === "start") {
          sendStatus("pending");

          const token = await login();
          const { wsHost, ticket } = await getStreamInfo(token);
          // connect to ASR websocket, store ASR data then broadcast to the clients
          asrWS = await connectWS(wsHost, ticket, recordWS); 

          start(asrWS);
          sendStatus("recording");
        } else if (evt.status === "stop") {
          stop();

          if (asrWS) {
            asrWS.close();
          }

          sendStatus("stop");

          timeout = setTimeout(() => {
            sendStatus("start");
          }, 3000);
        }
      } catch (error) {
        console.warn(error);
      }
    }

    if (evt.update) {
      // update ASR global data
      setTranscripts(+evt.segment, evt.original, evt.replaced, "update");
      console.log(getTranscripts());
    }
  });

  ws.on("close", () => {
    if (timeout) {
      clearTimeout(timeout);
    }
    console.log("Disconnected record");
  });
});
function connectWS(wsHost, ticket, recordWS) {
  const webSocketUrl = `${wsHost}?ticket=${encodeURIComponent(
    ticket
  )}&modelName=${modelName}&rate=16000`;

  const asrWS = new WebSocket(webSocketUrl, {
    binaryType: "arraybuffer",
  });

  asrWS.onopen = () => {
    console.log("open ASR server connection");
  };

  asrWS.onerror = (error) => {
    console.error(`ASR server encountered error: ${error.message}`);
    asrWS.close();
  };

  asrWS.onmessage = (event) => {
    let d = JSON.parse(event.data);

    // ...

    const transcripts = getTranscripts();
    const current = transcripts[+d.result.segment];

    if (current) {
        const re = new RegExp(current.original, "i");
        d.t= d.t.replace(re, current.replaced);
    }
    
    d = JSON.stringify(d);

    recordWS.clients.forEach((client) => {
      client.send(d);
    });
  }

  
  asrWS.onclose = (event) => {
    console.log(`Close ASR server connection ${event.code}`);
  };

  return new Promise((resolve) => asrWS.once("open", () => resolve(asrWS)));
}

Discord JS slash command zodError?

Whenever I run my code I get an odd error from my slash command file here is the error.
I have checked for capital names in the slash command and my command handler though I cant seem to figure it out perhaps you can help me?

  {
    "code": "invalid_type",
    "expected": "string",
    "received": "undefined",
    "path": [],
    "message": "Required"
  }
]
    at handleResult (/home/runner/MI6Agent/node_modules/zod/lib/types.js:28:23)
    at ZodString.safeParse (/home/runner/MI6Agent/node_modules/zod/lib/types.js:140:16)
    at ZodString.parse (/home/runner/MI6Agent/node_modules/zod/lib/types.js:120:29)
    at Y (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:5798)
    at b (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:5893)
    at te.runRequiredValidations (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:6930)
    at te.toJSON (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:7116)
    at /home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:12954
    at Array.map (<anonymous>)
    at MixedClass.toJSON (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:12945)
    at /home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:13239
    at Array.map (<anonymous>)
    at MixedClass.toJSON (/home/runner/MI6Agent/node_modules/@discordjs/builders/dist/index.js:3:13230)
    at Object.<anonymous> (/home/runner/MI6Agent/index.js:33:30)
    at Module._compile (node:internal/modules/cjs/loader:1101:14) 

Here is my slash command.

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('inform')
    .setDescription('Informs the specified user in DMs.')
    .addSubcommand(command => command
      .setName('channel')
      .setDescription('Sends a message to an channel')
      .addChannelOption(option => option.setName('target').setDescription('Select the target channel').setRequired(true)).addBooleanOption(option => option.setName('incognito').setRequired(true)))
    .addSubcommand(command => command
      .setName('member')
      .setDescription('Sends a message to an member')
      .addUserOption(option => option.setName('target').setDescription('Select the target user').setRequired(true)).addBooleanOption(option => option.setName('incognito').setRequired(true)))
  .addSubcommand(command => command
      .setName('role')
      .setDescription('Sends a message to an member')
      .addRoleOption(option => option.setName('target').setDescription('Select the target role').setRequired(true)).addBooleanOption(option => option.setName('incognito').setRequired(true))),
}

Add number to incrementing list on button click in JavaScript not working

Ok so in my code I’m supposed to enter a number between 4 and 15. Then I click a button to add it, Once that happens the number will be added to the total number of ages and to one of the leagues I have created (it should be incremented by 1, for example, if I enter a 12 it will be 1 if I enter 12 again the total will say 2). When I try and run the code it does nothing.

<html>
<head>
<title>Soccer Manager</title>
<script>
function addAge()
{
// gets the input age
var age = Number(document.getElementById("age").value);

// clears the input field
document.getElementById("age").value = "";

// checks if age is between 4 and 15
if(age >= 4 && age <= 15){
// table cell to display total number of children
var total = document.getElementById("total");

// table cell to display total number of junior
var junior = document.getElementById("junior");

// table cell to display total number of intermediate
var intermediate = document.getElementById("intermediate");

// table cell to display total number of senior
var senior = document.getElementById("senior");

// increase total number of children by 1
total.innerHTML = Number(total.innerHTML) + 1;

// if its a junior age
if(age<=7)

// increase total number of junior by 1
junior.innerHTML = Number(junior.innerHTML) + 1;


// if its a intermediate age
else if(age<=11)

// increase total number of intermediate by 1
intermediate.innerHTML = Number(intermediate.innerHTML) + 1;


// else it will be a senior age
else

// increase total number of senior by 1
senior.innerHTML = Number(senior.innerHTML) + 1;

}

// if age is not between 4 and 15 alert an error
else{
window.alert("Age should be between 4 and 15");
}
}
}
</script>
</head>
<body>

<center>
<h1>
Soccer Manager
</h1>
<div>

<table>
<tr>
<th>Total Children</th>
<td id="total">0</td>
</tr>
<tr>
<th>Junior</th>
<td id="junior">0</td>
</tr>
<tr>
<th>Intermediate</th>
<td id="intermediate">0</td>
</tr>
<tr>
<th>Senior</th>
<td id="senior">0</td>
</tr>
</table>


<input type="number" placeholder="Age"  id="age">

<button onClick="addAge()">Add</button>
</div>
</center>
</body>


</html>