how to update properly an json´s object?

I´m learning backend using node.js, so I´m developing a API RESTfull. I need to use PUT to update a object by id (the id as a params) in a json file. I´m using postaman to test.

This is my array:

[
  {
    "item": "phone",
    "price": 10000,
    "id": 1
  },
  {
    "item": "tv",
    "price": 20000,
    "id": 2
  },
  {
    "item": "nintendo",
    "price": 2500000,
    "id": 3
  },
  {
    "item": "ipad",
    "price": "500000",
    "id": 4
  }
]

For example I a have a local server http://127.0.0.1:8080/products/3 (the number 3 will be the item I wanna update changing the price or the name).

I started like this

app.put("/products/:id", (request, resolve) => {
  const id = Number(request.params.id);



})

JS – Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ({a})

I am working on the below. I am novice with this.

I am not sure why I am getting this error – Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ({a})

enter code here

function winProbSimulator(playersArray, courseObj, N=100) {
const winners = {};
playersArray.forEach(player=>winners[player.name]=0);
for (let i=0; i<1000; i++) {
const playersCopy = JSON.parse(JSON.stringify(playersArray));
const bestScore = {score: 1000, count: 1};
   playersCopy.forEach(player=>{
        playerRound(player, courseObj);
        if (player.score < bestScore.score) {
            bestScore.score = player.score;
            bestScore.count = 1;
        }
        else if (player.score === bestScore.score) {
            bestScore.count += 1;
        }
    });
    playersCopy.forEach(player=>{
        if (player.score===bestScore.score) {
            winners[player.name] += 1 / bestScore.count;
        }
    });
}
Object.keys(winners).forEach(key=> winners[key] /= N);
return winners;

}

How to pass the filtered data which is returned from Custom Pipe to Child Component?

Parent Component

<app-search-bar (sender)="searchVideo($event)"></app-search-bar>

<ng-container *ngFor="let video of videos | search: query; let i=index;">
...
</ng-container>

<app-pagination (sender)="setStartEnd($event)"></app-pagination>

Custom Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(value: any, args: any): any {
    if(!value){
      return null;
    }
    if(!args){
      return value;
    }
    args = args.toLowerCase();
    return value.filter((data: any) => {
      return JSON.stringify(data).toLowerCase().includes(args);
    })
  }

}

Child Component (app-pagination)

<div class="pagination" *ngIf="videos.length > 3">
...
</div>

I need to get the filtered data that returned by Custom Pipe so that with the help of that I can handle the number of pages in Pagination Component.

Reset react component props in a single test

I have a component that display text base on state (‘success’ or ‘loading’)

const Button = (state) => <button>{state === 'success' ? 'Sucess!' : state === 'loading' ? 'Please wait...' : ''}</button>

and I’ve to write test like so:

test('Button approved state', () => {
    render(<Button state="success" />)
    expect(screen.getByText('Sucess!'))
})

test('Button pending state', () => {
    render(<Button state="loading" />)
    expect(screen.getByText('Please wait...'))
})

Is it possible to them in one test? I tried


test('Button approved and pending state', () => {
    render(<Button state="success" />)
    expect(screen.getByText('Sucess!'))

    //need to reset here?

    render(<Button state="loading" />)
    expect(screen.getByText('Please wait...'))
})

the test failed. how do I do some sort of reset in between?

How to show a div when the enter key has been pressed in two textareas?

How do you detect that the enter key was pressed in two textareas? I have a way to detect the enter key was pressed in one textarea and need help with detecting the enter key was pressed in two textareas.

This is what I’ve done so far:

$('#test1').keyup(function(e) {
   if(e.keyCode == 13) {
        $("#GFG_DOWN").text("Enter key pressed inside textarea");
   }
});  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test1"></textarea>
        <textarea id="test2"></textarea>
        <br>     
          
        <p id = "GFG_DOWN" style = 
            "color:green; font-size: 20px; font-weight: bold;">
        </p>

Search bar using Window. Find in js and html

Hello I am trying to make a search bar to search anything which is available on a html page. I used window.find method.it highlights the string if its available in the html page. It returns a boolean value true or false. It gives false if the searched string is not available. But main problem is that it also returns false if all the searched strings are highlighted.Then how can I message the user that Nothing found OR searched text is already highlighted.
I also want to Search again if button clicked again also when all the searched text is highlighted .

I AM USING THIS CODE BUT ITS NOT COMPLETING MY ALL WISHES THAT I WANT.

JS

function  SEARCH(){
 var Search=document.getElementById("Search").value;
 var result=window.find(Search);
 if (result == false) {
  alert("Nothing found or already highlighted "
); }
} 

HTML

<input class="FLDS" type="text" id="Search" placeholder="Search" />
  <button onclick="SEARCH()" id="SEARCHIT">SEARCH</button>

<p>    A paragraph is a self-contained unit of discourse in writing dealing with a particular point or idea. A paragraph consists of one or more sentences. Though not required by the syntax of any language, paragraphs are usually an expected part of formal writing, used to organize longer prose.   </p>

Forge Design Automation Revit Tutorial Error

I am trying the Design Automation Tutorial for Revit.
I am getting the following error.
Can someone help me fix this error.

enter image description here

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of ReadStream
at new NodeError (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationlibinternalerrors.js:372:5)
at write_ (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationlib_http_outgoing.js:742:11)
at ClientRequest.end (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationlib_http_outgoing.js:855:5)
at Request._end (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationnode_modulessuperagentlibnodeindex.js:1282:9)
at Request.end (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationnode_modulessuperagentlibnodeindex.js:1000:8)
at c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationnode_modulessuperagentlibrequest-base.js:282:12
at new Promise (<anonymous>)
at RequestBase.then (c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationnode_modulessuperagentlibrequest-base.js:264:31)
at c:Usersroshan.kerkettaDesktopDigitalForgeModelDesignAutomationSampleDesignAutomationnode_modulesforge-apissrcApiClient.js:394:7
at processTicksAndRejections (node:internal/process/task_queues:96:5) {code: 'ERR_INVALID_ARG_TYPE', statusCode: undefined, stack: 'TypeError [ERR_INVALID_ARG_TYPE]: The "chunk"…ions (node:internal/process/task_queues:96:5)', message: 'The "chunk" argument must be of type string …nt8Array. Received an instance of ReadStream', toString: ƒ, …}

Live server isn’t running scripts

I’m on chrome on a Mac, and the index file runs but the script doesn’t change anything. I tried just removing paragraphs and that doesn’t work either. I tried hard refreshing and running from the Live extension.

This is the code from Index.html

<!DOCTYPE html>
 
<html>
    <head>
        <h1> I've a lot of things to do today.</h1>
    </head>
    <body>
        <p> 1. Get the litter & Wet Food.</p>
        <p> 2. Clean the Room.</p>
        <p> 3. Go out with the girlfriend.</p>
        <p> 4. Teach Rishabh.</p>
        <p> 5. Watch a show.</p>
        <p> 6. DON'T GET ANYMORE NFTS SER.</p>
        <script scr="scripts.js"></script>
    </body>
</html>

and scripts.js

let ps = document.querySelectorAll('p')
ps.forEach(function(p){
    p.remove()
})

The script isn’t called at all because even a simple console.log statement in the scripts.js file won’t run. No errors either :/

Thanks a lot for the help. I’m super new and this has been kinda frustrating.

Add score board in ti-tac-toe game

var grid = document.getElementById('grid');
var msg = document.querySelector('.message');
var chooser = document.querySelector('form');
var mark;
var cells;

// add click listener to radio buttons
function setPlayer() {
  mark = this.value;
  msg.textContent = mark + ', click on a square to make your move!';
  chooser.classList.add('game-on');
  this.checked = false;
  buildGrid();
}

// add click listener to each cell
function playerMove() {
  if (this.textContent == '') {
    this.textContent = mark;
    checkRow();
    switchMark();
    computerMove();
  }
}

// let the computer make the next move
function computerMove() {
  var emptyCells = [];
  var random;

/*  for (var i = 0; i < cells.length; i++) {
    if (cells[i].textContent == '') {
      emptyCells.push(cells[i]);
    }
  }*/
  
  cells.forEach(function(cell){
    if (cell.textContent == '') {
      emptyCells.push(cell);
    }
  });
  
  // computer marks a random EMPTY cell
  random = Math.ceil(Math.random() * emptyCells.length) - 1;
  emptyCells[random].textContent = mark;
  checkRow();
  switchMark();
}

// switch player mark
function switchMark() {
  if (mark == 'X') {
    mark = 'O';
  } else {
    mark = 'X';
  }
}

// determine a winner
function winner(a, b, c) {
  if (a.textContent == mark && b.textContent == mark && c.textContent == mark) {
    msg.textContent = mark + ' is the winner!';
    a.classList.add('winner');
    b.classList.add('winner');
    c.classList.add('winner');
    return true;
  } else {
    return false;
  }
}

// check cell combinations 
function checkRow() {
  winner(document.getElementById('c1'), document.getElementById('c2'), document.getElementById('c3'));
  winner(document.getElementById('c4'), document.getElementById('c5'), document.getElementById('c6'));
  winner(document.getElementById('c7'), document.getElementById('c8'), document.getElementById('c9'));
  winner(document.getElementById('c1'), document.getElementById('c4'), document.getElementById('c7'));
  winner(document.getElementById('c2'), document.getElementById('c5'), document.getElementById('c8'));
  winner(document.getElementById('c3'), document.getElementById('c6'), document.getElementById('c9'));
  winner(document.getElementById('c1'), document.getElementById('c5'), document.getElementById('c9'));
  winner(document.getElementById('c3'), document.getElementById('c5'), document.getElementById('c7'));
}

// clear the grid
function resetGrid() {
  mark = 'X';
 /* for (var i = 0; i < cells.length; i++) {
    cells[i].textContent = '';
    cells[i].classList.remove('winner');
  }*/
  cells.forEach(function(cell){
    cell.textContent = '';
    cell.classList.remove('winner');
  });
  msg.textContent = 'Choose your player:';
  chooser.classList.remove('game-on');
  grid.innerHTML = '';
}

// build the grid
function buildGrid() {
  for (var i = 1; i <= 9; i++) {
    var cell = document.createElement('li');
    cell.id = 'c' + i;
    cell.addEventListener('click', playerMove, false);
    grid.appendChild(cell);
  }
  /* cells = document.querySelectorAll('li'); //Returns a NodeList, not an Array
  See https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches */
  cells = Array.prototype.slice.call(grid.getElementsByTagName('li'));
}

var players = Array.prototype.slice.call(document.querySelectorAll('input[name=player-choice]'));
players.forEach(function(choice){
  choice.addEventListener('click', setPlayer, false);
});

var resetButton = chooser.querySelector('button');
resetButton.addEventListener('click', function(e) {
  e.preventDefault();
  resetGrid();
});
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

body {
  background-color: #996E89;
  font-family: "Comfortaa", sans-serif;
}

h1 {
  font-family: "Lobster", serif;
}

.message {
  color: #fff;
  font-size: 1.5em;
  padding-bottom: 1em;
}

form {
  label {
    font-size: 4em;
    font-weight: bold;
    vertical-align: middle;
  }
  input[type=radio] {
    margin: 1em;
    cursor: pointer;
  }
  fieldset {
    display: block;
    opacity: 1;
    transition: all ease 1s;  
  }
  &.game-on fieldset {
    opacity: 0;
    display: none;
  }    
  &.game-on button {
    opacity: 1;
    display: block;
    margin: 0 auto;
  }
 
}

#grid-section {
  margin: 3em 0;
}

#grid {
  width: 300px;
  margin: 0 auto;
}

li {
  border: 1px solid #000;
  width: 100px;
  height: 100px;
  display: block;
  float: left;
  font-size: 3em;
  text-align: center;
  padding: .5em;
}

#c1, #c2, #c3 {
  border-top: none;
}

#c3, #c6, #c9 {
  border-right: none;
}

#c7, #c8, #c9 {
  border-bottom: none;
}

#c1, #c4, #c7 {
  border-left: none;
}

.winner {
  color: #9AE1E5;
}

.btn-primary, 
.btn-primary:focus {
  background-color: #33B7A5;
  opacity: 0;
  outline: 0;  
  transition: all ease .3s;
}

.btn-primary:hover {
  background-color: #4C2F39;
}
<div class="container">
  <div class="row text-center" id="intro-section">
    <h1>Player vs Computer Tic-Tac-Toe</h1>
    <h2 class="message">Choose your player:</h2>
    <form action="#">
      <fieldset>
        <input type="radio" name="player-choice" id="player-choice-1" value="X" />
        <label for="player-choice-1">X</label>
        <input type="radio" name="player-choice" id="player-choice-2" value="O" />
        <label for="player-choice-2">O</label>
      </fieldset>
      <button id="reset" class="btn btn-primary">Reset</button>
    </form>
  </div>
  <div class="row" id="grid-section">
    <ul id="grid"></ul>
  </div>

I wish to add a scoreboard on top where wins,loses,draws would be calculated. How do I go about the same? Also an another HTML page where I could see the number of wins, loses, draws.
I have tried adding table in the html and using it in JS but not able to implement the same.
Could you suggest any methods to implement these tasks in the project.

How do I mount an Image or JSON (dataURL) to a webpage URL?

Is there a way to mask or mount a dataURL to a webpage route using React, so that I can use it as an src or retrieved it with axios.get(url)?

I’ve tried using the <img src="dataURL(SVG)" atl="loading" />
which displays the image on the page.

when I try to set the src=”websiteURL/PageId” on another page it doesn’t seem to fetch the image?

is there a way I can mount it to the webpage url in html or javascript?

please let me know

Thank you in advance!

Accessing server-side text file using JavaScript

I am making a website for students to give test… I will be also hosting it. But I want to make the code such that a particular student can give the test only once a day. So, I thought of placing a text (.txt) file on the server and read and write the dates, the student last gave the test. But, I came to know about the fact that JavaScript cannot access server-side files. So, is there a way to do the thing I want to?

Note : I want to do both reading and writing into the file

Batch delete documents of a subcollection error: TypeError: n.indexOf is not a function

I am trying to batch delete a document of a subcollection.

There are times when I might need to delete the same product document ID and different history document ID or multiple product document IDs and different history document IDs.

I am passing the product document ID and history document ID, and I already see them in the console. However, I receive this error once I try to batch.delete()
this:

This is what the docID and the historyId shows in the console:

enter image description here

async function deleteDocumentSubcollection(docID, historyId) {
try {
  const batch = writeBatch(db);

//I think this is where the error appears
  historyId.forEach((id) => {
    batch.delete(doc(db, "products", docID, "history", historyId));
  });

  await batch.commit();
  alert("deleted");
 

  console.log("deleted");
} catch (err) {
  console.log(err);
}
}

React – why i cant running for loop with useState? [duplicate]

Using react,

There is a button and a value “x” inside a p tag.

Why the final x value is 2?

In the for loop, the final x value should be 100.

export default function Sectiom() {
  const [x, setX] = useState(1)

  const handleClick = () => {
    for (var i = 0; i < 99; i++) {
      setX(x + 1);
    }
  }

return (
<div>
<p>{x}</p>
<button onClick={handleClick}> Plus </button>
</div>
}
}