HackerRank is not passing the code, on some test cases …need help here [closed]

my code is passing 20 out of 35 test cases, and I am not sure what fails it.
Would really appreciate assistance here, as the input is very large

function passwordCracker(pswrds, attempt) {
  let buildPswrd = [];
  let parsedAttempt = attempt;
  while (parsedAttempt.length > 0) {
    let parsedLength = parsedAttempt.length;
    for (let i = 0; i < pswrds.length; i++) {
      let pswrd = pswrds[i];
      let l = pswrd.length;
      if (parsedAttempt.slice(0, l) === pswrd) {
        buildPswrd.push(pswrd);
        parsedAttempt = parsedAttempt.slice(l);
        break;
      }
    }
    if (parsedLength === parsedAttempt.length) return 'WRONG PASSWORD';
  }
  let answer = buildPswrd.join(' ')
  console.log(answer);
  return answer;
}
//link to challenge 
//   https://www.hackerrank.com/challenges/password-cracker/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

Returning response in validation Express indicates error and continues the flow

I am validating through a middleware that the quantity of product required by the client is not greater than the quantity of product in stock.

The validation is correct, the message is displayed indicating that there is less stock than the user requires, but even if the message is displayed, the execution does not stop, it reaches the controller and saves the information.

This is my middleware:

let productHasStock =  async ( req, res, next ) => {
    try { 
        const details = req.body.detail;

        const product = await details.map( async detail => {
            let product = await Product.findById( detail._id );
 
            if (product.stock < detail.quantity) {
                console.log('stock error');
                return res.status(401).json({
                    msg: 'Stock error'
                })
            }
        })

        next();
    
    } catch (error) {
        res.status(401).json({
            msg: 'La petición es incorrecta'
        })
    }

}

const checkStock = async (id, quantity) => {

    let product = await Product.findById( id );
    return (quantity > product.stock) ? false : true;
};

module.exports = {
    productHasStock
}

In addition to this I get an error stating: Cannot set headers after they are sent to the client

error on console

I tried passing this logic to the controller but I get exactly the same errors so much so that it doesn’t stop executing like the error in the console.

Thanks for your help.

New to js, trying to make a simple To-Do list site [duplicate]

cannot for the life of me figure out why newTask is returning undefined instead of the input value from my form.

Heres my HTML code:

<!DOCTYPE html>
<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>Document</title>
</head>
<body>
    <h1>Todo List!</h1>
    <form action="" id="addTask">
        <label for="newTask"></label>
        <input type="text" placeholder="Task" id = "newTask">
        <input type="submit" >
    </form>
    <ul id = "tdList">
        
    </ul>
    <script src="myTodo.js"></script>
</body>
</html>

and heres my Js:

const form = document.querySelector('#addTask');
const input = document.querySelector('#newTask');
const tdList = document.querySelector('#tdList');

form.addEventListener('submit', function(e) {
    e.preventDefault();
    const newTask = document.createElement('li');
    console.log(input.value);
    newTask.innerText = input.Value;
    input.value = '';
    tdList.appendChild(newTask);
});

Javascript not executed when go back to previous page, behaves differently between local and live on githubpage, edge and chrome

Please check out this GithubPage where I try to recreate an issue I had.

When you click the first button, it will create a paragraph, append it to a localstorage item and display it.

When you click the second button, it will first clear the localstorage, then redirect to another page.

Now if you click the browser back button from page2, you go back to index.html, but the paragraphs are still there. If you check the localstorage, the paragraphs are deleted, as they should, but they still display as if the js script didn’t execute when coming back to the index.html.

I have this problem with chrome and Firefox, but edge behaves as I expected(coming back to index.html, no paragraphs displayed). Everything was also working as expected when I test it on local live server even with chrome. But not right on a GitHub page. Does Js script run again when visiting a page through browser’s back button? I thought so, but can someone explain what’s going on here? Thanks.

Here is the script

const addPEle = document.querySelector(".addP");
const clearPEle = document.querySelector(".clearP");
const contentEle = document.querySelector(".content");

addPEle.addEventListener("click", () => {
  const curContent = localStorage.getItem("content") || "";
  localStorage.setItem("content", `${curContent}<p>This is a paragraph.</p>`);
  displayContent();
});

clearPEle.addEventListener("click", () => {
  localStorage.setItem("content", "");
  location.href = "page2.html";
  // displayContent();
});

function displayContent() {
  contentEle.innerHTML = "";
  const content = localStorage.getItem("content") || "There is no paragraph.";
  contentEle.innerHTML = content;
  console.log("from displayContent function");
  console.log(`content: ${content}`);
  console.log(`localStorage: ${localStorage.getItem("content")}`);
}

displayContent();

player object undefined only in update()ƒ

not exactly sure what to call whats going on. I need to create a definition for the clients main player physics body and i can’t read it or any of its properties, no matter where or how i call it, from update(). Also if this is a bit hard to understand Im a young and new JS programmer so bare with me. Im willing to change the construction of my scenes if i need to if anyone recommends something easier.

class MainScene extends Phaser.Scene {
constructor() {
  super({ key: 'MainScene' })
}

preload() {
    this.load.image('grass','./assets/map.png',);
    this.load.spritesheet('graf', './assets/wang.png', { frameWidth: 200, frameHeight: 170})
  }

create() {
  this.add.image(100,400,'grass');
  this.playerMap = {};
  Client.askNewPlayer();
  window.myScene = this;
  this.body  = this.matter.bodies.circle(
      1,
      1,
      10,
      {
          isSensor: true
      }
      );
}
addNewPlayer(id, x, y) {
    if(id == clientID){
        this.playerMap[id] = this.matter.add.sprite(x, y, 'graf','', {'shape' : this.body['player-20-00']}).setScale(.5);
        this.player = this.playerMap[id];
        this.cameras.main.centerOn(this.player.x, this.player.y)
    }
    else{
    this.playerMap[id] = this.add.sprite(x,y,'graf').setScale(.5);
    }
}
removePlayer(id){
    this.playerMap[id].destroy();
delete this.playerMap[id];
}
movePlayer(id, x, y) {       
    // var player = this.playerMap[id];
    // var distance = Phaser.Math.Distance.Between(player.x,player.y,x,y);
    // var duration = distance*10;
    // var tween = this.add.tween(player);
    // tween.to({x:x,y:y}, duration);
    // tween.start();
    
}
cameraOn(){
    this.cameras.main.centerOn(this.player.x, this.player.y) 
}
update(){
   //haven't been able to access any variables Ive called from here
}

}

remove spaces from strings in array [duplicate]

I’m not sure if there is a more simpler way, but I am trying to create a function that loops through an array of strings and removes any space found.

This code manages to print out “00”, “11” and “22” correctly but the last loop prints “undefined” if I use i < as opposed to i <=.

When I added i <= stringArr[i].length, although it now prints “33”, I get an error saying:

**Uncaught TypeError: Cannot read properties of undefined (reading 'length') at removeSpaces**
const spacesArr = ["0 0", "1 1", "2 2", "3 3"];

const removeSpaces = stringArr => {
    for (let i = 0; i <= stringArr[i].length; i++) {
        console.log(stringArr[i].replace(/ /g, ''));
    }
}

I’m quite new to coding. Be gentle XD

serving live canvas or other live images with NPM

I’m trying to make a line graph that will follow the value of a value in a game, I can already read memory addresses with node.js (memoryjs) so my only problem is making the graph, I haven’t been able to find a way for node to allow me to serve or otherwise display an image that can update in real time

Input range variable is not defined & can’t be collected

I have this form:

        <form name="myLoginForm" method="post">
            <div class="container">
                <label for="uname"><strong>Username</strong></label>
                <input id="uname" type="text" placeholder="Enter Username" name="uname" required>

                <label for="difficulty"><strong>Difficulty:</strong><br></label>
                <input type="range" id="difficulty" name="difficulty" min="0" max="10">

                <button id="startGame" type="button">Start Game</button>
            </div>
        </form>

I can’t grab the input value of my input range. This is what I’m trying right now:

            var selectedDifficulty = document.getElementById("difficulty").value
            var sd = parseInt(selectedDifficulty);

How to extract the public numbers from an RSA keypair using the Web Cryptography API?

This question is directly related to the Web Cryptography API;
I have generated an RSA key pair as per the example on MDN:

const keyPair = await crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 4096,
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: "SHA-256",
  },
  true,
  ["encrypt", "decrypt"]
);

Is there any straightforward interface to extract the public numbers (exponent, modulus) from the public key?
Preferably as BigInt.

Declaring complex nested arrays in Javascript [duplicate]

I’m using the following array:

[[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]]

It’s an array that contains five times an array that contains three arrays. Is there a shorter syntax for declaring this? – I tried:

new Array(5).fill(new Array(3).fill(new Array()))

But that doesn’t work.

How do I bind the iphone/Safari “Search” button on the on screen keyboard with an input event like keyup.enter?

How do I bind the virtual on screen keyboard “Search” key on my iPhone/iPad to an input event like

(keyup.enter)="searchLocation()"

enter image description here

I have an HTML input like this

<input enterkeyhint="search" #searchInput (keyup.enter)="searchLocation()" type="text" class="form-control" />

Maybe there is another issue I’m unaware of, but I can’t debug my iPhone with VS Code. The only think I can do is push to the dev site and then open the browser to look.

How can I use the map() method in javascript to create a div with a button that fetches from an API

Im am trying to create a bunch of div elements on a page using the map() function. The array mapped is called cards, and each of these cards has a value called the id. Im trying to have a button on each div that will post to an api using the respective card’s id.

For example: If the cards array includes 3 cards, card1, card2, and card3, I want to create three divs, one for each card. I want each div to have a button that will allow me to add that card to a database using the card id. So if card1 had a card id of 1, when I press the button, the card id 1 should be added to the database. Any help is appreciated, thanks!

HTML code:

<div className="cardImages">
        {cardsFetched ? (
          cards.data.map((card) => (
            <div className="searchedCards" key={card.id}>
              <div className="singleCard">
                <img src={card.images.small} />
                <p>Card ID : {card.id}</p>
                <button onClick={() => addToCollection2(card.id)}>
                  Add Card
                </button>
              </div>
            </div>
          ))
        ) : (
          <div>Searched cards will appear below</div>
        )}
      </div>

Image URL not getting redirect to port 8000 of Django while working with React

I am working on a project where backend is Django Rest Framework and frontend is React. I have a Product Screen where I have Product details listed down. In Product Screen I first fetch product object from Redux store and then use that product to render details and also image of the product from the URL.

Fetching product object from Redux store:

const productDetails = useSelector((state) => state.productDetails);
const { error, loading, product } = productDetails;

Image Tag:

<Image src={product.image} alt={product.name} fluid />

I have setup a setupProxy.js file where I set the target port 8000.

SetupProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    "/api",
    createProxyMiddleware({
      target: "http://127.0.0.1:8000",
      changeOrigin: true,
    })
  );
};

But when I have image uploaded from Django Admin Panel the image url in Product Screen turns out to be:

http://localhost:3000/images/sample.jpg

instead of:

http://localhost:8000/images/sample.jpg

How can I fix this issue?

Dojo Dialog not highlighting first focus element on first-time show

Working on updating a web-based project that that ran under IE to run under modern browsers like Chrome, Edge, and Firefox. The Dojo Toolkit (v1.x) is used.

One annoyance encountered is the failure for the first focusable widget to be highlighted when a dijit.Dialog is first raised. Take the following example test page:

  <!DOCTYPE html>
  <html>
  <head>
    <link rel="stylesheet"
          href="https://ajax.googleapis.com/ajax/libs/dojo/1.13.0/dijit/themes/claro/claro.css">
    <script>dojoConfig = {parseOnLoad: true}</script>
    <script src='https://ajax.googleapis.com/ajax/libs/dojo/1.13.0/dojo/dojo.js'></script>
    <script>
      require(["dojo/parser", "dijit/Dialog", "dijit/form/Button"]);
    </script>
  </head>
  <body class="claro">
    <div data-dojo-type="dijit/Dialog"
         data-dojo-id="myFormDialog"
         title="Form Dialog"
         execute="alert('submitted w/args:n' + dojo.toJson(arguments[0], true));">
      <div class="dijitDialogPaneContentArea">
        <p>This is a test.</p>
      </div>
      <div class="dijitDialogPaneActionBar">
      <button data-dojo-type="dijit/form/Button"
              type="submit"
              onClick="return myFormDialog.isValid();">OK</button>
      <button data-dojo-type="dijit/form/Button"
              type="button" onClick="myFormDialog.hide()">Cancel</button>
      </div>
    </div>
    <button id="buttonThree"
            data-dojo-type="dijit/form/Button"
            type="button" onClick="myFormDialog.show();">Show me! </button>
  </body>
</html>

When the dialog is first raised, the “Ok” button is not showing an outline to indicate it has focus, even though it does. If the Shift (or any other) key is pressed on the physical keyboard, then the outline shows.

I have tried to simulate a keypress using a variety of methods with the hope it would trigger the focus outline, but no success. I tried using Dijit focus() method on the buttons, but no outline shows, even though the keyboard focus does change to button focused.

In IE11, the focus outline does render as desired, but in the major modern browsers, Chrome, Edge (Chromium), and Firefox, the focus outline does render on initial dialog show. Is this a known problem with Dojo 1.x? Problem exists in v1.17.0 and at least to versions back to 1.10.