Moving the div evenly aorund inside the grid

How can I make the green square always land on the center of the blue square.It works when I first hit the up key but after that it lands in deifferent possitions.Also I want to be able to keep the green square from going outside the grid.As it can be seen, i’m realy green when it comes to coding and maybe this takes more complex coding than I realized.But the most common advice has been to try,goolge and ask on forums.

html
  <div class="wrapper">
    <div class="one">One</div>
    <div class="two">Two</div>
    <div class="three">Three</div>
    <div class="four">Four</div>
    <div id="five">Five
        <div class="mun"></div> 
    </div>
    <div class="six">Six</div>
    <div class="seven">Seven</div>
    <div class="eight">Eight</div>
    <div class="nine">Nine</div>
</div> 
css
    .wrapper {
        display: inline-grid;
        grid-template-rows: 100px 100px 100px;
        grid-template-columns: 100px 100px 100px;
        border: 2px solid black;
    }

    .one, .two, .three,
    .four, .six, .seven, .eight, .nine {
        background-color: blue;
        border: 1px solid black;

    }

    #five {
        background-color: blue;
        border: 1px solid black;
        position: relative;
    }

    .mun {
        background-color: green;
        width: 35px;
        height: 35px;
        position: center;
        position: absolute;
        top: 31%;
        left: 32%;

    }
javascript
    const mun = document.querySelector('.mun')

    let xAxis = 0
    let yAxis = 0
   

    function control(e) {
        switch (e.key) {
            case 'ArrowLeft':
                xAxis -= 80;
                mun.style.left = xAxis + 'px'; 
                break;
     
            case 'ArrowRight':
                xAxis += 80;
                mun.style.left = xAxis + 'px'; 
                break;
        
            case 'ArrowUp':
                yAxis -= 80;
                mun.style.top = yAxis + 'px';
                console.log(yAxis)
                break;
         
            case 'ArrowDown':
                yAxis += 80;
                mun.style.top =yAxis + 'px';
                break;    
       }
     };
     
      document.addEventListener('keydown', control)

Trying to fix a bug in this browser tic-tac-toe game

I am trying to make a tic-tac-toe game with ai. So far, i have applied game logic, ai logic, players and game board handling. All works but there is a problem with choosing the character, if i choose a button X or O, it should assign that to human player and the other one to the ai. However, while X button works as intended, my O button still makes human player choose X. I need to be able to choose O and play second, but the game always starts with me as first player and the second ai..

const chooseXObtn = document.querySelector(".chooseXO-btn");
const chooseXO = document.querySelector(".chooseXO");

function displayXO() {
  chooseXO.classList.toggle("closed");
  console.log("display work")
}

chooseXObtn.addEventListener("click", displayXO);


const gameBoard = (() => {
  let winner;
  let getWinner = () => winner;
  let gameboard = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
  ];

  const getBoard = () => gameboard;
  const getPosition = (row, column) => gameboard[row][column];
  const setPosition = (row, column, el) => {
    gameboard[row][column] = el;
    render();
  }
  const resetBoard = () => {
    gameboard = [
      ["", "", ""],
      ["", "", ""],
      ["", "", ""]
    ];
  };
  const getEmptyFieldsId = () => {
    let fields = [];
    for (let row = 0; row < gameboard.length; row++) {
      for (let col = 0; col < gameboard[row].length; col++) {
        const field = gameboard[row][col];
        if (field == "") {
          fields.push([row, col]);
        }
      }
    }
    return fields;
  };
  const setFieldForAiLogic = (row, column, player) => {
    if (player == undefined) {
      board[row][column] = "";
      return;
    }
    board[row][column] = player.getMark();
  }

  return {
    getBoard,
    getWinner,
    getPosition,
    setPosition,
    resetBoard,
    getEmptyFieldsId
  }

})();

const Player = (name, mark) => {
  const getName = () => name;
  const getMark = () => mark;
  const setMark = (mark) => this.mark = mark;

  return {
    getName,
    getMark,
    setMark
  }
}


const gameController = (() => {

    let humanPlayer = Player("Player1", "X");
    let aiPlayer = Player("AI", "O");
    let turn = true;
    let board;
    let winner = null;
    const setTurn = (falseortrue) => turn = falseortrue;
    const getWinner = () => winner;
    const whoseTurn = () => turn ? humanPlayer : aiPlayer;
    const switchTurn = () => turn = turn ? false : true;
    const startGame = () => {
      gameBoard.resetBoard();
      board = gameBoard.getBoard();
      render();
      winner = null;
      // Check who has the 'X' mark and let that player start
      if (humanPlayer.getMark() === 'X') {
        console.log("x called turn true");
        turn = true; // Human starts
      } else {
        console.log("o called turn = false");

        switchTurn(); // AI starts
      }
      // If AI starts, make a move for AI
      if (!turn) {
        let arr = _getbestMove(gameBoard.getBoard());
        console.log(arr)
        gameBoard.setPosition(arr[0], arr[1], whoseTurn().getMark());
        switchTurn();
      }
      // If Human starts, wait for their move
      else {
        // Wait for human to make a move
      }
    }


    const handleMove = (moveRow, moveColumn) => {
      if (!isGameOver(gameBoard.getBoard()) && whoseTurn().getMark() === "X") {
        gameBoard.setPosition(moveRow, moveColumn, whoseTurn().getMark());
        switchTurn();
        // If it's now AI's turn and the game is not over, make a move for AI
        if (!isGameOver(gameBoard.getBoard()) && whoseTurn().getMark() === "O") {
          let arr = _getbestMove(gameBoard.getBoard());
          console.log(arr)
          gameBoard.setPosition(arr[0], arr[1], whoseTurn().getMark());
          switchTurn();
        }
      }
    }

    const changeMark = (mark) => {
      if (mark == "X") {
        humanPlayer.setMark('X');
        aiPlayer.setMark("O");
        turn = true;
      } else if (mark == "O") {
        humanPlayer.setMark("O");
        aiPlayer.setMark("X");
        turn = false;
      } else throw 'incorrect sign';
    }

    const isGameOver = (board) => {
      //check row and columns
      for (let i = 0; i < 3; i++) {
        if (board[i][0] !== "" && board[i][0] === board[i][1] && board[i][1] === board[i][2]) {
          winner = board[i][0];
          return winner;

        } else if (board[0][i] !== "" && board[0][i] === board[1][i] && board[1][i] === board[2][i]) {
          winner = board[0][i];
          return winner;

        }

      }

      //check diagonals

      if (board[0][0] !== "" && board[0][0] === board[1][1] && board[1][1] === board[2][2]) {
        winner = board[0][0];
        return winner;

      } else if (board[2][0] !== "" && board[2][0] === board[1][1] && board[1][1] === board[0][2]) {
        winner = board[2][0];
        return winner;
      }

      //if draw
      let isDraw = true;

      for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
          if (board[i][j] === "") {
            isDraw = false;
          }
        }
      }
      if (isDraw) {
        return "draw";
      }

      // game still continues
      return null;
    }

    return {
      whoseTurn,
      startGame,
      handleMove,
      isGameOver,
      getWinner,
      changeMark
    }
  }

)();

function render() {
  const tiles = document.querySelectorAll(".tile");
  tiles.forEach(
    (tile) => {

      tile.innerHTML = gameBoard.getPosition(tile.getAttribute("data-row"), tile.getAttribute("data-col"))
    }
  );

};

// Announce the winner or draw
function announceResult(result) {
  const message = result === 'draw' ? 'It's a draw!' : `${result} wins!`;
  // Display the message in an alert or a div

  setTimeout(() => {
    alert(message);
  }, 100);
}




const tiles = document.querySelectorAll(".tile");
tiles.forEach((tile) => {
  const row = tile.getAttribute("data-row");
  const col = tile.getAttribute("data-col");
});

// Add this event listener to the "Restart" button to start a new game
const restart = document.querySelector(".restart");
restart.addEventListener("click", () => {
  gameController.startGame();
  render();

});
// Add an event listener to each tile
tiles.forEach((tile) => {
  tile.addEventListener("click", () => {
    // Get the row and column of the clicked tile
    const row = tile.getAttribute("data-row");
    const col = tile.getAttribute("data-col");

    // Make a move on the game board

    if (tile.innerHTML == "") {
      gameController.handleMove(row, col);
    }
    // Check if the game is over
    const result = gameController.isGameOver(gameBoard.getBoard());
    if (result) {
      // Announce the result of the game
      announceResult(result);


    }



  });
});


function _getbestMove(currentBoard) {
  let bestVal = +Infinity
  let bestMove = [-1, -1]

  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (currentBoard[i][j] !== "X" & currentBoard[i][j] !== "O") {
        let temp = currentBoard[i][j]
        // console.log(temp)
        currentBoard[i][j] = 'O'
        let moveVal = _minimax(currentBoard, 9, true)
        // console.log("move val", moveVal, bestVal)
        currentBoard[i][j] = temp
        if (moveVal < bestVal) {
          bestMove = [i, j]
          bestVal = moveVal
        }
      }
    }
  }
  // console.log("best Val:", bestVal)

  return bestMove
}


function _minimax(currentBoard, depth, isMaximixingPlayer) {
  // console.log(currentBoard, depth, isMaximixingPlayer)
  let winSymbol = gameController.isGameOver(currentBoard)
  if (depth === 0 | winSymbol === "X" | winSymbol === "O" | winSymbol === "draw") {
    let gameOutcome = gameController.isGameOver(currentBoard)
    if (gameOutcome === 'X') {
      return 10
    } else if (gameOutcome === 'O') {
      return -10
    } else {
      return 0
    }
  }

  if (isMaximixingPlayer) {
    let maxEval = -Infinity
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        if (currentBoard[i][j] !== "X" & currentBoard[i][j] !== "O") {
          let temp = currentBoard[i][j]
          currentBoard[i][j] = 'X'
          let val = _minimax(currentBoard, depth - 1, false)
          // console.log(val)
          currentBoard[i][j] = temp

          if (val > maxEval) {
            maxEval = val;
          }
        }
      }
    }
    return maxEval;




  } else {
    let minEval = +Infinity
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        if (currentBoard[i][j] !== "X" & currentBoard[i][j] !== "O") {
          let temp = currentBoard[i][j]
          currentBoard[i][j] = 'O'
          let val = _minimax(currentBoard, depth - 1, true)
          currentBoard[i][j] = temp

          if (val < minEval) {
            minEval = val;
          }
        }
      }
    }
    return minEval


  }

}
const O_btn = document.querySelector("#O-btn");
const X_btn = document.querySelector("#X-btn");

X_btn.addEventListener("click", function() {
  gameController.changeMark(this.innerHTML);
  gameController.startGame();
  console.log("X button clicked");
});

O_btn.addEventListener("click", function() {
  gameController.changeMark(this.innerHTML);
  gameController.startGame();
  console.log("O button clicked");
});
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  font-family: 'Open Sans', "Helvetica";
}

.title {
  margin-top: 100px;
  flex: 1;
  display: flex;
  justify-content: center;
  border: 1px solid black;
  font-size: 40px;
}

.game-board-container {
  width: 50vh;
  height: 50vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.game-board {
  display: grid;
  grid-template-columns: repeat(3, minmax(100px, 1fr));
  grid-template-rows: repeat(3, minmax(100px, 1fr));
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  grid-gap: 1px;
  /* This creates a 1px gap between cells */
}

.game-board div {
  width: 100%;
  height: 100%;
  outline: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 100px;
}

.game-board div:hover {
  cursor: pointer;
}

.bottom-menu {
  margin-top: 100px;
  ;
  display: flex;
  width: 50vh;
  height: 50px;
  text-align: center;
}

.bottom-menu div {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  width: 100%;
  height: 100%;
  border: none;
  box-shadow: 1px 1px 1px grey;
  outline: 1px solid black;
}

button:hover {
  box-shadow: 3px 3px 2px grey;
  cursor: pointer
}

span {
  outline: 1px solid black;
  height: 100%;
  display: flex;
  align-items: center;
}

.chooseXO {
  height: 50px;
}

.closed {
  display: none !important;
}

#X-btn {
  background-color: green;
}

#O-btn {
  background-color: red;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js" defer></script>
</head>

<body>
  <div class="title">
    <h1>Tic-tac-toe</h1>
  </div>
  <div class="game-board-container">
    <div class="game-board">
      <div class="tile" data-row="0" data-col="0">X</div>
      <div class="tile" data-row="0" data-col="1">O</div>
      <div class="tile" data-row="0" data-col="2">X</div>
      <div class="tile" data-row="1" data-col="0">O</div>
      <div class="tile" data-row="1" data-col="1">X</div>
      <div class="tile" data-row="1" data-col="2">O </div>
      <div class="tile" data-row="2" data-col="0">x</div>
      <div class="tile" data-row="2" data-col="1">O</div>
      <div class="tile" data-row="2" data-col="2">X</div>
    </div>
  </div>
  <div class="bottom-menu">
    <div class="menu-left">
      <button class="restart">Restart</button>
    </div>
    <div class="menu-right">
      <button class=chooseXO-btn>Choose your letter</button>
      <div class="chooseXO closed">
        <button id="X-btn">X</button>
        <button id="O-btn">O</button>
      </div>
    </div>
  </div>
</body>

</html>

So far i tried to debug the code with console.log calls, it returns “X called turn true” on both buttons and buttons say X clicked, O clicked as well. So buttons work, the game starts, however the assignment of marks to players don’t seem to work as intended. There should be some fundamental error i must be doing. Thank you

Why does [contenteditable] become unfocusable in Chrome 117 (and 118 beta)

I have been working on a project that creates a custom element with a <slot> in the shadowRoot. Starting with the release of Chrome 117 if someone clicks on a contenteditable div the element gains focus and they can type, however if you click away and back, then the element is no longer focusable. Here is a minimal example of this (demo):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <input id="test-input" />

    <example-component>
      <div contenteditable="true">
        <h1>Hello World!</h1>
        <p>This is an example</p>
      </div>
    </example-component>

    <script>
      customElements.define(
        "example-component",
        class extends HTMLElement {
          constructor() {
            super();
            this.attachShadow({ mode: "open" });
            this.shadowRoot.innerHTML = `
            <slot></slot>
          `;
          }
        }
      );
    </script>
  </body>

This bug only appears in Chrome version 117 (and 118 beta), and not in any other browsers (that I can test on my mac). Anyone have any ideas?

Inconsistent state behaviour

I have a react component, with roughly the following code in it, and I’m getting inconsistent behaviour. Whenever the button is pressed, state is reset back to [] and is logged as such. However, afterwards whenever foo is called, state is returned to being however it was as if the resetState call had never happened.

Additionally, sometimes when foo is called and state is updated the useEffect doesn’t execute?

function myComponent() {
const [state, setState] = useState([]);

useEffect(() => {
  console.log(state);
}, [state]);


function foo (){
  let temp = state;
  temp.unshift(data);
  setState(temp);
};

function resetState () {
  setState([]);
}

return (
  <button onClick={() => resetState()}/>
  );
}

Cannot read properties of null but the variable is defined

I’m trying to implement my first full stack project according to the next YouTube tutorial:
https://www.youtube.com/watch?v=5Y5QKfxTErU

Based on MERN technology.

Implementing that step by step.

Until some part Everything just going as on video, until React part at 1:32:22
when Author got working page of http://localhost:3000/books
enter image description here
when I’m getting the next Error Screen:
enter image description here

**Edited: Second image is incorrect ,the actual error is:
Cannot read properties of null (reading ‘useContext’)
TypeError: Cannot read properties of null (reading ‘useContext’)

While playing with code lines if found out that the next line cause the error in Books.js
<Book book={book} />

The same error jumps 5 times as a number of Book’s properties (not including _id)
I feel lost a little bit, because I’m doing the same code, maybe somebody could help with debug that or avoid the cause of getting the null pointer?
Thanks in advance.
Here are the pieces of code on client side:

Books.js:

import React, { useEffect,useState } from 'react'
import axios from 'axios';  
import Book from './Book';
const URL = "http://localhost:5000/books"; 
const fetchHandler = async()=>{
    return await axios.get(URL).then((res)=>res.data);
};  
const Books = () => {
  const [books, setBooks] = useState();
    useEffect(()=>{
fetchHandler().then((data)=>setBooks(data.books));
  },[]);
  console.log(books);
return (
    <div>
    <ul>
    {books && books.map((book,i)=>(
      <div  key={i}>
      <Book  book={book}  />
      </div>
    ))}
  </ul>
    </div>
  );
};
export default Books

Book.js

import { Button } from 'react-bootstrap';
import React from 'react'

const Book = (props) => {
    const {_id,name,author,description,price,image} = props.book;
  return (
    <div>
     <img src={image} alt={name} />
     <article>By {author}</article> 
     <h3>{name}</h3>
     <p>{description}</p>
     <h2>Rs {price}</h2>
     <Button>Update</Button>
     <Button>Delete</Button>
    </div>
  )
}

export default Book

angularjs $http document load into an iFrame

I have read through two dozen references trying to get $http.get to pull a document from my server and load it into an iFrame. The call to the document works and its all stored in data – and I can see the HTML rendered in the Preview tab of Chrome’s Devtools network section. The page data/html is there, but I can’t get it to render in the iFrame.

App config:

.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://api.example.com/v1/**'
  ]) ;
})

In the Service:

.factory("eventService",function($http) {

  var headers = {
    'Pragma' : 'no-cache', 
    'Expires' : -1, 
    'Cache-Control' : 'no-cache,must-revalidate', 
    'Content-Type' : 'application/json',        
    'X-Requested-With' : 'com.example',
    Authorization : 'Token ' +clientToken[0]
  } ;

  function eventShow(dataObj) {
    //dataObj[0].fullVer = appVersion.replaceAll(".","") ;   
    var baseUrl = "https://api.example.com/v1/events/eventsPage.html?e="+dataObj.e ;
    
    var req = {
      method: 'GET',
      url: baseUrl,
      timeout:30,
      headers: headers
    }

    return $http(req)
    .then(function(response){
      if (response.status == 200) {
        return {"success":true,data:response.data} ;
      } else {
        // received an improper response
        return {"success":false,error:response.status} ;
      }
    }
   });
  }

  return {
    eventShow(eventID) {
      console.log("tBuy: "+eventID) ;
      var dataObj = [{"e":eventID}] ;
      return eventShow(dataObj) ;
  }
})

In the Controller:

  eventService.eventShow($scope.club.ceID)
  .then(function(res) {
    if (res.success == true) {
      console.log(res.data) ;
      $scope.eventItem.url = $sce.trustAsHtml(res.data);
      //$scope.eventItem.url = "data:text/html;charset=utf-8," + escape(res.data);
      $scope.eventItem.isLogin = 1 ;        
    }
  }) ; 

The template HTML:

  <iframe id="eventIframe" ng-src="{{eventItem.url}}" style="width:100%;height:100%;"</iframe>

In the controller, the console.log prints the entire requested page – so I know its loaded to this point, but I can’t get it to display/render in the iframe.

In the controller, when using $scope.eventItem.url = $sce.trustAsHtml(res.data); – nothing loads into the iFrame, there is no error produced, but behind the scenes I see my entire app reload with every JS file (app JS and plugin JS) as well as all my Templates load again and the app functionally crashes.

And when I change the controller to use $scope.eventItem.url = "data:text/html;charset=utf-8," + escape(res.data); – I get this error: Blocked loading resource from url not allowed by $sceDelegate policy – but the URL I am passing into the $http call is listed in my $sceDelegate

Download a text file without displaying save file popup in an electron app

In my electron app, I am taking user input in a text field and trying to download that text as a csv file on button click. The below JS function is working fine but it displays a popup along with the file name and ask to click save button before starting download. How can I get rid of the popup and download it automatically?

// Function to download CSV file
function downloadCSV(filename, text) {
  const element = document.createElement('a');
  element.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename + '.csv');

  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);

   // Display file location in console
  const fileLocation = `Saved file: ${filename}.csv`;
  console.log(fileLocation);
}

how to configure a service client object in the JavaScript SDK v3?

From example here i want to know how we can achieve in aws sdk JS v3?

The following example configures a service client object in javascript sdk object in v2. I want to know how we can achieve something like this in aws-sdk js v3?

import AWS from 'aws-sdk';

const { Service, apiLoader } = AWS;

apiLoader.services.personalize = {};
AWS.Personalize = Service.defineService('personalize', ['2018-05-22']);
Object.defineProperty(apiLoader.services.personalize, '2018-05-22', {
  get: function get() {
    const model = require('./aws-api-model-personalize.json');
    model.paginators = {};
    return model;
  },
  enumerable: true,
  configurable: true,
});

apiLoader.services['personalize-runtime'] = {};
AWS.PersonalizeRuntime = Service.defineService('personalize-runtime', ['2018-05-22']);
Object.defineProperty(apiLoader.services['personalize-runtime'], '2018-05-22', {
  get: function get() {
    const model = require('./aws-api-model-personalize-runtime.json');
    model.paginators = {};
    return model;
  },
  enumerable: true,
  configurable: true,
});

// initialize an instance of the Personalize service client
const personalize = new AWS.Personalize({ apiVersion: '2018-05-22' });

// use it
personalize.listDatasetGroups().promise().then((resp) => {
  console.log(resp);
});

How can I copy to clipboard an specific item in an array and how can i detect which one is clicked? in react js

I have an array of objects showing them in a table and one of the objects in this array is something that I want to copy to clipboard which has a copy icon button next to it but when i set the copy function it copies all the other objects in the array and I do not know how to detect which index has been clicked for copy!

const data = [
{title: "first", number: 1234},
{title: "second", number: 5678},
]

const [copied, setCopied] = useState(false);

const handleCopy = () => {
    setCopied(data.map((item) => item.number));
    navigator.clipboard.writeText(data.map((item) => item.number));
    toast({
      position: "top",
      isclosable: true,
      duration: 1500,
      render: () => <BaseAlert title="number copied!" />,
    });

    setTimeout(() => {
      setCopied("");
    }, 3000);
  };

<button onClick={handleCopy}>Copy</button>

When I click on the Copy button it copies two numbers in the array
output: 1234, 5678
while i want to detect which button has been clicked to copy 1234 OR 5678!

Multipart: Unexpected end of form with nestjs

  @Post()
  @Roles('USER', 'ADMIN')
  @ApiBody({
    description: 'Upload file',
    type: 'object',
    required: true,
  })
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  async uploadFile(
    @UploadedFile()
    file: Express.Multer.File,
  ) {
    console.log(file);
    await this.uploadService.uploadToFile(file);
    return { message: 'File uploaded successfully' };
 }

i am trying to create an endpoint to upload files with nestjs, when i test this on postman with form data and setting the key value to file i keep getting this error

{
    "statusCode": 400,
    "message": "Multipart: Unexpected end of form"
}

i tried different images, and i tried to send the request without the FileInterceptor the file gets logged but as an a normal object

{
  fieldname: 'file',
  originalname: 'pre-order-now.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: './uploads/',
  filename: 'name.png',
  path: 'uploads/pre-order-now.png',
  size: 1127
}

How to make an animation repeat after an element moves to another position?

I’m trying to make a box that moves every time its clicked, and stays there until its clicked again. I have an animation to make it look ‘angry’ when hovering over it, and an animation to run away once clicked.

However, I can’t figure out how to repeat the animation after it moved. I found this post that about adding and removing classes to trigger animations, but when I try to add and remove the classes a second time, its position resets and the hover animation doesn’t replay.

I’m pretty new to HTML/CSS and JS, so I’m not sure its even possible with this approach.

HTML file:

<button type="button" id= "box" class= "hovering" onclick="runAway()">DONT CLICK ME!</button>

CSS file:

body{
background-color: slategrey;
display: flex;
flex-direction: column;
}

#box{
  height: 100px;
  width: 100px;
  background-color: red;
  border: solid 3px black;

  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;

  font-family:fantasy;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.hovering:hover{
  font-weight: bold;

  animation: angry;
  animation-iteration-count: infinite;   
  animation-duration: .1s;
}

.hovering:active {
  box-shadow:
    inset -2px -2px 3px rgba(255, 255, 255, 0.6),
    inset 2px 2px 3px rgba(0, 0, 0, 0.6);
}

.running{
  animation: runner;
  animation-iteration-count: 1;   
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

@keyframes angry {
    
0% {transform: rotateZ(-3deg)}
50%{transform: rotateZ(3deg)}
100% {transform: rotateZ(-3deg)}
    
}

@keyframes runner {

  100% {transform: translateX(100%);}    

}

JS file:

function runAway() {

   let theButton = document.getElementById('box'); 

    theButton.classList.remove("hovering");
    
    theButton.classList.add("running"); 
    
    //how to repeat? simply adding and removing again doesnt work
    
}

Unable to override default styled-component theme

I created an NPM theme package there: https://www.npmjs.com/package/leon-theme?activeTab=readme

Using it in a basic create-react-app: https://github.com/leongaban/test-project

However once imported into the test-project, so far unable to override / change the theme using a local theme inside the test.

test-project index.ts

import { LeonTheme } from "leon-theme";

const theme = {
  borderRadius: "30px",
  colors: {
    main: "yellow",
    secondary: "purple",
  },
};

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <LeonTheme component={App} theme={theme} />
  </React.StrictMode>
);

enter image description here

Default theme (leon-theme package)

import { DefaultTheme } from "styled-components";

const myTheme: DefaultTheme = {
  borderRadius: "5px",

  colors: {
    main: "cyan",
    secondary: "magenta",
  },
};

export { myTheme };

The LeonTheme component

import React from "react";
import { ThemeProvider } from "styled-components";

import { myTheme } from "../../theme";

interface colorsTheme {
  main: string;
  secondary: string;
}

interface myThemeInterface {
  borderRadius: string;
  colors: colorsTheme;
}

interface LeonThemeProps {
  component?: any;
  theme: myThemeInterface;
}

const LeonTheme = (props: LeonThemeProps) => {
  const Component = props.component;
  const themeStyle = props.theme ? props.theme : myTheme;

  return (
    <ThemeProvider theme={themeStyle}>
      <Component />
    </ThemeProvider>
  );
};

export default LeonTheme;

Button component

import React from "react";
import { styled } from "styled-components";

interface ButtonProps {
  label: string;
}

const LeonButtonStyle = styled.button`
  margin: 20px;
  border-radius: 15px;
  font-size: 1.5em;
  text-align: center;
  cursor: pointer;

  color: ${(props) => props.theme.btnColor};
  padding: ${(props) => props.theme.btnPadding};
  border: 2px solid ${(props) => props.theme.mainColor};
  background-color: ${(props) => props.theme.mainColor};
`;

const Button = (props: ButtonProps) => {
  return (
    <LeonButtonStyle className="leon-button">{props.label}</LeonButtonStyle>
  );
};

export default Button;

I also tried <ThemeProvider theme={theme}> in the index.ts file to no avail. What step or config am I missing?

Problem while running example code from CredentialsContainer.create docs

total FE noob here.
I’m trying to follow these instructions on the create method relative to the Web Authentication API described here.

I’m getting:

Uncaught (in promise) DOMException: CredentialContainer request is not allowed.

when running the example code from the above site:

let credential = navigator.credentials.create({
    publicKey: {
      challenge: window.crypto.getRandomValues(new Uint8Array(8)),
      rp: { id: "acme.com", name: "ACME Corporation" },
      user: {
        id: new Uint8Array([79, 252, 83, 72, 214, 7, 89, 26]),
        name: "jamiedoe",
        displayName: "Jamie Doe"
      },
      pubKeyCredParams: [ {type: "public-key", alg: -7} ]
    }
  });

I have two questions:

  1. what am I doing wrong?
  2. is there a way to make the error message more explicit? Yeah, probably doesn’t like the request… but what bit exactly? How do you approach this?

Thanks

Xml Generation mismatch

When I run a script that generates an xml file in my server and on my local machine it generates two slightly different xml files how could that occur because the script is connected to the same database using the same credentials and has the same permission. I am confused

I expected the XML files generated at both environment to be the same but they are not. I am using the script so there are no differences in the code, the sql credentials are also completely similar. the database doesnt get updated so there is no data mismatch.

Build failed when I write yarn android in terminal

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring root project ‘Recalls’.

Could not determine the dependencies of null.
Could not resolve all task dependencies for configuration ‘:classpath’.
> Could not find com.android.tools.build:gradle:.
Required by:
project :
> Could not resolve com.facebook.react:react-native-gradle-plugin.
Required by:
project :
> No matching variant of project :gradle-plugin was found. The consumer was configured to find a library for use during runtime, compatible with Java 8, packaged as a jar, and its dependencies declared externally, as well as attribute ‘org.gradle.plugin.api-version’ with value ‘8.0.1’ but:
– Variant ‘apiElements’ capability com.facebook.react:react-native-gradle-plugin:unspecified declares a library, packaged as a jar, and its dependencies declared externally:
– Incompatible because this component declares a component for use during compile-time, compatible with Java 11 and the consumer needed a component for use during runtime, compatible with Java 8
– Other compatible attribute:
– Doesn’t say anything about org.gradle.plugin.api-version (required ‘8.0.1’)
– Variant ‘mainSourceElements’ capability com.facebook.react:react-native-gradle-plugin:unspecified declares a component, and its dependencies declared externally:
– Incompatible because this component declares a component of category ‘verification’ and the consumer needed a library
– Other compatible attributes:
– Doesn’t say anything about its target Java version (required compatibility with Java 8)
– Doesn’t say anything about its elements (required them packaged as a jar)
– Doesn’t say anything about org.gradle.plugin.api-version (required ‘8.0.1’)
– Doesn’t say anything about its usage (required runtime)
– Variant ‘runtimeElements’ capability com.facebook.react:react-native-gradle-plugin:unspecified declares a library for use during runtime, packaged as a jar, and its dependencies declared externally:
– Incompatible because this component declares a component, compatible with Java 11 and the consumer needed a component, compatible with Java 8
– Other compatible attribute:
– Doesn’t say anything about org.gradle.plugin.api-version (required ‘8.0.1’)
– Variant ‘testResultsElementsForTest’ capability com.facebook.react:react-native-gradle-plugin:unspecified:
– Incompatible because this component declares a component of category ‘verification’ and the consumer needed a library
– Other compatible attributes:
– Doesn’t say anything about how its dependencies are found (required its dependencies declared externally)
– Doesn’t say anything about its target Java version (required compatibility with Java 8)
– Doesn’t say anything about its elements (required them packaged as a jar)
– Doesn’t say anything about org.gradle.plugin.api-version (required ‘8.0.1’)
– Doesn’t say anything about its usage (required runtime)

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

How can I fix this problem with your help?This is react native app I take failed build sentence