trying to generate array using recursion in javascript but getting undefined value [duplicate]

I am trying to generate an array of 3 random numbers representing the 3 RGB values using recursion, but getting undefined in the console can you please explain what is the problem and how can I solve it.

const randomColor = (currColor = []) => {
  let color = currColor;
  color.push(Math.floor(Math.random() * 255 + 1));
  if (color.length === 3) return color;
  else {
    randomColor(color);
  }
};

const rc = randomColor();
console.log(rc);

how to validate phone no onclick in react?

i want to validate phone no onClick of a button. This is what I have done, I am new to reactjs. please help me in this. When I click submit that time it will show error message

const [phoneNo, setPhoneNo] = useState(false)
const [errorMessage, setErrorMessage] = useState("")

const validateFunc = () => {
  setPhoneNo(true)
}

const onChangeValidate= (e) => {
   var phone = e.target.value;
   if( !(phone.match('[0-9]{10}')) ){
     setPhoneNo(false);
     setErrorMessage("Please enter 10 digit")
    }else{
    }
    setPhoneNo(true)
   }




----
<input onChange ={() => onChangeValidate(e)} />
<button onClick = {validateFunc()}>Submit</button>
<p>{errorMessage}</p>

How to create a size responsive independantly scrolling section in vanilla html

I have a scrolling issue that might be common but I can’t seem to find it. Essentially, I have a scrollable section of a webpage that goes from just below the header to the bottom of the screen. However, to make that section scrollable, I have to set a height which I set as 70vh, while the header is a static height. When the viewport changes height, to a larger screen for example, the 70vh isn’t enough to reach the bottom of the screen because it now should proportionally take up more space.

My question is, how do I make it so that the section is always the correct height when the viewport changes size. An idea I had was to find the percentage of the viewport height that the header is taking up and then detract that from 100 variably, but I have no clue how to do that.

I can’t add images in my post yet but this is a link to what the section looks like

jQuery.get() is not a function

When I try to run this code I get an error jQuery.get is not a function. According to the documentation it should work but it doesn’t seem to run here.

// Run dotenv
const jQuery = require('jquery');
require('dotenv').config();


const Discord = require('discord.js');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });

client.on('ready', () => {
    console.log(`Started bot as ${client.user.tag}.`);
});

client.on('messageCreate', msg => {
    if (msg.content.charAt(0) === '?') {
        if (msg.content === '?g') {
            let d = new Date();
            let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
            msg.reply("On " + d.getDate() + " " + months[d.getMonth()] + "" + Date.now());
            jQuery.get("https://example.com/");
        } else {
            const reply = "Debug";
            msg.reply(reply);
            console.log("Recieved: " + msg.content + "nReply: " + reply);
        }   
    }
});

client.login(process.env.DISCORD_TOKEN);

How to create dynamic onclick elements in vuejs without repeating same value

I am trying to create a form in vuejs, where a group of inputs can be append onclick. It works fine, but the problem is, All inputs return the same value. I am sharing an image here :

enter image description here

I am sharing my code from template :

<div class="form-group" v-for="(input,k) in data.invoice_product" :key="k">
    <div class="row mb-2">
         <div class="col-md-3">
              <select class="form-control" v-model="data.invoice_product.product_id" 
               @change="getProductCost">
                  <option v-for="(product, i) in products" :key="i" :value="product.id">{{ 
                  product.product_name }}</option>
               </select>
         </div>
         <div class="col-md-3">
              <input type="text" class="form-control" placeholder="Quantity" v- 
               model="data.invoice_product.quantity" @keyup="getProductCost">
         </div>
         <div class="col-md-3">
              <input type="text" class="form-control" placeholder="Total" v- 
              model="data.invoice_product.total">
         </div>
         <div class="col-md-3">
              <span>
                   <i class="fa fa-minus-circle" @click="removeElement(k)" v-show="k || ( !k 
                   && data.invoice_product.length > 1)">Remove</i>
                   <i class="fa fa-plus-circle" @click="addElement(k)" v-show="k == 
                   data.invoice_product.length-1">Add fields</i>
              </span>
          </div>
     </div>
 </div>

from my script (I am excluding irrelevant code segments) :

export default {
data() {
    return {
        data : {
            customer_id : '',
            vat : '',
            invoice_product : [{
               product_id : '',
               quantity : '',
               total : ''
            }]
        },
        products : []
    }
},

methods : {
   addElement() {
       this.data.invoice_product.push({
            product_id : '',
            quantity : '',
            total : ''
       })
    },

    removeElement (index) {
       this.data.invoice_product.splice(index, 1)
    },
}

Onclick anywhere on word get position number of word inside textarea – JQuery

this is my code. It works only when I click on the first letter of any word. Then it gives me the position of that word like 0 for first word, 1 for second and etc. But when when I click on middle or anywhere then It don’t take position number until I don’t click on the start of first letter.
Here’s how my code is running:

$("#checktext").on('click', function(e) {
         var text = document.getElementById("checktext").value,
        element = $("#checktext")[0],
        arr1 = text.split(" "),
        length = 0,
        selectIndex = element.selectionStart;
         if (selectIndex == 0) {
        console.log(arr1.indexOf(arr1[0]));
         } else {
        for (var i = 0; i < arr1.length; i++) {
             length = length + arr1[i].length + 1;
             if (length == selectIndex) {
            console.log(i + 1);
            break;
             }
        }
        }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script>
<textarea id="checktext">This will only work if click on start of each letter.</textarea>

regex match and replace in vscode for repetitive pattern

I have this svg

<circle id="a/b/c" stroke="#2C2C2C" stroke-width="2" fill="#FFF" fill-rule="nonzero" cx="141" cy="21" r="9"/><text id="a/b/c-something" font-size="10" fill="#2C2C2C"><tspan x="0" y="10">a/b/c Something</tspan></text>

I want to replace id="a/b/c" to id="a-b-c" in the circle and also
id="a/b/c-something" to id="a-b-c-something" in text
and exclude a/b/c Something from being replaced.

I’m using vscode, and I’ve tried (id=.+)/(.+) but it doesn’t seem to match it properly. I want to

Enabling image to open Window using Winbox.js

I would like to know what I’m doing wrong since I used all the documentation in order to use Winbox.js (link here) I will share below my HTML, CSS, and js just to see if anyone can help me figure this out. I would like it to once I click on either the folder image and/or the folder name a winbox pops up.enter image description here

HTML:

<div class="desktopContainer">
      <div class="desktop-icon">
        <div class="folder text-center" id="aboutme-folder">
          <img src="../../media/desktop_ico_folder.png" class="" alt="aboutme-icon">
          <p id="folder-name">About Me</p>
        </div>
        <div class="folder text-center" id="projects-folder">
          <img src="../../media/desktop_ico_folder.png" class="" alt="projects-icon">
          <p id="folder-name">Projects</p>
        </div>
        <div class="folder text-center" id="experience-folder">
          <img src="../../media/desktop_ico_folder.png" class="" alt="experience-folder">
          <p id="folder-name">Experience</p>
        </div>
        <div class="folder text-center" id="travels-folder">
          <img src="../../media/desktop_ico_folder.png" class="" alt="travels-folder">
          <p id="folder-name">Travels</p>
        </div>
      </div>
    </div>

CSS:

.desktopContainer {
  position: relative;
  min-height: calc(75vh + 10px);
  width: 100%;
  bottom: -35px;
  /*border: 3px solid #8AC007;*/
  margin: 0 auto;
  overflow: hidden;
}

.folder {
  box-sizing: border-box;
  width: 150px;
  height: 100px;
  padding: 20px;
  margin-right: -10px;
  margin-left: -30px;
  /*border: 2px dashed purple;*/
  float: right;
}

.folder img {
  max-width: 100%;
  height: 100%;
}

.folder p {
  margin: 0;
  font-family: SF;
  font-weight: bolder;
  src: url(../../Fonts/SF-UI-Display-Regular.otf);
}

JS:

const aboutmeFolder = document.querySelector('#aboutme-folder')
const projectsFolder = document.querySelector('#projects-folder')
const experienceFolder = document.querySelector('#experience-folder')
const travelsFolder = document.querySelector('#travels-folder')

aboutmeFolder.addEventListener('click', () => {
  new WinBox()
})

projectsFolder.addEventListener('click', () => {
  new WinBox()
})

experienceFolder.addEventListener('click', () => {
  new WinBox()
})

travelsFolder.addEventListener('click', () => {
  new WinBox()
})

How to get most repeated object property value using lodash? [closed]

I am new to lodash and was wondering how I could use it to get the most repeated property value in an object array. Like say I have an array such as

var arr1 = [{points: 50, player: LeBron James},{points: 32, player: Kevin Durant},{points: 62, player: LeBron James},{points: 90, player: LeBron James}]

In the player property in arr1, “LeBron James” is the most repeated. How would I get this using lodash? Thanks again.

Failed to convert web-saved .wemb audio to .wav by using php “shell_exec” and javascript

I’m working on an online experimenter which could record participants’ audio from the browser. The audio data I get has an extension of .wemb, so I plan to use ffmpeg to convert it to .wav while I save the data.

I tried to use PHP’s shell_exec but nothing happens when I run the scripts. Then I found that my echo and print_r also did not work. I’m new to PHP and javascript, so I”m really confused now.

Below are the relevant codes, I really appreciate it if you could help!

write_data.php:

<?php
  $post_data = json_decode(file_get_contents('php://input'), true); 
  // the directory "data" must be writable by the server
  $name = "../".$post_data['filename'];
  $data = $post_data['filedata'];
   // write the file to disk
  file_put_contents($name, $data);
  
  $INPUT = trim($name) . ".webm";
  $OUTPUT = trim($name) . ".wav";
  echo "start converting...";

  // check if ffmprg is available
  $ffmpeg = trim(shell_exec('which ffmpeg'));
  print_r($ffmpeg);
  // call ffmpeg
  shell_exec("ffmpeg -i '$INPUT' -ac 1 -f wav '$OUTPUT' 2>&1 ");
?>

javascript:

  saveData: function(fileName,format){
    // save  as json by default
    if (!format){ format = 'json';}
    // add extension to filename
    fileName = `${fileName}.${format}`
    // create saveData object using fetch
    let saveData = [];
    if (format == 'json') {
        saveData = {
          type: 'call-function',
          async: true,
          func: async function(done) {
            let data = jsPsych.data.get().json();
            const response = await fetch("../write_data.php", {
              method: "POST",
              headers: {
                "content-type": "application/json"
              },
              body: JSON.stringify({ filename: fileName, filedata: data })
            });
            if (response.ok) {
              const responseBody = await response.text();
              done(responseBody);
            }
          }
        }
    } else {
        saveData = {
          type: 'call-function',
          async: true,
          func: async function(done) {
            let data = jsPsych.data.get().csv();
            const response = await fetch("../write_data.php", {
              method: "POST",
              headers: {
                "content-type": "application/json"
              },
              body: JSON.stringify({ filename: fileName, filedata: data })
            });
            if (response.ok) {
              const responseBody = await response.text();
              done(responseBody);
            }
          }
        }
    }
    return saveData;
  },

I want to fix the proportions of a square in three.js

Renderer

import { WebGLRenderer } from 'three'
    
    class Renderer {
      constructor(element) {
        this.renderer = new WebGLRenderer({ antialias: true, alpha: true })
    
        this.setRenderer(element)
      }
    
      setRenderer(element) {


        this.renderer.setPixelRatio(1)
        this.renderer.shadowMap.enabled = true
        this.renderer.setSize(element.clientWidth || window.innerWidth, element.clientHeight || window.innerHeight)
    
        element.appendChild(this.renderer.domElement)
      }
    
      get domElement() {
        return this.renderer.domElement
      }
    
      get rendererElement() {
        return this.renderer
      }
    }
    
    export { Renderer }

Camera

import { CinematicCamera } from 'three/examples/jsm/cameras/CinematicCamera'

class Camera {
  constructor() {
    this.camera = new CinematicCamera(1000, 1, 1, 2000)

    this.setCamera()
  }

  setCamera() {
    this.camera.position.set(100, 100, 100)
  }

  get cameraElement() {
    return this.camera
  }
}

export { Camera }

I want to make a square, but it stretches and shrinks according to the aspect ratio.
How can I fix the proportions and only change the canvas size?

I’ve been advised to fix the size of the container, but I don’t know how to do it.

Pass A Function Down But Retain A Prop From Parent

I have 2 components. The parent is a mapped list. In each map render, there is a dropdown menu. The dropdown menu component has a handler prop that you pass a function to and it sends you back the data of the clicked item. See the simplified code below.



const ParantList = () => {
  const listData = [1,2,3]
  const handleClick = (x, i) => {
     // Here x will return data from the child
     // i returns nothing but I would like it to be the current index of listData
     return [x, i]
  }

  return (
    <div>
       {listData.map((x, i) => <Child handleClick={handleClick} /> )}
    </div>
  )
}

const Child = ({handleClick}) => {
  const differentList = [4,5,6]

  return (
    <Dropdown>
      {differentList.map(x => 
        <Dropdown.Item onClick={()=>handleClick(x)}>
           {x} 
        </Dropdown.Item>
    )}
    </Dropdown>)
}

The issue is in the handle click function in the parent, I need the data from the differentList in the child to pass to the function, which works fine. However, I also need the index or data from the corresponding item (listData) in which the drop-down was clicked in the parent map. So the handleClick function needs the data from both lists.

The simple solution is to pass down the current index of the listData list to the child. HOWEVER, in reality, the child component is a package that I can’t (or don’t know how to) change the function handler. Is there a simple way to pass a function to a child but pass a prop at the same time? Thank you!

How to write items with a particular key value from Firebase Realtime database

Some please consider a solution for me,
This is my database:
enter image description here

This is my database rules:enter image description here

Am trying to get how many users “referralcode” match any users “refercode”,
For example, this first user “refercode:” is “Fhb0VP7xje97” I want to know how many users from the whole database has this referral code in their “referralcode” value, and save the number to the “referno” value, so that the number of people referred by users would be visible to the user, so far I have tried this

Var referralcode=snapshot.val().referralcode;
Var refercode=snapshot.val().refercode;
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralcode').equalTo('refercode').get().then((results) => {
  console.log(Object.keys(results.val()).length);
  results.forEach((snapshot) => {
    console.log(snapshot.key, snapshot.val());
  });
});

But am getting this error:
enter image description here

Please can someone tell me what to do specifically?

Javascript addEventListener click Event doesn’t work [duplicate]

You see, I was starting a new project. But I encountered a problem. I want the user to choose an option and delete all other options but somehow it just doesn’t work. Btw I am using Chrome latest version. Just ignore the chinese words.

Here’s the HTML5:

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Rock Paper Scissors</title>
        <link rel="stylesheet" href="style.css">
    <body>
        <script src="script.js"></script>
        <p>
            </p><div class="Title-en" align="center" draggable="false">Rock Paper Scissors<br></div>
            <div class="Title-ch" align="center" draggable="false">石头剪刀布</div>
        </p>

        <div class="command-en" draggable="false">
            <p>Please select one</p>
        </div>

        <div class="command-ch" draggable="false">
            <p>请选择一个</p>
        </div>

        <div class="vertical-line"></div>

        <div draggable="false">
            <p id="img-rock">✊</p>
        </div>
        <div draggable="false">
            <p id="img-paper">✋</p>
        </div>
        <div draggable="false">
            <p id="img-scissors">✌</p>
        </div>
    </body>
</html>

Here’s the Javascript:

    let rock = document.getElementById("img-rock");
    let scissors = document.getElementById("img-scissors")
    let paper = document.getElementById("img-paper")
}

if (rock){
    rock.addEventListener("click", rock_del);
}

if(scissors){
    scissors.addEventListener("click", scissors_del);
}

if(paper){
    paper.addEventListener("click", paper_del);
}


function rock_del(){
    document.getElementById("img-scissors").innerHTML = "";
    document.getElementById("img-paper").innerHTML = "";
}```