use a map() for loop

how do I want to fill the undefined value in the seats array with the value in namaPenumpang

my code

const a = undefined;
var kursi = [a, "galih"];

function tambahPenumpang(namaPenumpang, kursi) {
  
  if (kursi.length == 0) {
    kursi.push(namaPenumpang);
    return kursi;
  } 
  else {
    kursi.map(function (element, i) {

      if (element[i] === a) {
        element[i] = namaPenumpang;
        return element;
      }

      else if (element[i] === namaPenumpang) {
        return console.log("Kursi ini sudah terisi");
      }
    
      else if (i === element.length - 1) {
        element[i].push(namaPenumpang);
        return element;
      }
    });
  }
}

I have tried using a for loop it worked

Code for loop

var kursi = [undefined, "galih"];

function tambahPenumpang(namaPenumpang, kursi) {
  // jika angkot masih kosong
  if (kursi.length == 0) {
    kursi.push(namaPenumpang);
    return kursi;
  } else {
    for (let i = 0; i < kursi.length; i++) {
      if (kursi[i] === undefined) {
        kursi[i] = namaPenumpang;
        return kursi;
      } else if (namaPenumpang === kursi[i]) {
        console.log("Kursi ini sudah terisi oleh " + kursi[i]);
        return kursi;
      } else if (kursi[i] !== undefined) {
        kursi.push(namaPenumpang);
        return kursi;
      }
    }
  }
}

How my code work use a map()

Please help me to solve this problem, how can the contents of the array at the index with the value unndefined be replaced using the value namaPenumpang

Creating a Filter based database for html page

I am attempting to recreate this table as a basic database with an uploaded spreadsheet.

LINK

My goal is to just upload a JSON file made from a spreadsheet to update the fields when there is new content to add instead of manually adding the numbers line by line.

Is there a straight forwrard simple way to do this?

I tried exporting the Spreadsheets as JSON file and linking it to an exsisting similar page with no results.

How can i make this react Layout private

i need to prevent the user from going to the layout component unless the user is loged

 const router = createBrowserRouter([
    {
      path: "/",
      element: <Layout />,
      children: [
        {
          path: "/",
          element: <Home />
        },
        {
          path: "/users",
          element: <Users />
        },
        {
          path: "/products",
          element: <Products />
        },
        {
          path: "/profile",
          element: <Profile />
        }
      ]

    },
    {
      path: "/login",
      element: <Login />
    },
    {
      path: "/register",
      element: <SignUp />
    },

  ])

i tryed to create a component where this component gonna check if there is a token if token exit return else return go to login page

How to run Python and PHP with JavaScript?

Goal 1 = Must contain JavaScript code to run PHP and Python. (Separately please.)

Goal 2 = The code is not using someone else’s code and is completely your code.

Goal 3 = The code must also work as a bookmarklet because that’s what this question is for.

How Can I Optimize the Performance of a React Native App for Both Android and iOS?

Hello Stack Overflow Community,

I’m currently working on a React Native app that needs to perform well on both Android and iOS devices. While React Native offers a fantastic way to develop cross-platform applications, I’m facing some performance challenges, especially when it comes to animations, navigation, and handling large data.
online casino best bonus
I’d love to hear from experienced developers about their best practices and strategies for optimizing React Native app performance. Specific topics I’m interested in include:
onlinecasino
Techniques for smooth animations on both platforms.
Tips for optimizing navigation and routing.
How to efficiently handle large data sets without causing lags.
Tools and libraries that can assist in profiling and debugging.
If you have experience in dealing with performance bottlenecks in React Native or have successfully optimized your cross-platform app, please share your insights. Any code snippets, recommended libraries, or real-world experiences would be greatly appreciated.
bästa privat lån
Let’s work together to make React Native apps faster and more responsive on Android and iOS. Your expertise will be a valuable resource for developers like me who aim to deliver a top-notch user experience.

Thank you in advance for your contributions!

The community of experienced developers and experts may provide detailed and practical insights on how to optimize the performance of a React Native app for both Android and iOS. These responses may include:

Specific code snippets or examples demonstrating how to achieve smooth animations.
Recommendations for popular navigation and routing libraries that work well in React Native.
Strategies for handling large data sets efficiently, possibly mentioning the use of virtualization or pagination.
Suggestions for tools and libraries that can assist in profiling and debugging React Native apps.
The expectation is to receive a range of responses from various perspectives, including practical solutions, best practices, and real-world experiences, which would help the original poster (OP) overcome their performance challenges and improve their React Native app for both Android and iOS.

Troubleshooting Apache Tomcat and Next.js Integration for Subpages

I’ve recently set up an Apache Tomcat server locally and deployed a Next.js web app. In my Next.js project’s next.config.js file, I have the following code snippet:

const nextConfig = {
    output: 'export',
}

This configuration is used to export the project to the “out” directory, making it a static resource. When I zip the contents of the “out” directory and rename it to a .war file, the project runs smoothly.

However, I’ve encountered an issue when trying to access subpages, like localhost:port/webapp/example?1. The server returns a 404 error, and I suspect that this is because the pages in the “out” directory are not organized into separate folders for subpages.

What can I do to resolve my problem? Has it something to do with URL rewriting?

Kind Regards

Why does this computed property fail to change in my Vue 3 app?

I am making the transition from Vue’s Options API to the Composition API and for this purpose, I have put together a small Todo App.

In App.vue I have:

<template>
  <div id="app">
    <ErrorMessage
      v-if="!isValid"
      message="The todo body has to be at least 3 characters long"
    />

    <SuccessMessage v-if="allDone" message="You can relex! :)" />

    <p>{{ allDone }}</p>

    <div class="card">
      <Header />
      <List
        :todos="todos"
        @delete-todo="deleteTodo"
        @toggle-todo="toggleTodo"
      />
      <AddTodo @add-todo="addTodo" />
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import ErrorMessage from './components/ErrorMessage.vue';
import SuccessMessage from './components/SuccessMessage.vue';
import Header from './components/Header.vue';
import List from './components/List.vue';
import AddTodo from './components/Add.vue';

export default {
  name: 'App',
  components: {
    ErrorMessage,
    SuccessMessage,
    Header,
    List,
    AddTodo,
  },

  setup() {
    const todos = ref([]);
    const isValid = ref(true);
    const allDone = ref(false);

    return { todos, isValid, allDone };
  },

  methods: {
    toggleTodo: function (index) {
      this.todos[index].done = !this.todos[index].done;
    },
    deleteTodo: function (index) {
      if (confirm('Are you sure?')) {
        this.todos.splice(index, 1);
      }
    },
    addTodo: function (text) {
      let newTodo = {
        done: false,
        text: text,
      };

      if (text.length > 2) {
        this.isValid = true;
        this.todos.push(newTodo);
      } else {
        this.isValid = false;
      }
    },
  },

  computed: {
    allDone: function () {
      // Check if there are todos and
      // If all of them are done
      let undoneTodos = this.todos.filter((todo) => todo.done === false);
      return this.todos.length && !undoneTodos.length;
    },
  },
};
</script>

StackBlitz

I try to use the computed property allDone to check if there are todos and all of them are done, in which case I try to display a success message (“You can relax!”) in an alert component.

However, the initial value of the allDone variable does not change when the conditions are met for it to change.

What am I doing wrong? What is the most reliable way to achieve the desired result?

chrome extension chrome.identity.launchWebAuthFlow – how to set size of popup window?

How do you set the popup size from chrome.identity.launchWebAuthFlow : https://developer.chrome.com/docs/extensions/reference/identity/#method-launchWebAuthFlow

This question: Setting popup dimensions in Chrome launchWebAuthFlow? from 10 years ago asks same question, and it sounded like it was being developed, but I can see no way to do it 10 years later.

Is it possible now? Or do you have to roll your own auth flow ui just to set the size?

I have full control of the auth page, but adding a size like you do for other chrome ext popups….

body, html {
 width:500px;
 height:500px;
}

does nothing, and

<script >

    window.addEventListener('load', () => {
      window.resizeTo(500, 500);
    })

  </script>

throws lots of CSP errors

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' http://localhost". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

Even with unsafe-inline in the manifest as a test still throws the error in the auth window.

any ideas?

Dynamic data reloading with Ajax and pagination

I’m trying to get information about animals and their speeds from an API.

enter image description here

The information should be saved in a table with 5 columns. it should look something like this:

enter image description here

you will find the code that I have written so far underneath. The problem is that only the two buttons load, but not the table with the information. Do you have an idea what the error could be?

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Test</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-1srTifKwwmIWHsyIaapyeJQY2XxzfjIHpftPvwHSi97Mfm4cZNKDBAdVSrtRvti5" crossorigin="anonymous">
    <script> src = "https://code.jquery.com/jquery-3.7.1.min.js"
        integrity = "sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs"
        crossorigin = "anonymous"
    </script>
</head>

<body class="text-center">
    <br />
    <button class="btn btn-primary btn-lg" id="prev">Prev</button>
    <button class="btn btn-primary btn-lg" id="next">Next</button>
    <br />
    <table id="table" class="table table-striped table-striped table-hover">
        <tbody id="tableBody" />
    </table>
    <script src=" myScript.js">
    </script>
</body>

</html>

//Below the myScript.js

$(document).ready(function () {

    /*Variablen  */
    var counter = -5;
    var end = false;

    $("#next").click(function () {
        if (!final) {
            counter = counter + 5;
        }
        $.get("http://localhost:8080/webService/api/velocitiespagination?start=" + counter, function (velocities) {
            createTable(velocities);
        });
    });
    $("#prev").click(function () {
        counter = counter - 5;
        if (counter < 5){
            counter = 0;
        }
        $.get("http://localhost:8080/webService/api/velocitiespagination?start=" + counter, function (velocities) {
            createTable(velocities);
        });
    });


    createTable(velocities);
});

function createTable(velocities) {
    var text = "<tbody><tr><th>Tier<>/th><th>Maximalgeschwindigkeit Tier</th></tr>";
    $.each(velocities, function (key, velocity) {
        text = text + "<tr><td>" + velocity.animal + "</td><td>" + velocity.velocity + "</td></tr>";
    });
    text += "</tbody>"
    $("#myTable").html(text);

    end = velocities.length === 0;
}

Map division into groups then finding by address the correct group

Is there a library for displaying and dividing map into groups and then finding which group is corresponding to some address?

On example. Lets have a delivery app. A user orders delivery and you the app would charge him by address where the food is delivered to. Because some parts of the city might have different pricings…

Thanks for any advices and answers.

async/await in python vs javascript [closed]

In javascript all code executes on the event loop and unless we are using a promise nothing blocks the rest of the execution. e.g.:

async blockingFunc() {
  // Are we blocking here, rest of code doesn't execute?
  let result = await fetch()
}

Python seems to be the oppsite, everything blocks UNLESS we are using await. So:

async def blocking_func() {
  // We are not blocking here, rest of the code executes.
  result = await fetch()
}

I know I’m wrong because I have a python function that has async and sync code running together – async redis calls and sync network requests – and I’m getting strange results.

Can you please enlighten me?

I have an problem with my html and javascript code [closed]

Of course, let’s explain the problem in a simple way:

In an HTML file, I have a button with the text “Divide Money” and a function called “divideMoney()” that should be executed when the button is clicked. This is typically done using the “onclick” HTML attribute like this:

<button type="button" onclick="divideMoney()">Divide Money</button>
function divideMoney() {
  const totalAmountInput = document.getElementById("total-amount");
  const numberOfPeopleInput = document.getElementById("number-of-people");
  const finalAmountSpan = document.getElementById("final-amount");
  const equalAmountSpan = document.getElementById("equal-amount");
  const totalAmount = parseFloat(totalAmountInput.value);
  const numberOfPeople = parseInt(numberOfPeopleInput.value);
  if (!isNaN(totalAmount) && !isNaN(numberOfPeople)) {
    const equalAmount = totalAmount / numberOfPeople;
    finalAmountSpan.textContent = totalAmount.toFixed(2); // Set the final amount
    equalAmountSpan.textContent = equalAmount.toFixed(2); // Set the amount per person
  } else {
    finalAmountSpan.textContent = "Invalid input";
    equalAmountSpan.textContent = "Invalid input";
  }
}

The purpose of the “divideMoney()” function is to perform some calculations and display the result on the page. However, when I loaded the page and clicked the button, I received an error message that says, “Uncaught ReferenceError: divideMoney is not defined.” This means that the browser couldn’t find the “divideMoney()” function, as if it’s not defined.

I’d like to understand why this error is occurring and how to fix this issue so that the “Divide Money” button works correctly when clicked. What do I need to do to ensure that the browser recognizes and executes the “divideMoney()” function as expected?

I tried looking for typo’s but i didn’t find anything

blocked by CORS on production

error + whole page

im quite new to js and had now deployed my project. in development everything was working, and so now im blocked by cors when trying to signin (registering for example works for me without a problem so i know the db is connected ). there are a few thing that i dont really understand fully and i will also provide the code sample down.

heres how i use cors + signin endpoint:

app.use(cors({
  origin:["https://almoghasson.github.io/Face-Recognition/","http://localhost:3001"],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
}));

app.post('/signin', (req, res) => {
  const { email, psw } = req.body 
  const user = { email: email } //

  postgres.select('email', 'hash').from('login')
    .where('email', '=', email) 
    .then(data => {
      const isValid = bcrypt.compareSync(psw, data[0].hash)

      if (isValid) {
        const refreshToken = uuid();
        // store token in db & cookie
        postgres.select('*').from('users')
          .where('email', '=', email)
          .update({
            token: refreshToken
          })
          .catch(err => res.status(400).json(err))

        //return user data
        return postgres.select('*').from('users')
          .where('email', '=', email)
          .then(user => {
            const { token: _, ...userWithoutRefreshToken } = user[0];
            const accessToken = generateAccessToken(userWithoutRefreshToken);
            res.cookie(REFRESH_TOKEN_COOKIE_NAME, refreshToken, { httpOnly: false, maxAge: 24 * 60 * 60 * 1000, sameSite: "none", path: '/', secure: true });
            res.json({ accessToken });
          })
          .catch(err => res.status(400).json('unable to get user'))
      } else {
        res.status(400).json('wrong credentials')
      }
    })
    .catch(err => res.status(400).json('wrong credentials'))
});

my frontend fetch:

fetch('https://face-recognition-api-n3yg.onrender.com/signin', {
            method:'post',
            headers : {
                'Content-Type':'application/json',
            },
            body: JSON.stringify({
                email: this.state.signInEmail,  
                psw: this.state.signInPsw
            }),
            credentials: 'include'
        })
        .then(res => res.json())
        .then(res => {
            if (res.accessToken){
                const user = decodeAndStoreJWT(res.accessToken);
                this.props.setBearer(res.accessToken)
                this.props.loadUser(user)
                this.props.onRouteChange('home')
                this.props.runInterval()
            }
        })

i dont get why it does not accept the origin i provided , also why is the url “…/face-recognition/” but the origin does not have this part, only “…github.io”

tried adding on the front code headers the access-allow-origin header without success
tried to set the origin in my cors to “*” without success and its not recommended anyway

Regex matches with to many other words

I want to implement a blocking function that blocks the following words (Doesn’t matter if an url or a text message (Matched words here shown are: Porn, Fuck, Erotik /Erotic / Erregend). My way to implement was a Regex which looks like this. My Problem is. That it blocks not even this words. It also blocks others what contains most of Letters (For example support). Does anybody have an idea what could cause the problem?

$regex =
‘/([Pp]+[+s-_.,%][Oo]+[+s-_.,%][Rr]+[+s-_.,%][Nn]+[+s-_.,%])|([Ff]+[+s-_.,%][Uu]+[+s-_.,%][Cc][+s-_.,%][Kk]+[+s-_.,%])|([Ee]+[+s-_.,%][Rr]+[+s-_.,%][Oo]+[+s-_.,%][Tt]+[+s-_.,%][Ii]+[+s-_.,%][KkCc]+[+s-_.,%])|([Ee]+[+s-_.,%][Rr]+[+s-_.,%][Oo]+[+s-_.,%][Gg]+[+s-_.,%][Ee]+[+s-_.,%])|([Ee]+[+s-_.,%][Rr]+[+s-_.,%][Ee]+[+s-_.,%][Gg]+[+s-_.,%][Ee]+[+s-_.,%][Nn]+[+s-_.,%][Dd]+[+s-_.,%]*)/’;

and if i make something to match it:

if (preg_match($regex,$text) {
    /*Do something (for example an error Message).*/  
}