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 = "";
}```

shorted Jquery by using each() function

How can i shorted this jquery by using each() function? or have another method to shorted this jquery?

            $("div.body-t-option-1").hover(function() {
                $(".body-t-img-2,.body-t-img-3,.body-t-img-4").hide();
                $(".body-t-img-1").show();
                $(".body-t-img-1").addClass('animated fadeInLeft');
            });

            $("div.body-t-option-2").hover(function() {
                $(".body-t-img-1,.body-t-img-3,.body-t-img-4").hide();
                $(".body-t-img-2").show();
                $(".body-t-img-2").addClass('animated fadeInLeft');
            });

            $(".body-t-option-3").hover(function() {
                $(".body-t-img-1,.body-t-img-2,.body-t-img-4").hide();
                $(".body-t-img-3").show();
                $(".body-t-img-3").addClass('animated fadeInLeft');
            });

            $(".body-t-option-4").hover(function() {
                $(".body-t-img-1,.body-t-img-2,.body-t-img-3").hide();
                $(".body-t-img-4").show();
                $(".body-t-img-4").addClass('animated fadeInLeft');
            });

Swiper.js SwiperSlide render props not working properly with Swiper loop set to true

I’m kinda stucked into a problem where isPrev and isNext SwiperSlide render props are not working correctly in a Swiper with loop prop set into true. Here is my code:

export default function FadingSwiper() {
  const handleSwipeFade = (isActive, isNext, isPrev) => {
    if (isActive) return "translate-x-0";
    else if (isPrev) return "translate-x-[-20px]";
    else if (isNext) return "translate-x-[20px]";
  };

  return (
    <Swiper
      slidesOffsetAfter={0}
      modules={[Navigation, Pagination, EffectFade]}
      navigation={true}
      speed={500}
      effect={"fade"}
      fadeEffect={{
        crossFade: true,
      }}
      loop={true}
    >
      <SwiperSlide>
        {({ isActive, isPrev, isNext }) => (
          <div
            className={`transition-all duration-[1.2s] w-full h-full ${handleSwipeFade(
              isActive,
              isPrev,
              isNext
            )}`}
          >
            <div className="flex justify-center items-center w-full h-full">
              <div>SLIDE 1</div>
            </div>
          </div>
        )}
      </SwiperSlide>
      <SwiperSlide>
        {({ isActive, isPrev, isNext }) => (
          <div
            className={`transition-all duration-[1.2s] w-full h-full ${handleSwipeFade(
              isActive,
              isPrev,
              isNext
            )}`}
          >
            <div className="flex justify-center items-center w-full h-full">
              <div>SLIDE 2</div>
            </div>
          </div>
        )}
      </SwiperSlide>
      <SwiperSlide>
        {({ isActive, isPrev, isNext }) => (
          <div
            className={`transition-all duration-[1.2s] w-full h-full ${handleSwipeFade(
              isActive,
              isPrev,
              isNext
            )}`}
          >
            <div className="flex justify-center items-center w-full h-full">
              <div>SLIDE 3</div>
            </div>
          </div>
        )}
      </SwiperSlide>
      <SwiperSlide>
        {({ isActive, isPrev, isNext }) => (
          <div
            className={`transition-all duration-[1.2s] w-full h-full ${handleSwipeFade(
              isActive,
              isPrev,
              isNext
            )}`}
          >
            <div className="flex justify-center items-center w-full h-full">
              <div>SLIDE 4</div>
            </div>
          </div>
        )}
      </SwiperSlide>
    </Swiper>
  );
}

What I am trying to achieve is to have a fading transform effect that depends on which direction you’ve swiped, for example if you swiped or navigate the component to the left, the current slide fades and transforms to the left and the next slide goes in fading also from the left, and then vice versa.

The problem is that in this code, the isNext or isPrev is not being set into true on some of the looping slides(the new slides made after the last initial slide), specifically on the 2nd slide or 2nd to the last slide. This does not satisfy the if condition in my handleSwipeFade function and thus not having the transform effect I wanted.

Any ideas or workarounds on this?

how to create multiple x-axis datasets labels by using chart.js

i’m using chart.js to draw line charts. and currently there is a need is to draw 3 different lines. they have same y-axis dataset, but the x-axis datasets are different. like:

y-axis datasets: [2,4,6,8,10]
x-axis1 datasets: [1,2,3,4,5]
x-axis2 datasets: [5,6,7,8,9]
x-axis3 datasets: [8,9,10,12,14]

i want the x-axis range is 1 to 14. and display them by each datasets real value.

however, i investigated and just found the way to use different x-axis labels by xAxisID, but in this way, the x-axis2 and x-axis3 are still using 1,2,3,4,5 as x-axis dataset.

dose anyone know how can i achieve this? thanks a lot!

Viết chương trình Java sử dụng cấu trúc dữ liệu danh sách liên kết [closed]

Viết chương trình Java sử dụng cấu trúc dữ liệu danh sách liên kết đơn để lưu trữ thông tin
của đối tượng. Thông tin đối tượng được chọn lọc dựa vào tên họ của sinh viên. Ví dụ sinh
viên tên Nguyen Van An -> dự kiến sẽ chọn đối tượng (tiếng anh) là Nurse gồm các thuộc
tính như code, name, inhabitant và food (bắt buộc tối thiểu 4 thuộc tính có int và String)

  1. Viết class khai báo Nurse và Node
  2. Viết class cài đặt tương ứng của cấu trúc dữ liệu trên với các phương thức sau:
  • Thêm phần tử vào đầu danh sách
  • Xóa phần tử từ đầu danh sách
  • In danh sách liên kết theo thứ tự đảo ngược
  • Tìm kiếm Nurse dựa trên tên nhập vào
  1. Xây dựng các chương trình con thực hiện các nhiệm vụ sau

How trigger an event individually to different instances of the same id

I have a list and I want to trigger an event individually with the same javascript code without define an id for each. For example, I want when I click each item the inner text changes to the color it says. In other words, I want the code knows where I’m clicking and apply the function to that particular item, and don’t want to use id=color1″, id=color2″, id=color3″. Any help appreciated!

<ul>
<li onclick="jsCode" id="color">Red<li>
<li onclick="jsCode" id="color">Blue<li>
<li onclick="jsCode" id="color">Green<li>
</ul>

Getting JS object values from html input

So basically my issue is that I’m looking to get some data from an object. The object is picked from and html tag and the selected option is put into a function. The function handles getting the data but throws an error when trying to get the length of an array found inside the object. getRandInRange is a function I created that works perfectly so that is not the issue.

When I run the code in the browser this is the error I get

Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at buildHorde (app.js:46:60)
    at setValue (app.js:33:5)
    at HTMLInputElement.onclick (index.html:27:101)
function buildHorde(obj,num){
    // for every num add a random coin roll
    for (i = 0; i < num; i ++){
        coinArr.push(obj.coins[getRandInRange(0, obj.coins.length-1)]);
    }
    // following lines add the new arrays into the html document.
    document.getElementById("coins").innerHTML = coinArr;
    return;
}
<p>Select Party Level: <select name="Party Level" id="getObj">
    <option value=level1>level1</option>
    <option value=level2>level2</option>
</select></p>

And this is the code to set the arguments in the function

function setValue(){
    var select = document.getElementById('getObj');
    obj = select.options[select.selectedIndex].value
    num = document.getElementById('getNum').value;
    buildHorde(obj,num);
}

await fetch(url) stopped working in Safari 15.5

Been using “await fetch(url)” in a project for quite some time now and today I noticed Safari 15.5 doesn’t return the url.

I’m running MacOS 12.4.

Chrome still works correctly.

Checked on a Mac with Safari 15.3 and that one still works.

The same code still works fine from iOS 15.5 Safari.

Happens on different urls. Happens in private mode too.

How do I make my text strikethrough on click with node?

I’m making a todo list with express/node. I’m having a hard time making the text strikethrough on click after you add something to do list, and my group is pretty stumped.

This project was originally created in with just html and javascript, but for another project we have to do, we had to make it working using node and mongo. I’m having a hard time making it strikethrough on click (as well as having nothing populate when there is no text added in the input bar. Right now, if you click, it’ll show empty spots, instead of showing nothing).

This is my index.ejs:

<ul id="ulForItems">
            <% for(var i=0; i<tasks.length; i++) {%>
                <% let lineThrough = tasks[i].completed ? 'line-through' : 'none' %>
                <li>
                  <span style='text-decoration: <%= lineThrough %> '><%= tasks[i].task %></span>
                  <span class="complete"></span>
                </li>
              <% } %>
        </ul>

This is my main.ejs:

let complete = document.getElementsByClassName("complete");
let trash = document.getElementsByClassName("delete");

Array.from(complete).forEach(function(element) {
      element.addEventListener('click', function(event){
        const listItem = this.parentNode.childNodes[1].innerText
        fetch('/editTask', {
          method: 'put',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            'task': listItem,
            'completed' :false
          })
        })
        .then(response => {
          if (response.ok) return response.json()
        })
        .then(data => {
          console.log(data)
         window.location.reload(true)
        })
      });
});

Array.from(trash).forEach(function(element) {
      element.addEventListener('click', function(){
        fetch('/deleteList', {
          method: 'delete',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
          })
        }).then(function (response) {
          window.location.reload()
        })
      });
});

This is my server.js:

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));

app.get("/", (req, res) => {
  db.collection("tasks")
    .find()
    .toArray((err, result) => {
      if (err) return console.log(err);
      console.log(result);
      res.render("index.ejs", { tasks: result });
    });
});

app.post("/addTask", (req, res) => {
  db.collection("tasks").insertOne(
    {
      task: req.body.task,
      completed: false,
    },
    (err, result) => {
      if (err) return console.log(err);
      console.log("saved to database");
      res.redirect("/");
    }
  );
});

app.put("/editTask", (req, res) => {
  console.log(req.body);
  db.collection("tasks").findOneAndUpdate(
    { task: req.body.task, completed: false },
    {
      $set: {
        completed: true,
      },
    },
    {
      sort: { _id: -1 },
      upsert: false,
    },
    (err, result) => {
      if (err) return res.send(err);
      res.send(result);
    }
  );
});

app.delete("/deletelist", (req, res) => {
  db.collection("tasks").deleteMany({}, (err, result) => {
    if (err) return res.send(500, err);
    res.send("Message deleted!");
  });
});

Please let me know if you need more information!

Can I write regular expressions and use .test() like this in javascript?

Okay, I am very new to javascript and have a question regarding using regular expressions in it.

Can I write regular expressions and use .test() like this for a message based response of a discord bot to test and give a message reply like this based on if it matches:

let myRegex = /morning/i;
    if (myRegex.test(msg.content)) {
       msg.reply("Good Morning!");
    }

    myRegex = /some text/i;
    if (myRegex.test(msg.content)) { 
       msg.reply("Bot replies to some text");
    }

    myRegex = /some other text/i;
    if (myRegex.test(msg.content)) { 
       msg.reply("bot replies to some other text");
    }

It seems to work but while executing it. But for some reason, it feels like this is the wrong way of doing things as I am specifying myRegex each time before the .test().


Before this, I was initially using if statements like this but the issue there was that I had to write a separate message when there were more words as it would only check for that exact message:

if (msg.content.toLowerCase() === 'morning') {
          msg.reply('https://media.giphy.com/media/34dapC0zP8iSQ0wjHX/giphy.gif ');
    }

I have noticed that the second code would only work for message inputs such as ‘morning’ or ‘MoRnING’ or ‘MORNING’, but wouldn’t work for ‘good morning’ or ‘GooD MoRnIng’ ‘GOOD MORNING’ etc.

So, I am thinking of moving to regular expressions, but I want to make sure that I am doing it right.

Can someone please help me out with this?

TypeScript: How to define a type with nested objects

I’m trying to define this object type.

colors: {
  text: "#343D48", // body color and primary color
  text_secondary: "#02073E", // secondary body color
  heading: "#565F67", // primary heading color
  heading_secondary: "#0F2137", // heading color
  background: "#FFFFFF", // body background color
  background_secondary: "#F9FBFD", // secondary background color
  border_color: "#E5ECF4", // border color
  primary: "#78F0AC", // primary button and link color
  secondary: "#29CC5F", // secondary color - can be used for hover states
  muted: "#7B8188", // muted color
  dark: "#343D48",
  accent: "#609", // a contrast color for emphasizing UI
  yellow: "#F6C416",
  error: "#F65241",

  // highlight  a background color for highlighting text
  modes: {
    dark: {
      text: "#fff",
      background: "#000",
      primary: "#0cf",
      secondary: "#09c",
      muted: "#111",
    },
  },
},

This is what I wrote so far, I’m not sure how to define nested objects with TypeScript. How do I define the type for the code above? This is what I have so far:

export type Color = {
[colorName: string]: string;
};