Window prompot(method) for use input text [duplicate]

please help

    <button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let person = prompt("Please enter your name", "Harry Potter");
  if (person != null) {
    document.getElementById("demo").innerHTML =
    "" + person + ""
  }
}
</script>

<input type=”text” name=”T1″ value=”javascript”

How can I add the field here?
“” + person + “”

input text value.

more efficient way of looping await / async? [duplicate]

I am trying to get messages given a list of message ids (Gmail API).

let messageIdList = [msg1: { id: 1234 }, ...]
 
let messages = [];

for (const msg of messageIdList) {
    const response = await gapi.client.gmail.users.messages.get({
        'userId': 'me',
        'id': msg.id,
        'format': 'full'
    })

    messages.push(response.result);
};

// do something with messages

I used a for … of loop because of this post, so it works…but it’s super slow (I assume it’s because it goes one at a time). What would be a way to go about making all of the API calls be fired at the same time but somehow knowing when all of them are complete?

Maximum update depth exceeded from Navigate component react-router-dom v6

I’m using react-router-dom v6 to control the route of my React Js app.

Here are the specifications:

  1. I’m creating the AuthenticationRoute and PrivateRoute components.

  2. The AuthenticationRoute component is used to wrap pages that the user doesn’t need to authenticate for examples SignIn, SignUp, ForgotPassword, and ResetPassword pages.

  3. The PrivateRoute component is used to wrap private pages (authentication is needed) for example Home page. Inside the PrivateRoute, there are some layouts. One of them is called the Dashboard layout to wrap the Drawer (Sidebar/Navigation) component and the Home page.

  4. If the user has not logged in via the SignIn page, the app would return the SignIn page.
    If the user has logged in, the app would return the Home page.

Here are the current conditions:

Note: The check sign (✅) represents the conditions I want while the cross sign (❌) represents the error or unwanted conditions.

  1. All of the specifications above are met. ✅

  2. The first time user runs the app, the SignIn page is returned because the user has not logged in. ✅

  3. If the user has not logged in and typed “/” route to the address bar (to access the Home page) via the SignIn page, the app will not redirect the user to the Home page instead of returning the SignIn page. ✅

  4. If the user successfully logged in via the SignIn page, the app would return the Home page (with “/” route). ✅

  5. If the user has logged in and typed “/sign-in” route to the address bar (to access the SignIn page) via the Home page, the app return error: ❌

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
    at Navigate (https://5xxrw.csb.app/node_modules/react-router/index.js:247:12)
    at AuthenticationRoute (https://5xxrw.csb.app/src/components/Routes/AuthenticationRoute.jsx:21:26)
    at Routes (https://5xxrw.csb.app/node_modules/react-router/index.js:306:18)
    at App
    at Router (https://5xxrw.csb.app/node_modules/react-router/index.js:266:18)
    at BrowserRouter (https://5xxrw.csb.app/node_modules/react-router-dom/index.js:284:18)

The app should navigate back the user to the Home page (“/” route) instead of returning the error.

Here is the playground: https://codesandbox.io/s/stackoverflow-auth-private-routes-5xxrw

I did a similar thing using react-router-dom v5 but didn’t return the error. Everything was fine.

So, what’s the solution for this case?

Difference between Python’s cv2.imread(), Tensorflow’s JS tf.node.decodeImage()

Comparing the printings for a same image between the two mentioned functions I get different information.
For example using a 100×100 jpeg image in Python like:

path = "./test.jpeg"
training_data = []
pic = cv2.imread(path)
pic = cv2.cvtColor(pic,cv2.COLOR_BGR2RGB)
training_data.append(pic)
print(training_data[0][0])

For the first three rows, my print shows:

[[180  71  51]
 [233 145 125]
 [206 155 136]

Then, using the same image in VS Code with tf.node like:

const file_path   = "./test.jpeg";
const img = fs.readFileSync(file_path);
const tensor = tf.node.decodeImage(img, 3);
console.log(tensor.print())

For the same three rows, my print shows in console:

 [[[177, 70 , 50 ],
   [231, 144, 124],
   [201, 153, 133],

Altough the values are very similar, they are clearly different. Inspecting other values, they even match some times. So my question is what’s the difference between these two functions that generate different results for the same image? Also, what result should I expect from tf.browser.fromPixels(), the Python like result or tf.node?

Error deploying to vercel but no errors when I run npm run build

I’m trying to deploy my project to Vercel, so before I push my changes to GitHub I run npm run build, and it builds fine with no errors but when Vercel tries to build I get an error that it can not read properties of undefined (I believe this is because the function that makes the API call did not execute). How can I fix this?

Code that I think is causing the issue

export const getStaticProps = async () => {
    const popularCountries = ["Netherlands", "Poland", "Canada"]
    let countryData = [];
    const date = getDate();
    const promise1 = popularCountries.map(async country => {
        const options = {
            method: 'GET',
            url: 'https://covid-19-statistics.p.rapidapi.com/reports',
            params: {
              region_name: country,
              date: date
            },
            headers: {
              'x-rapidapi-host': 'covid-19-statistics.p.rapidapi.com',
              'x-rapidapi-key': process.env.RAPID_API_KEY
            }
        };
        await axios.request(options).then(response => {
            const data = response.data.data;
            const country_name = data[0].region.name;
            const date = data[0].date;
            const iso = data[0].region.iso;
            let cases = 0;
            let deaths = 0;
            data.map(item => {
                cases += item.confirmed;
                deaths += item.deaths;
            })
            countryData.push({
                "country_name": country_name,
                "date": date,
                "cases": cases,
                "deaths": deaths,
                "iso": iso
            })
        })
        .catch((error) => {
            console.error("error - ", error);
        });
        return countryData;
    })
    const returnedData = await Promise.all(promise1);
    const data = returnedData[0];

    return {
        props: { data },
        revalidate: 43200
    }
}

I’m stuck because I don’t get errors on my end so I’m not sure how to debug/fix this.

Discord JS v13 Get Status of Specific User

For the bot I’m writing I am trying to get the current status of the user that started an Interaction. This is my code, which seems perfectly fine according to the discord.js docs.

console.log(interaction.member.presence)

When running this, it outputs null.

enter image description here

Why is this happening? I’ve seen some people use fetching but I can’t seem to implement that into my app.

How can I make some arrow keys that can manipulate a js-tray-slider?

I am using this tutorial:
https://tympanus.net/codrops/2019/09/17/how-to-build-a-color-customizer-app-for-a-3d-model-with-three-js/

to create a similar concept.
However, in the color selection area (the swatches), I don’t want only to be able to use the mouse to “scroll” back and forth. I also want to be able to use some arrow keys similar to these ones:
Arrow keys to controls back and forth

However, I am having a hard time figuring out how this can be done, so I would appreciate some help.

Is this something that can be done?

Also, there is problem when you use the mouse or even use touch devices, that it will select colors while trying to slide back and forth, which is quite annoying because you can’t scroll without hitting every color you touch on the way.

How can this be fixed as well?

You can try out the whole site (the tutorial) on codepen here:

'https://codepen.io/kylewetton/pen/jONpxpa'

But I have also made a version with more colors, that is a little more simple:
js fiddle

SImple christmas tree in JS

I’m trying to make a trunk for this christmas tree. I want to use if so it can be with only one loop as in code. Any ideas how to do it? Thanks.

function Tree() {
    const star = "*";
    for (let i = 1; i <= 6; i++) {
      document.write(`${star.repeat(i)}<br/>`);
    }
  }

  Tree();

How can I return my data in this nested promise model?

I have this function, I created it but then I’m getting confused and don’t know how to return the data.

I have tried Promise.all() before but it’s seems I do not quite understand it so I have removed it from my code, I don’t know if it’s a correct way to do it or not.

I’m following this AniList Node Document

Here’s how the code work. I’m using POSTMAN to query the Title, for example, One Piece, it’ll then search the query title and get the ID of that Title in AniList. Then, it’s using that ID to find all the info (it’s in the detailInfo)

Here’s my Model:

static async getAnilist(title) {
const Anilist = new anilist()

const animeInfo = Anilist.searchEntry
    .anime(title, null, 1, 1)
    .then((titleToID) => {
        const animeID = titleToID.media[0].id
        const detailInfo = Anilist.media.anime(animeID).then((data) => {
            return {
                AnimeID: animeID,
                Schedule: data.airingSchedule[0],
                Score: data.averageScore,
                BannerImg: data.bannerImage,
                Character: data.characters,
                Country: data.countryOfOrigin,
                CoverImg: data.coverImage,
                Duration: data.duration,
                EndDate: data.endDate,
                EpisodeTotal: data.episodes,
                Genre: data.genres,
                Season: data.season,
                SeasonYear: data.seasonYear,
                Status: data.status,
                Studio: data.studios,
                UpdateAt: data.updatedAt,
            }
        })

        return detailInfo
    })
return animeInfo
}

Here’s my Controller:

static async getAnilist(req, res, next) {
    const { title } = req.query
    try {
        const { data } = await Model.getAnilist(title)

        res.json({
            success: true,
            data: data,
        })
    } catch (err) {
        next(err)
    }
}

What I’m hoping for:

"success" : true,
"data" : {
     AnimeID,
     Schedule,
     Score,
     BannerImg,
     ...
     UpdateAt
}

What I’m getting right now

"success" : true

but without any data due to I can’t return it.

The request is succeeded, but I don’t know how to actually return it from nested promise.

Here’s what I get from using console.log({AnimeID, Schedule...}) instead of return

INFO

Any way to force js engines to unroll a loop?

I have a performance critical queue container that does a lot of random inserts/deletes. In my container class, I have a fixed size Uint32Array called updates and in my insert logic, I need to compare a value to every value in this update array.

Originally, I did it simply like this:

const u = this.updates;
for (let i = 0; i < u.length; i++) bucket_offset += bi >= u[i];

Then, just as I was putting finishing touches on the container and just screwing around, I tried unrolling said loop

const u = this.updates;
bucket_offset += (bi >= u[0]) + (bi >= u[1]) + (bi >= u[2]) + (bi >= u[3]) + (bi >= u[4]) + (bi >= u[5]) + (bi >= u[6]) + (bi >= u[7]) + (bi >= u[8]) + (bi >= u[9]) + (bi >= u[10]) + (bi >= u[11]) + (bi >= u[12]) + (bi >= u[13]) + (bi >= u[14]) + (bi >= u[15]);

And turns out this is around 10x faster on chrome, making the whole insert ~30% faster.

After that revelation, I’m looking for a way to make the VM understand that its okay to unroll that loop, after all, this.updates.length is a constant.

At the end of the day, it can stay the way it is but I’d prefer a loop since it would just look nicer. Any ideas?

Iterate geojson data in a flatlist

Hello i want to make a flatlist with the geojson data
i want to access to 3 properties attributes and iterate it
the problem is i have only access in one data the same data is iterate it
//mon code

//la requete retourne un geojson
    const getAllAgr = () => {
          fetch('https://api.tolbico.com/api/agences/1/agriculteurs/', {
             method: 'GET',
             headers: { 
               'Authorization': 'Bearer '+ Token,
              'Content-Type': 'application/json'
             },
           }).then((response) => response.json())
           .then((json) =>{
              setAgriculteurs(geo.getProperties(json))
           
             })
          
    }
    useEffect(()=>{
        getAllAgr() 
        
         },[])            
    
       
    
        return (
                 //flatlist pour afficher les information      
                 <SafeAreaView>
                
                   <FlatList
                        
                      data={agriculteurs}
                      //keyExtractor={(item) => item.id.toString()}
                       renderItem={({item}) => <ListesAgr agro={item}/> }
                       />
    
                 </SafeAreaView>
        )
    }

How to reset button style in Javascript

function showQuestion(questionAndAnswers) {
    const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
    questionTag.innerText = questionAndAnswers.question;
    shuffledAnswers.forEach(({ text, correct }, i) => {
        answerTag[i].innerText = text;
        answerTag[i].dataset.correct = correct;
    });
}
document.querySelectorAll(".answer").forEach((answer) => {
    answer.addEventListener("click", (event) => {
        if (event.target.dataset ) {
            answer.style.border = "1.5px solid"
        } 
    });
});
function nextQuestion() {
    const nextIndex = currentQuestionIndex + 1;
    if (nextIndex <= myQuestions.length - 1) {
        showQuestion(myQuestions[nextIndex]);
        currentQuestionIndex = nextIndex;
    } else {
        end.style.visibility = "visible";
        nxt_question_btn.style.visibility = "hidden";
    }
}

Basically, In this quiz app, I have 4 buttons for answers and once you click on one answer it makes the border black. The problem I am facing is that once I press the next question, it loads up another question with 4 different answers but one of the buttons will still have the border black. How do I get it to reset once I load up another question? and Extra question if it’s okay, how can I only select one button at a time per question?