Unable to add dougle digits in a calculator. Can only add single digit numbers

Like the title says. When I put single digit numbers, it works good but when I try to put bigger numbers like two digit numbers, it doesn’t work and I have no idea why. It seems like it reads only second digit of a second number, for example: 50 + 55(it’s read as a 5) so the result is 55. Same with 3 digits number, it only reads a third digit in the second number.

const calcDisplay = document.querySelector('.output');
calcDisplay.textContent = '0'

let num2 = calcDisplay.value

const add = (a, b) =>  a + b;
const subtract = (a, b) =>  a - b;
const multiply = (a, b) =>  a * b;
const divide = (a, b) => a / b;

//assigning calculator functions to operators' buttons //
  const buttonOperation = document.querySelectorAll('.keyButtonOperation').forEach(operator => {
  operator.addEventListener('click', () => {
  operator.classList.add('isDepressed')
  
    switch(operator) {
      case(operator === 'add'):
        return add(a, b)
       
      case(operator === 'substract'):
        return subtract(a, b)

      case(operator === 'multiply'):
        return multiply(a, b)

      case(operator === 'divide'):
        return divide(a, b)
        
    }  

   num2 = calcDisplay.textContent
  }) 
});

 //an event that make digits appear on the display // 
const buttons = document.querySelectorAll('.keyButton').forEach(button => {
button.addEventListener('click', () => {
  removeClass();
  num1 = button.textContent;
  displayedNum = calcDisplay.textContent;

    if (displayedNum === '0') {
      calcDisplay.textContent = num1;
  } else if (displayedNum === num2) {
      calcDisplay.textContent = num1
  } else  {
      calcDisplay.textContent = displayedNum + num1
  }
  
  });

});


const buttonEquals = document.querySelector('.keyButtonEquals');
buttonEquals.addEventListener('click', () => {
  if(add) {
    calcDisplay.textContent = parseInt(num1) + parseInt(num2)
   }
});





// Clears the whole display with one click //
const buttonClear = document.querySelector('.keyButtonClear');
buttonClear.addEventListener('click', () => {
  calcDisplay.textContent = '0'
  // I will fill up the rest of the code here when I get done with the rest //
  
});

// Deletes a single number when you click a button //
function deleteInput() {
  const deleteButton = document.querySelector('.keyButtonDelete')
  deleteButton.addEventListener('click', () => {
    calcDisplay.textContent = calcDisplay.textContent.slice(0, -1);

  });
}
deleteInput()

//removes a selection of a operator after a second number is clicked //
function removeClass () {
  buttonRemove = document.querySelectorAll('.keyButtonOperation').forEach(button => {
  button.classList.remove('isDepressed')

  });
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
        <link rel="stylesheet" href="./styles/style.css">
        <body>
          <div class="calcContainer">

            
            <div class="buttons">
              <div class="output">
              </div>
              <button class="keyButton">7</button>
              <button class="keyButton">8</button>
              <button class="keyButton">9</button>
              <button class="keyButtonOperation" data-action = "SignChange" >+/-</button>
              <button class="keyButtonDelete">DEL</button>

              <button class="keyButton">4</button>
              <button class="keyButton">5</button>
              <button class="keyButton">6</button>
              <button class="keyButtonOperation" data-action="multiply">X</button>
              <button class="keyButtonOperation" data-action="divide">%</button>

              <button class="keyButton">1</button>
              <button class="keyButton">2</button>
              <button class="keyButton">3</button>
              <button class="keyButtonOperation" data-action = "substract">-</button>
              <button class="keyButtonEquals">=</button>

              <button class="keyButtonClear">C</button>
              <button class="keyButton">0</button>
              <button class="keyButton">.</button>
              <button class="keyButtonOperation" data-action = "add">+</button>
            </div>
          </div>

            <script src="./scripts/script.js"></script>
        </body>
    </head>
</html>

Chartjs – Custom y axis ticks and labels

I’m using ChartJS 2.9.4 (restricted to V2 as generating PDFs using wkhtmltopdf) to build a line chart.

My problem is the data and I need to plot on the y axis.

Whilst the min/max ranges from 1-9 (with a 0.1 tick) it is impossible for some points within this range to be hit by the data and so I’d like to remove them and shift the other indexes down.

An example of the datapoints is:

1.1, 1.2, 1.3, 1.4, 1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.1

In this example I need to remove the points between 1.5/2.1 so the latter follows on directly from the former. Is this even possible?

I have also tried leaving the y axis points as standard and just generating the labels at these points but they don’t display unless the conditions in the switch satisfy label % 5 === 0 e.g. case 1.0/case 1.5 will display a label but case 1.1 will not.

My testing table is below:

<div class="month-graph">
    <canvas id="monthChart"></canvas>
</div>

new Chart(document.getElementById("monthChart").getContext('2d'), {
            type: 'line',
            data: {
                labels: ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August'],
                datasets: [{
                    data: [1.8, 2.9, 3.6, 4.6, 5.6, 6.7, 7.7, 8.9],
                    fill: false,
                    borderColor: 'rgb(252, 210, 1)',
                    tension: 0
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            min: 1,
                            max: 9,
                            stepSize: 0.1,
                            callback: function(label, index, labels) {
                                switch(label) {
                                    case 1.1:
                                        return 'Level 1';
                                    case 1.8:
                                        return 'Level 2';
                                    case 2.9:
                                        return 'Level 3';
                                    case 3.6:
                                        return 'Level 4';
                                    case 4.6:
                                        return 'Level 5';
                                    case 5.6:
                                        return 'Level 6';
                                    case 6.7:
                                        return 'Level 7';
                                    case 7.7:
                                        return 'Level 8';
                                }
                            }
                        },
                        gridLines: {
                            color: '#c2c2c2'
                        }
                    }],
                    xAxes: [{
                        gridLines: {
                            color: '#c2c2c2'
                        }
                    }]
                },
                legend: {
                    display: false,
                },
                animation: false,
                transitions: false
            }
        });




function that checks if a number is narcisstic or not

I run the code multiple times but couldn’t find the problem!!

A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

Your code must return true or false (not ‘true’ and ‘false’) depending upon whether the given number is a Narcissistic number in base 10.

function narcissistic(value) {
  let strDigits = value.toString();
  let power = strDigits.length;
  
  let arrayDigits = strDigits.split('');
  let sum, poweredValue = 0;
  for (let i = 0; i < power; i++){
   poweredValue = Number(arrayDigits[i])**power;
    sum += poweredValue;
  }
  if (sum === value){
    return true;
  }else {
    return false;
  }
  };
  

What is the best way to send both Image and JSON to my express server?

Ok, so I got a mongodb database, and I am using mongoose.

I have the following model for my product.

const productSchema = new Schema({
  name: { type: String, required: true},
  description: { type: String, required: true },
  price: { type: Number, required: true },
  image: { type: String, required: true },
  
  usage: { type: String, required: true },
  species: [{
    specie: { type: String, required: true }
  }],
  ingredients: [{
    name: { type: String, required: true },
    quantity: { type: String, required: true },
  }],
});

What I am trying to do is send both an image and JSON in a SINGULAR http request. I found out that this is not really possible. So what is the best to achieve this?
Send two different HTTP requests, one with the json/text data, and one with the file? This would mean that I need to edit my model and make the fields unrequired, and it would be a bit rough to debug in case something goes wrong with one of the requests.

Google Apps Script Sheet extract numbers as string

So I’m new to Google apps script and i’m trying to extract from a sheet a range of numbers but i want to extract them as string the way they are written on the sheet.
I used the getValues() function as such but the numbers are getting formatted example 12 becomes 12.0 and long ints like 14500536 becomes 14500536E7

  var X=sheet.getSheets()[0].getRange(5,1,lastrow-4);
  var rawX=X.getValues();

How does str.match() works?

If I clearly understand then in this example match finds all strings with length 0. And empty strings are in the beginning, ending and between all symbols in string so there is 11 empty string

const str = '0123456789';
const regexp = /|/g;
const matches = str.match(regexp);

console.log('Length = ' + matches.length);
console.log(matches);

In this example everything is clear. I just search digits so there are 10 digits:

const str = '0123456789';
const regexp = /d/g;
const matches = str.match(regexp);

console.log('Length = ' + matches.length);
console.log(matches);

But I don’t understand why I cann’t get 21 matches when trying to combine 2 regexp:

const str = '0123456789';

const regexp1 = /|d/g;
const matches1 = str.match(regexp1);
console.log('Length = ' + matches1.length);
console.log(matches1);

const regexp2 = /d|/g;
const matches2 = str.match(regexp2);
console.log('Length = ' + matches2.length);
console.log(matches2);

React Query // How to properly use client-state and server-state (when user can drag/sort items on the UI)?

I have an React App using React Query to load a dataset of folders containing items. The app allows the user to drag/sort items (within a folder and to drag to another folder). Before implementing drag/sort it was simple, RQ fetched the dataset folderData and then the parent supplied data to child components: parent > folder > item .

In order to implement drag/sort, I am now having to copy the entire dataset folderData into a client-state variable foldersLocal. This is the only way I could figure out how to change the UI when the user moves an item.

However, I feel like this approach essentially removes most of the benefits of using React Query because as soon as the data is fetched, I copy the entire dataset into a “client-side” state variable (foldersLocal) and only work with it. This also makes the QueryClientProvider functionality effectively useless.

Is there a better way to approach this? Or am I missing something?

// Fetch data using React Query
const {isLoading, isError, foldersData, error, status} = useQuery(['folders', id], () => fetchFoldersWithItems(id));

// Place to hold client-state so I can modify the UI when user starts to drag/drop items
const [foldersLocal, setFoldersLocal] = useState(null);

// Store React Query data in client-state
useEffect(() => {
    if (status === 'success') {
        setFoldersLocal(foldersData);
    }
}, [foldersData]);

// Callback to change "foldersLoacal" when user is dragging an item
const moveItem = useCallback((itemId, dragIndex, hoverIndex, targetFolderId) => {
    setFoldersLocal((prevData) => {
        // change data, etc. so the UI changes
    }
}

// Drastically simplified render method
return (
    <QueryClientProvider client={queryClient}>         
        <FolderContainer folders={foldersLocal} moveItem={moveItem} moveItemCompleted={moveItemCompleted}/>
    </QueryClientProvider>
)

hide a field of virtual population mongoose

i have a comment collection and a post collection, and post schema are like this:

postSchema.virtual("comments", {
  ref: "Comment",
  localField: "_id",
  foreignField: "post",
})

and when i want to see comments of a post i use this:

   const post = await Post.findById(req.params.id);
    await post.populate("comments");
    res.send(post.comments);

i dont want to get email field of post.comments. i tried foreach delete key and it didnt work
tnx for helping me

execute ajax after enter and press button

i have easy ajax script, which send data from form, it work this button, and i want to date send when i press enter, how i can make it? Very thanks!

ajax code

jQuery(document).ready(function(){
    jQuery('.ajaxSubmit').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        });
            jQuery.ajax({
                url: "{{ url('/names') }}",
                method: 'get',
                data: {
                    runBy: $(this).closest("form").find(".name").val(),
                    command: $(this).closest("form").find(".surname").val(),
                },
                success: function() {
                    location.reload();
                }
            });
    });
});

php code

  <form>
       <input type="hidden" value="{{Auth::user()?->name}}" class="name">
        <textarea class="surname" name="input" cols="30" rows="1"> </textarea>
        <button class="ajaxSubmit" onclick="event.preventDefault()">send</button>
  </form>

MongoDB – Update All Map Values

I have documents that are structured like this:

// Document 1

    { 
      _id : "910",
      requests : {
        100 : {
          date : "10/06/2022 11:24:19"
          isProcessed : false
        },
        123 : {
          date : "10/06/2022 11:24:19"
          isProcessed : false
        },
      }
    }

// Document 2

    { 
      _id : "743",
      requests : {
        999 : {
          date : "10/06/2022 11:24:19"
          isProcessed : false
        },
        152 : {
          date : "10/06/2022 11:24:19"
          isProcessed : false
        },
      }
    }

requests are saved as a map structure and the keys are different in each document. I want to change isProcessed to true in every value of every field in the requests map, and do it for all the documents. How can I do that?

socket shows connection true and false at the same time, what can cause this issue?

I am trying to create a chat, here is I have created instance of socket and unmounted it, but the issue is the connection shows false and true at the same time, The chats and messages are listened but cannot get the new messages.What is the correct way of using socket.io-client ? help!!

when I console.log(socket) on the client, this prints as follows :

Socket {connected: false, receiveBuffer: Array(0), sendBuffer: Array(0), ids: 0, acks: {…}, …}
acks: {0: ƒ}
connected: true
flags: {}
id: "_klZ4PeyF0r37wPcAABa"
ids: 1
io: Manager {nsps: {…}, subs: Array(5), opts: {…}, setTimeoutFn: ƒ, clearTimeoutFn: ƒ, …}
nsp: "/"
receiveBuffer: []
sendBuffer: []
subs: (4) [ƒ, ƒ, ƒ, ƒ]
_callbacks: {$chats: Array(1), $new_message: Array(1), $message_list: Array(1)}
active: (...)
disconnected: (...)
volatile: (...)
[[Prototype]]: Emitter

when I consolelog(socket.connected),it also returns false, I have created the instance like this,

 useEffect(() => {
    socket = io(`https://samsara-chat.herokuapp.com/?token=${token}`, {
      transports: ['websocket']
      // autoConnect: true
    })
    socket?.connect()
    socket?.emit('chat-list', {})
    socket?.on('chats', (args) => {
      setChats(args.chats)
    })
    socket?.emit('list', { room_id: currentroom })
    socket?.on('message_list', (args) => {
      setMessage((list) => [...args.messages])
    })

    return () => {
      socket?.disconnect()
    }
  }, [socket, currentroom])

I am not able to add new items in my todolist web app

When I am trying to execute the code and trying to add new items in my todolist webapp I am getting this error
Here is my app.js code

    //jshint esversion:6
    
    const express = require("express");
    const bodyParser = require("body-parser");
    const mongoose = require("mongoose");
    
    const app = express();
    
    app.set('view engine', 'ejs');
    
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("public"));
    
    mongoose.connect("mongodb://localhost:27017/todolistDB");
    
    const itemsSchema = new mongoose.Schema({
      name: String
    });
    
    const Item = mongoose.model(
      "Item", itemsSchema
    );
    
    const defaultItem1 = new Item({
      name: "Welcome to your todolist!"
    });
    const defaultItem2 = new Item({
      name: "Hit the + button to add a new item."
    });
    const defaultItem3 = new Item({
      name: "<-- Hit this to delete an item."
    });
    
    const listSchema = {
      name: String,
      items: [itemsSchema]
    };
    
    const List = mongoose.model("List", listSchema);
    
    const defaultItems = [defaultItem1, defaultItem2, defaultItem3];
    
    
    app.get("/", function (req, res) {
      Item.find({}, function (err, foundItems) {  //Model.find({condition}, function (err, result){})
    
        if (foundItems.length === 0) {
          Item.insertMany(defaultItems, function (err) {
    
            if (err) {
              console.log(err);
            } else {
              console.log("Items added successfully!");
            }
            res.redirect("/");
          });
        } else {
          res.render("list", { listTitle: "Today", newListItems: foundItems });
        }
      })
    });
    
    app.get("/:customListName", function (req, res) {
      const customListName = req.params.customListName;
    
      List.findOne({ name: customListName }, function (err, foundList) {
        if (!err) {
          if (!foundList) {
            //Create a new list
            const list = new List({
              name: customListName,
              items: defaultItems
            });
            list.save();
            res.redirect("/" + customListName);
          }
          else {
            //Show an existing list
            res.render("list", { listTitle: foundList.name, newListItems: foundList.items });
          }
        }
      });
    
    
    });
    
    
    app.post("/", function (req, res) {
    
      const itemName = req.body.newItem;
      const listName = req.body.list;
    
      const item = new Item({
        name: itemName
      });
    
    
      if (listName === "Today") {
        item.save();
        res.redirect("/");
      }
      else {
        List.findOne({ name: listName }, function (err, foundList) {
          foundList.items.push(item);
          foundList.save();
          res.redirect("/" + listName);
        });
      }
    
    
    });
    
    
    app.post("/deleteItems", function (req, res) {
      const checkedItemId = req.body.checkbox;
      Item.findByIdAndRemove(checkedItemId, function (err) {
        if (!err) {
          console.log("Successfully deleted checked item");
          res.redirect("/");
        }
        else {
          console.log(err);
        }
      });
    });
    
    
    
    
    
    
    app.get("/work", function (req, res) {
      res.render("list", { listTitle: "Work List", newListItems: workItems });
    });
    
    app.get("/about", function (req, res) {
      res.render("about");
    });
    
    app.listen(3000, function () {
      console.log("Server started on port 3000");
    });

Adding new Item in the list

After hitting the add button in browser

Error thrown in console

Here is my list.ejs code

    <%- include("header") -%>
    
      <!-- Title Rendering -->
      <div class="box" id="heading">
        <h1>
          <%= listTitle %>
        </h1>
      </div>
    
      <!-- Deleting an item using a checkbox -->
    
      <div class="box">
        <% newListItems.forEach(function(item){ %>
    
          <form action="/deleteItems" method="post">
            <div class="item">
              <input type="checkbox" name="checkbox" value="<%= item._id %>" onChange="this.form.submit()" />
              <span>
                <p>
                  <%= item.name %>
                </p>
              </span>
            </div>
            <input type="hidden" name="listName" value="<%= listTitle %> " />
          </form>
          <% }) %>
    
            <!-- New Item Rendering -->
    
            <form class="item" action="/" method="post">
              <input type="text" name="newItem" placeholder="New Item" autocomplete="off" />
              <button type="submit" name="list" value="<%= listTitle %>  ">+</button>
            </form>
      </div>
    
      <%- include("footer") -%>

Anyone please help me to resolve this issue.

Ignore the following text (this is just for bypassing the stackoverflow conditions error)

Lorem ipsum dolor sit amet consectetur adipisicing elit. Id odit quasi
aliquid. Laborum voluptate, corrupti alias ratione excepturi ex rem
laboriosam magni enim, repellendus numquam modi odit incidunt unde
possimus vero, pariatur et neque tempore qui! Obcaecati ipsa dolor,
aspernatur eos, hic officia et doloremque recusandae doloribus numquam
odio commodi vitae. Repellat vitae eaque exercitationem autem, eos,
quasi incidunt dicta laborum maiores dolorum mollitia natus animi
inventore. Quisquam eius dolore error eaque delectus libero
voluptatibus ipsam reprehenderit dignissimos numquam. Repellendus id
soluta nisi ratione est dolores at, nemo consectetur doloribus saepe
aspernatur sequi veniam ducimus laudantium dignissimos a eaque rerum.