How to align the header and its components evenly in node js

enter image description here`.header { padding: 15px 20px; display: flex; position: sticky; background-color: white; justify-content: space-between; z-index: 100; top: 0; box-shadow: 0px 5px 8px -9px rgba(0, 0, 0, 0.75); }

.header_left { display: flex; justify-content: space-evenly; }

.header_input { display: flex; align-items: center; background-color: #eff2f5; padding: 10px; margin-left: 10px; border-radius: 999px;

}

.header_left > img { height: 40px; }

.header_input { border: none; background-color: transparent; outline-width: 0; }

.header_center { display: flex; flex: 1; justify-content: center; }

.header_option > .MuiSvgIcon-root { color: gray; }

.header_option:hover > .MuiSvgIcon-root { color: #2e81f4; }

.header_option { display: flex; align-items: center; padding: 0 30px; cursor: pointer; }

.header_option:hover { background-color: #eff2f5; border-radius: 10px; align-items: center; padding: 0 30px; border-bottom: none; }

.header_info { display: flex; align-items: center; }

enter code here
.header_info > h4 { margin-left: 10px; }’

Game Map with Canvas – Drawing Boundaries for Player at Certain Point

I’m writing a basic multiplayer game and working on client rendering of data sent by the server, but have been stumped on this question for a few days.

Basically, the game map is 6000×6000 (when the player reaches -3000 or 3000 on either the x or y, it stops moving). Relative to the player coordinates (the viewport is determined by a translation of the player to 0,0), a grid is drawn behind the player, giving the sense of movement. However, I would like to have the grid only extend to the edges of the 6000×6000 area, so that the player can see they have reached the end of the map.

Initially, I tried using the player coordinates to determine whether the edge of the map is visible, and in that case only draw behind or ahead of the player in order to denote the map end.

my draw function looks like this:

/*
 * Function drawBoard - draws grid on canvas
 * takes 2 args, height, width of game canvas
*/
var drawBoard = function(w, h) {
    ctx.beginPath();
    
    // vertical lines
    for (x = 0; x <= w; x += 50) {
        // draw after player
        // -3000, 3000 is map top right
        if (ship.pos.x >= (-3000-(w/2))) {
            ctx.moveTo(x+ship.pos.x, 0);
            ctx.lineTo(x+ship.pos.x, h);
        }

        // draw before player
        // 3000, 3000 is map top left
        if (ship.pos.x <= (3000+(w/2))) {
            ctx.moveTo(ship.pos.x-x, 0);
            ctx.lineTo(ship.pos.x-x, h);
        }
        
        // horizontal lines
        for (y = 0; y <= h; y += 50) {
            if (ship.pos.x >= (-3000-(h/2))) {
                ctx.moveTo(0, y+ship.pos.y);
                ctx.lineTo(w, y+ship.pos.y);
            }

            if (ship.pos.x <= (3000+(h/2))) {
                ctx.moveTo(0, ship.pos.y-y);
                ctx.lineTo(w, ship.pos.y-y);
            }
        }
    }
    ctx.strokeStyle = "gray";
    ctx.stroke();
    
    ctx.closePath();

};

I looked around extensively for a similar problem, but couldn’t find any, so I’d appreciate a few tips/pointers on how to solve this.

How to get the exact BBox for svg

I am trying to figure out why getBBox() for tspan element of a svg does not return the dimension.

To demonstrate this with an example,

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">

    <text class="t1" id="t1" font-size="20" font-family="PT Mono" text-decoration="underline">
        <tspan class="tsp1" id="tsp1" x="10.23" y="135.05">Abc ef ghi</tspan>
    </text>
    <rect class="rect1" id="rect1" x="9.23" y="112.73368530273439" height="31.546314697265625" width="1" fill="orange" />
</svg>

If I run BBox on both tsp1 and rect1, it returns the correct dimension for rect1 but not for tsp1

var tsp = document.getElementById('tsp1');
var tspBBox = tsp.getBBox();

var rect = document.getElementById('rect1');
var rectBBox = rect.getBBox();

S1

I was expecting BBox to return the exact x and y for tsp1 but it does not.
I don’t know why. I need to pass on the exact values to the succeeding class dynamically.

How can javascript return the exact dimension for the tspan element?

Thank you in advance.

Timeout a submit animation with JavaScript

i have a submit button and a JavaScript. On click the button changes the state from active to inactive and a spinner animation is shown. I want to add to the script a timeout function. The button shall stop the animation and go back in active state after 3000 ms and show the normal submit button again. Here is my code:

 <button type="submit" class="btn btn-primary btn-lg" value="submit" id="ajax-form-button">Submit</button>

$(document).ready(function() {
 $("#ajax-form").submit(function(e) {
   // disable button
   $('#ajax-form-button').prop("disabled", true);
   // add spinner to button
   $('#ajax-form-button').html(
   `<i class="spinner-border spinner-border-sm mb-1"></i> Bitte warten...`
   );            
 });
}); 

React Router Dom v6 render not redirecting

          <Route
            exact
            path="/register"
            element={<Register />}
            render={() => !isAuthenticated ? <Register/> : <Navigate replace to="/login" />}
          /> 

Okay so i want to redirect to login if user is not authenticated and “isAuthenticated” is normally set to false but it wont redirect me. Not a single error is logged. I replaced <Navigate /> with console.log("something") to see if there is something wrong with component imported from React-Router-Dom but that “something” is not logging. I tried all still don’t know what is wrong. Thanks

prompt problem in VS editor or node js editor

When i want to take user input in my code by taking command prompt vs code or node js editor says it is not defined. But as far i know we can take user input in JS by “prompt” .

example :-

function leapYear(year) {
    if ((year %2 == 0) && (year %100 != 0) || (year %400 == 0)) {
        console.log(year + " LeapYear");
    }
    else{
        console.log(year +" Not a LeapYear");
    }
  
}
const year = Prompt('Enter a year:');


leapYear(year);

Uncaught ReferenceError: prompt is not defined

Is there a way to check to see if two objects have the same keys and the same values in JavaScript? [duplicate]

I am making a program in JavaScript that reads two words from the user and determines if the two are anagrams. My objects hold keys which are the letters of the word, and the values which is the amount of times it appears in the word.
Here is how I am filling my objects at runtime:

for(var i = 0; i<word1.length; i++){
                      const curLetter = word1[i];
                      if(!dictWord1[curLetter]){
                          dictWord1[curLetter]=1;
                      }
                      else 
                      {
                          dictWord1[curLetter] += 1; 
                      }
                  } 
                  for(var i = 0; i<word2.length; i++){
                      const curLetter = word2[i];
                      if(!dictWord2[curLetter]){
                          dictWord2[curLetter]=1;
                      }
                      else
                      { 
                          dictWord2[curLetter] += 1;           
                      }
                  } 

Here is how they look when I console.log() them (I am using the words evil and live for this example)

Console.log results

I know how to loop through an object and print the keys and values, but is there a way in JavaScript I can compare the two? The way I am determining if they are anagrams is that I am seeing if the keys are the same and the values are the same in each object. Thanks in advance!

Выполнение кода до определённого момента [closed]

Имеется следующий код всплывающего окна:

<style>
.alert { box-shadow : 0 0 15px #c6e3f1; background-color:#fff; border-radius: 6px; -moz- 
border-radius: 6px; border: 2px #b5cad2 solid; }
.alert.success { background-color: #4CAF50; }
.alert.info { background-color: #2196F3; }
.alert.warning {background-color: #ff9800; }
.closebtn { margin-left: 15px; color: black; font-weight: bold; float: right; font-size: 22px; 
line-height: 20px; cursor: pointer; transition: 0.3s; }
</style>
<div align = "center">
<div class="alert"><span class="closebtn">×<br>
Информация:<br>
Текст...
</div></div>
<script>
var close = document.getElementsByClassName("closebtn"); var i;
for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = 
this.parentElement; div.style.opacity = "0"; setTimeout(function(){ div.style.display = 
"none"; }, 600); } }
</script>

Код работает, при нажатии на крестик окно закрывается, но при обновлении страницы всплывающее окно вновь появляется. Как сделать чтобы при нажатии на крестик один раз окно больше не появлялось, то есть оно отображалось на странице до тех пор пока не будет один раз нажати крестик чтобы его закрыть. Спасибо большое за помощь!

ReferenceError: indexedDB is not defined when testing React component with Jest

I have created a React App using Create React App, it uses IndexedDB.

When I try to run a test I’m getting this error:

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "ReferenceError: indexedDB is not defined".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

I understand that the testing suit is run in a headless browser that doesn’t have IndexedDB. How can I handle this case?

How to dynamically check if input is empty without using onChange?

I want to get one-time information from the input control when value is empty and when value is not empty

right now i’m using onChange like below:

<Input onChange={onChangeValue()} />

but this onChangeValue method is running every time when i type into the input, but I want two times information, first when value from input is empty and second when value from input is not empty.

Can someoone tell me what can i do this?

Thanks for any help!

Using Material UI (MUI) component in NextJS – Invalid Hook Call

Following the usage guide on MUI’s site, I have a simple NextJS app where index.js is:

import Button from '@mui/material/Button'

const Home = () =>
{
  return (
    <div>
      <Button variant="contained">Hello World</Button>
    </div>
  )
}

export default Home

And _app.js is:

import '../styles/globals.css'

function MyApp({ Component, pageProps }) 
{
  return <Component {...pageProps} />
}

export default MyApp

I haven’t modified _app.js here or in my other NextJS projects.

Running the project results in the following error:

Unhandled Runtime Error Error: Invalid hook call. Hooks can only be
called inside of the body of a function component. This could happen
for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
    and fix this problem

I think #2 is the issue here. However, I’m new to ReactJS so I’m not sure exactly what is going wrong.

Prior to this, I’ve worked on other projects to learn in which I used the useState and useEffect hooks without issue in this same Home component.

How can I integrate MUI components? MUI mentions a useButton hook here but I can’t find how to actually implement it without errors. Do you need to use a similar hook for every MUI component?

_.invoke function underscore.js

hey I need to rewrite the invoke function from underscore js, it works unless more than 2 arguments are being passed, then it fails. would appreciate help from someone more experienced

let finishArr = [];
  let aFunction = eval(methodName) /// given function as string, turning into function

  _.each(collection, function(value,index,collection){
    finishArr.push(aFunction.call(value))
  })

  return finishArr

Changing status on the basis of boolean value

I have a array as follows:

[{
      "data": {
        "name": "Cloud",
        "size": "20mb",
        "type": "Folder",
        "isDisplayStatus": 1
      },
      "children": [
        {
          "data": {
             "id":1,
            "name": "backup-1.zip",
            "size": "10mb",
            "type": "Zip",
            "isDisplayStatus": 1
          }
        },
        {
          "data": {
             "id":2,
            "name": "backup-2.zip",
            "size": "10mb",
            "type": "Zip",
            "isDisplayStatus": 1
          }
        }
      ]
    },
    {
      "data": {
        "name": "Desktop",
        "size": "150kb",
        "type": "Folder",
         "isDisplayStatus": 0
      },
      "children": [
        {
          "data": {
             "id":3,
            "name": "note-meeting.txt",
            "size": "50kb",
            "type": "Text",
             "isDisplayStatus": 0
          }
        },
        {
          "data": {
            "id":4,
            "name": "note-todo.txt",
            "size": "100kb",
            "type": "Text",
            "isDisplayStatus": 1
          }
        }
      ]
    }]

I have a method in which I will receive two arguments. One is boolean value and one is id.

  1. If boolean value is false, then I need to find the element in the array for the id which is coming as argument of method and set “isDisplayStatus” field to 0.

  2. If boolean value is true, then I need to find the element in the array for the id which is coming as argument of method and set “isDisplayStatus” field to 1.

  3. If for any children “isDisplayStatus” is 0, then “isDisplayStatus” in parent should be set as 0. If all chilren “isDisplayStatus” is 0, then for parent “isDisplayStatus” should be 0. If all children “isDisplayStatus” is 1, then for parent “isDisplayStatus” should be 1.

How can I do this?

Javascript Firebase RealTime Database Completion Block

I am trying to understand firebase-realtime-database. I am able to fetch the data, but I do not know how to add a completion block. I mean, is there a function to check when my data fetch query is completed?

function getData() { 
  firebase.database().ref('sections').once('value', function(names) {
     //got the data
  });
  //Completion block or a method to call processData() after I get all the sections
}

function processData() {
 //call this function after you get all the sections
}

Thank you very much!