Adding elements into arrays held as values in a map

I really struggle with the following. I have a simple Map, where for each key there is a value, which is an array.

MyMap= {
'Anna' => [ 'Item1', 'Item2' ]
}

However, I would need to extend the arrays for particular keys, i.e. add elements to them, but just cannot figure out the syntax.

I tried

 myMap.set(name,myMap.get(name).push(item))

Centring of element but in a very different way (Program help – html,css, javascript)

I want to center an element(inline-block) in my own thought way. Because I have an element(inline-block) let’s say of size 50px and the element I want to centre is on right side of this element.

I want to adjust the margin of an inline-block element(which is beside the 50px element) in such a way that it centers it.

The way I want is that we get the html body width and subtract it from the width of the 50px width element then divide by 2 and set the thus got value as the right and left margin.This will centre the element.

I just want program for following process but other flexible methods would work too.

I want the script or this specific function to run automatically at right time and assign the value.

I am a newbie. Not that much but i know basic.

I have tried margin 0 auto it is not working.

I have also used flexbox but don’t want to use it.

how to render a nested object inside of an object in react js

I want to render an nested object inside of an object.I’m not sure if I’m saying it right but see it for yourself first.

My api is like this:

I want to show the minimum_system_requirements objects.I mean graphics,os,storage etc.

Here is my code

 const Api = 'https://free-to-play-games-database.p.rapidapi.com/api/game'
    const [games,setGames] = useState([])

    const ApiCall = async() => {
        const data = await axios.get(Api,{
            params: {id: `${id}`},
            headers: {
                "X-RapidAPI-Key": "e45c2e2ba9msh04d74decbb1c499p1737fcjsn4f10ee599568",
                "X-RapidAPI-Host": "free-to-play-games-database.p.rapidapi.com"
              }
        })
        
        console.log(data.data)
        setGames(data.data)

    }
  useEffect(() => {
    ApiCall()
  },[])

return (
    <>
    <div className={themeSwitch ? 'Main-Bg-Container-light' : 'Main-Bg-Container-dark'}>
       <div className='GameInfo'>
        <div className='GameInfo-Top'>
           <h1 className={themeSwitch ? null : 'GameInfoP'}>{games.title}</h1>
           <img id='GameInfoImg' src={games.thumbnail}  alt=''/>
           <p className={themeSwitch ? null : 'GameInfoP'}>Description: {games.short_description}</p>
           <p className={themeSwitch ? null : 'GameInfoP'}>Genre: {games.genre}</p>
           <p className={themeSwitch ? null : 'GameInfoP'}>Platform: {games.platform}</p>
           <div className='Download-Container'>
           <a id={themeSwitch ? 'GameInfoLink-light' : 'GameInfoLink-dark'} href={games.game_url} target='_blank' rel='noopener noreferrer'>Download</a>
           </div>
        </div>
        <div className='GameInfo-Side'>
            <div className='GameInfo-Side-Title'>
           <h3 className={themeSwitch ? null : 'GameInfoP'}>Minimum System Requirements</h3>
            </div>
            <div className='GameInfo-Side-Text'>
           <p className={themeSwitch ? null : 'GameInfoP'}>Graphics: 
           
           </p>   
           <p className={themeSwitch ? null : 'GameInfoP'}>Memory: </p>
           <p className={themeSwitch ? null : 'GameInfoP'}>OS: </p>
           <p className={themeSwitch ? null : 'GameInfoP'}>Processor: </p>
           <p className={themeSwitch ? null : 'GameInfoP'}>Storage: </p>
            </div>
        </div>
       </div>
    </div>
    </>
  )

I tried doing this in console.log and it worked but I don’t know how to show it

 const ApiCall = async() => {
        const data = await axios.get(Api,{
            params: {id: `${id}`},
            headers: {
                "X-RapidAPI-Key": "e45c2e2ba9msh04d74decbb1c499p1737fcjsn4f10ee599568",
                "X-RapidAPI-Host": "free-to-play-games-database.p.rapidapi.com"
              }
        })
        
        console.log(data.data.minimum_system_requirements.graphics)
        setGames(data.data)

    }
  useEffect(() => {
    ApiCall()
  },[])

Javascript to python how data is sent i am using flask and unable to convert

(comment how can i improve way to present the question as well)
I am making a project for typing speed web application using Flask. But the problem is in calculating the time it takes for user to type. I’ve tried to calc time using page response time using @app.before_request and after… but it didn’t showed time.
So i applied JS(javascript) function to calculate time(hidden input from js[embeded] to html) and return to my python code along with the input data and calculated the time difference.
BUT there a value error
File “c:—-DesktopFlaskmain.py”, line 32, in typefast
in typefast
time_taken = end_time – float(start_time)
ValueError: could not convert string to float: ‘start_time’

The functional code is as follow:

{%block basic%}
<form method = 'Post' action = '/result'>
    <label for="text">Type the text below:</label><br>
    <textarea name="text" rows="10" cols="50">monster Speed</textarea>
    <input type="hidden" name="start_time" value="" id="start_time">
    <input type="submit" value="Submit">
</form>
{% endblock %}

{%block scripts%}
    <script>
        // curr time
        
**var start_time = String(new Date().getTime());
document.getElementById("start_time").value = start_time;**
    
    </script>
    {%endblock%}
@app.route('/result',methods = ['Get','Post'])
def typefast() -> 'html': 
    # request.parameter_storage_class = ImmutableOrderedMultiDict
    form_dta = request.form['start_time']
    #start_time = next(form_dta)
    start_time = start_time.strip(''')
    
    end_time = time.time()
    text = request.form['text']
    time_taken = end_time - float(start_time)
    words_typed = len(text.split())
    typing_speed = words_typed / (time_taken/60)
    return render_template('results.html',  the_title='It's Good to see your work!', typing_speed=form_dta)

The value of start time as concluded by python is > symbol.
I’ve tried to strip the string** but didn’t worked either. Other methods suggestions are also accepted for calculating time taken from input to submit. Also referred to related questions like html to flask method =Post but didn’t got the desired output.
Also i tried json format but couldn’t get it right either.
Thanks for your answer.

Passing a props to call a function is not working

I have a Cancel button. I would like to perform a specific function in another js file when the button is pressed. Here is what I am doing.

function Add(props) {
  const [cancel, setCancel] = useState(false);

  const handleCancel = () => {
    setCancel(true);
    <UploadFile cancel={cancel}/>
  }

  return(
    <div>
      <Dialog open={open} onClose={handleClose}>
         <DialogActions>
            <Button variant="contained" onClick={handleCancel}>Cancel</Button>
         </DialogActions>
      </Dialog>
    </div>
  )
}

In another file UploadFile.js, the code as below:

const UploadFile = (props) => {
    useEffect(() => {
        if(props.cancel) {
            remove();
        }
    },);

    const remove = () => {
    //Doing removing files
    ...
    };
}

But the remove() is never called. I am not sure useEffect() is properly used.

How to validate JWT token from auth0 with nextjs backend

I host a backend via Next.js on Vercel. In a separate frontend the user authenticates via Auth0. Now I want to protect the API in the backend. I get the token in the frontend and send it with the API call to the backend.

With Nextjs I have created a middleware in which I want to check every API call for the token. The token also arrives. How can I validate the token now?

Frontend

import {useAuth0} from "@auth0/auth0-react";
const {getAccessTokenSilently} = useAuth0();
const token = await auth.getAccessTokenSilently();
await axios.get('http://localhost:3000/api/users',
  {
    headers: {Authorization: `Bearer ${token}`}
  }
).then(console.log).catch(console.log);

Middleware Backend – middleware.ts

import {NextRequest, NextResponse} from 'next/server'
export async function middleware(req: NextRequest) {
    const token = req.headers.get("Authorization");
    console.log(token)
}

Range slider на React

enter image description hereНе получается реализовать данный слайдер на Реакте. Перебробовал много разных библиотек, ни на одной не вышло.

Подскажите пожалуйста библиотеки, с помощью которых можно сделать вот такой вот (именно такой) слайдер для цены. Перепробовал уже много разных библиотек. В одних не предполагается вот такое вот окошко с цифрами сверху, а в других документация не поддерживается, и вообще непонятно, чего делать. Если обучалки скинете, тоже буду очень благодарен, не смог найти

How to fix cors issue for images in nextjs

i’m rather new to nextjs and cors is giving me a headache.

I am trying to use the flagsapi.com API to add flags to a component.

and it does not work, I get the following error:


Access to image at 'https://flagsapi.com/US/flat/64.png' 
from origin 'http://localhost:3000' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 

I know that cors is blocking it. In other stacks I have solved it by adding the cors library but it seems to not work in nextjs.

Things I have tried fixing it was:

  • Adding flagsapi.com to the next.config.js file
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: [
      "images.unsplash.com",
      "ui-avatars.com",
      "flagsapi.com",
    ],
  },
};

module.exports = nextConfig;

and it does nothing.
Note: I have restarted the server

  • I tried using the /api route but as the api only returns images, I cannot really send it in a response.

How can I fix this cors issue

Thanks

React Native bottom tab navigator is too low and cut off at the bottom on iphone 14 pro (real device), expo 46.0.0

I’m developing a react native app with expo using createBottomTabNavigator from react-navigation-tabs (react-navigation-tabs version: ^2.4.0, react-navigation version ^4.4.4). When I run my app on any ios simulator (iphone 13, iphone 14 pro, iphone 14 max… with ios 16.2) the bottom tab navigator is displayed correctly. However, on the real device (iphone 14 pro, ios 16.3) the tab bar is moved to the bottom by around 20 pixels and cut off:

Tab bar on real iphone 14 pro

Tab bar on simulator iphone 14 pro

When I define the tab navigator I don’t change any margin, padding or height properties but stick to the default, the only thing I change is the tint color:

import React from "react";
import { createStackNavigator } from "react-navigation-stack";
import { createDrawerNavigator } from "react-navigation-drawer";
import { createBottomTabNavigator } from "react-navigation-tabs";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { Ionicons } from "@expo/vector-icons";

...

const MainTabNavigator = createBottomTabNavigator(
    {
        Home: {
            screen: HomeNavigator,
            navigationOptions: {
                tabBarLabel: "Home",
                showLabel: false,
                tabBarIcon: tabInfo => {
                    return (
                        <Ionicons
                            name={icons.home}
                            size={25}
                            color={tabInfo.tintColor}
                        />
                    );
                },
            },
        },
        Map: {...},
        Workouts: {...},
        Events: {...},
        Profile: {...},
    },
    {
        tabBarOptions: {
            activeTintColor: colors.primaryColor,
        },
    }
);

const MainNavigator = createSwitchNavigator({
    Startup: StartupScreen,
    Auth: AuthNavigator,
    ProfileCreation: ProfileCreationFlowScreen,
    ForgotPassword: ForgotPasswordScreen,
    Main: MainTabNavigator,
});

export default createAppContainer(MainNavigator);

Does anyone have an idea why the tab bar is displayed differently on the real iphone 14 pro than on the simulated iphone 14 pro and ideally how to fix this issue on the real device? Any help is appreciated.

Things that I tried out:

  • Running the app on differnt simulator devices (iphone 13, iphone 14 pro, iphone 14 max…) -> bottom tab navigator is displayed correctly
  • Running the app on a real iphone 11 pro -> bottom tab navigator is displayed correctly
  • Running the app on a real iphone 14 pro -> bottom tab navigator is cut off
  • Manually increasing the bottom tab navigator’s margin in the tab bar options (which worked, but is not a good solution as this differs per device, e.g. margin is too large then for iphone 11 pro…)
  • On expo version 44.0.0 the same app used to work and the tab navigator was displayed correctly, after upgrading to expo 46.0.0 the described issue occurred

Trying to perform form validation on my website

Followd a basic form validation video on youtube, and it seems that none of the messages on my javascript file are actually getting pushed onto the website with testing… Im expecting the error messages to display above the login form, but I could defintely have some errors in my code. any help would be appreciated.

const username = document.getElementById('Username')
const password = document.getElementById('Password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')

form.addEventListener ('Login', (e) => {
    let messages =[]
    if (username.value === '' || username.value == null){
        messages.push('username is required')
    }
    if (password.value.length <= 6){
        messages.push('Password must be longer than 6 characters')
    }

    if (password.value.length >= 20){
        messages.push('Password is too long')
    }

    if (password.value == 'password'){
        messages.push('Password cant be password')
    }

    if (messages.length > 0){
        e.preventDefault()
        errorElement.innerText = messages.join(', ')

    }
})
body {
    font-family: "Lato", sans-serif;
}

.main-head {
    height: 150px;
    background: #FFF;
}

.sidenav {
    height: 100%;
    background-color: #680C07;
    overflow-x: hidden;
    padding-top: 20px;
    width: 100%;
}

.main {
    padding: 0px 10px;
}

@media screen and (max-height: 450px) {
    .sidenav {
        padding-top: 15px;
    }
}

@media screen and (max-width: 450px) {
    .login-form {
        margin-top: 10%;
    }

    .register-form {
        margin-top: 10%;
    }
}

@media screen and (min-width: 768px) {
    .sidenav {
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
    }

    .login-form {
        margin-top: 80%;
    }

    .register-form {
        margin-top: 20%;
    }
}

.login-main-text {
    margin-top: 20%;
    padding: 60px;
    color: #fff;
}

.login-main-text h2 {
    font-weight: 300;
}

.btn-black {
    background-color: #000 !important;
    color: #fff;
}

.login-form {
  margin-top: 20%;
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.btn {
  margin-top: 20px;
}

.alert {
    color: #31708F;
    background-color: #D9EDF7;
    border-color: #BCE8F1;
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="sitestyle.css" rel="stylesheet" type="text/css">
<script defer src="C:UsersJohnDownloadscapstone projectsitescript.js"></script>
    <title>Excell Visualizer</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="sidenav">
    <div class="login-main-text">
        <h2>Chartcel <br> Login Page </h2>
        <p>Login or register from here to upload your desired spreadsheet.</p>
    </div>
    <div class="main">
        <div class="col-md-6 col-sm-12">
            <div class="login-form">
                <form id="form">
                    <div id="error"></div>
                    <div class="form-group">
                        <label for="username"> Username </label>
                        <input type="text" class="form-control" id="Username">
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" class="form-control" id="Password">
                    </div>
                    <button type="submit" onclick="check(this.form)" class="btn btn-black">Login</button>
                    <button type="submit" onclick="check(this.form)" class="btn btn-secondary"> Register</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

React – Stomp Websocket Class not subscribing to topic

I’m currently working on a small project where the user connects to a live auction site and places bids on items. I’m mostly a backend engineer, I’m having trouble with my front end and I’m not sure what is going wrong. I have reworked this from a basic chat application guide I read online for my needs, but something is breaking and I’m not sure where.

I’m able to connect to the backend socket connection. I’m able to send a bid to the topic subscription and see it logged out on my backend. I believe it’s returning the message correctly. I can see on the front end that it’s inside the initConnect function from the log but I don’t see the log from being inside the onConnected function. So I think it might be an issue with the way I’m building my StompClientGenerator class. Here is the code below.

Front end: React.js, Stomp
Back end : Spring Boot

 import SockJS from 'sockjs-client';

export default class StompClientGenerator {



    constructor(user) {
        this.socket = new SockJS('http://localhost:8080/ws')
        this.stompClient = Stomp.over(this.socket)
        this.initConnect();
    }


    initConnect =  async (stompClient, user) => {
        console.log("initConnect")
        await stompClient.connect({}, stompClient.onConnected(stompClient, user), stompClient.onError())
    }


    onConnected = async (stompClient, user) => {
        console.log('onConnected')
        await stompClient.subscribe('/topic/bids', stompClient.onMessageReceived())
    }


     onMessageReceived = async (payload)=>{
        console.log("onMessageReceived")
        console.log(payload)
    }

    
    onError = async (err) => {
        console.log(err);
       
    }


}

Here’s a link to the complete repository for my front end and back end if that helps!

https://github.com/jgarner828/AuctionHouse_React
https://github.com/jgarner828/AuctionHouse

Any help would be greatly appreciated!

How do you use a search bar and Javascript to filter out entire HTML divs?

I’m currently attempting to create a search bar with a filter for my website. This particular page has several different divs, each one containing several bits of information. It’s probably easier to explain with images and code.

Each of these sections is a self-contained div.

Here’s the code for one of them. They’re virtually all the same structure, with the only differences being the text and the background images.

<div class="block oblivion-one">
    <h1>The Elder Scrolls IV: Oblivion</h1>
    <h2>Let's Play Oblivion</h2>
    <p class="description">Veriax plays the former Imperial Legionnaire named Sir Veriax who evolves from a discharged soldier to become Tamriel's best hope for surviving the Oblivion Crisis.</p>
        <button class="link-to-playlist">
            <li>
                <a href="https://www.youtube.com/playlist?list=PLEE87B4A5E81D25D5">Playlist (Part One)</a>
            </li>
        </button>
        <button class="link-to-playlist">
            <li>
                <a href="https://www.youtube.com/playlist?list=PL24D7B506DCE8A29F">Playlist (Part Two)</a>
            </li>
        </button>
</div>

I’ve created a searchbar for this page, and basically I want to allow the user to search for individual series. For example, if they typed in: “The Elder Scrolls IV: Oblivion”, only the top row would show up. Everything else would be hidden.

I’ve been researching this question and it seems like it’s easy to filter out elements of a simple text list. This is a bit more complicated because I’m attempting to filter out an entire div of code.

I am admittedly new at Javascript and most of the code below was gathered from a Google search and adapted to my own code, but I wanted to at least present something.

function filterLP() {
    let input = document.getElementById('searchbar').value;
    input = input.toLowerCase();
    let x = document.getElementsByClassName('ul');
    for (i = 0; i < x.length; i++) {
        if (!x[i].innerHTML.toLowerCase().includes(input)) {
            x[i].getElementsByClassName.display="none";
        }
        else {
            x[i].getElementsByClassName.display="list-item";
        }
    }
}

Obviously that code doesn’t work, so I’m open to any suggestions on how to make it filter out the sections correctly. Thank you!

I’ve tried researching how to do this on my own, and while I’ve figured out how to do it with a text list I’m struggling to make the function above hide the entire div of code.

mPDF: Downloading PDF file in live server throws 403 forbidden error, but downloads successfully in localhost server

I have written a code which will write the HTML body of a particular webpage into my PDF file. I am using the mPDF library for this purpose.

This is the data that is being sent to my server:

enter image description here

This is my code:

JS:

function download(){
    return $.ajax({
              url: '/backend_pdfgen/pdfgen.php',
              type: 'POST',
              data:{
                   "pos_news_table": JSON.stringify(pos_links_snaps),
              },
              cache: false
          });
}
document.getElementById('download_pdf').addEventListener('click',function(){
    (async()=>{
        try{
            let response = await download();
            console.log(response)
        }catch(err){
            alert(err.status);
        }    
    })();
})

PHP:

(My server script is very big, so I am just pasting a part of the script here)

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Content-Type: text/plain; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    require_once __DIR__ . '/vendor/autoload.php';

    $mpdf = new MpdfMpdf(['setAutoTopMargin' => 'stretch','mode' => 'UTF-8']);

    $data_1 = json_decode($_POST["pos_news_table"],true);
    foreach($data_1 as $k=>$v){
        $split_val = explode("**",$v);
        $title = $split_val[1];
        $image = $split_val[0];
        $body = $split_val[2];
        $mpdf->WriteHTML('<div style="text-align:center";><table style="background-color:rgb(253, 188, 104);">
        $mpdf->WriteHTML('<tr>
                <td style="border: 3px solid rgb(87, 59, 22); text-align:center; width:350px; height:25px; font-size: 15px;">'.$name.'</td>
                <td style="border: 3px solid rgb(87, 59, 22); text-align:center; width:350px; height:25px; font-size: 15px;">'.$category.'</td>
            </tr>');
        $mpdf->WriteHTML('</table></div><br>');
        $mpdf->WriteHTML('<div style="text-align:center;"><img src="../'.$image.'"></div>');

        /* ..................*/
    }
    $mpdf->Output("reports/report.pdf");
?>

When I download the pdf, I get a 403 forbidden error in my live server. But when I run the same code in my local server, the pdf gets downloaded without any error.

I have spent hours searching for the reason, but I can’t find any. Surprisingly, this error occurs only when I send the data (posted in the screenshot) above. I’ve tried sending other random data to the server, the 403 error doesn’t occur then.

Only in this case, it shows the 403 error. Why is that? Please help me.

How to Create a website using React web app [closed]

I am newbie , I am working on self project where someone can drag and drop components and create a form . But now a user can make and we can create a form-website code for the user , how can I create a functionality of publish to make that form-website code on live server .

I havent tried anything , I dont have clue how to go with this.