How do i make my fetchMovieDescription function to get called after the story state has changed?

I cant make the fetchMovieDescription function to get called only after my story state is changed, instead, it gets called in the same time as fetchBotReply and generates a random image instead of the one from the story result.

import { process } from '../env'
import { Configuration, OpenAIApi } from 'openai'
import { useState, useEffect } from 'react'

const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY
})

const openai = new OpenAIApi(configuration)

export default function StoryPart() {
    const [userInput, setUserInput] = useState("")
    const [story, setStory] = useState("")
    const [images, setImages] = useState("")
    const [storyFetched, setStoryFetched] = useState(false);

    useEffect(() => {
            fetchMovieDescription(story);
    }, [storyFetched])

    const handleChange = (event) => {
        setUserInput(event.target.value);
    }

    const handleSubmit = async (event) => {
        event.preventDefault();
        await fetchBotReply(userInput);
        setUserInput("");
    }

    async function fetchBotReply(userInput) {
        try {
        const response = await openai.createCompletion({
            model: 'text-davinci-003',
            prompt: `You are an AI developed by OpenAI.
            You have been trained on a vast range of internet text.
            But unlike most AI models, your specialty is in creating unique and compelling movie scenarios.
            You understand the elements of a great movie, including plot development, character arcs, conflict, and resolution.
            You can generate scenarios in any genre, time period, or setting.
            Your task is to write a scenario based on: ${userInput}.You must create the scenario so its easy to split it into 5
            sections.The reason for it is that based on each section i will later ask you to write 5 detailed descriptions
            of an image for later image generation.`,
            max_tokens: 700,
            temperature: 1
        })
        setStory(response.data.choices[0].text)
        setStoryFetched(true)
    } catch (error) {
        console.log(error)
    }
    }


    async function fetchMovieDescription(story) {
        try {
        const response = await openai.createImage({
            prompt: `Create a descriptive and precise prompt for image generation based on this story: ${story}`,
            n: 1,
            size: "512x512",
            response_format: 'url'
        })
        console.log(story)
        setImages(response.data.data[0].url)
        console.log(response.data.data[0].url)
    } catch (error) {
        console.log(error)
    }
    }


    return (
        <div className="StoryPart">
            <form onSubmit={handleSubmit}>
                <label>
                    Story:
                    <input value={userInput} type="text" name="story" placeholder='input prompt' onChange={handleChange}/>
                </label>
                <button type="submit" value="Submit">Submit</button>
            </form>
        {story? <p>{story}</p> : "Writing your story..."}
        {images? <img src={images} alt="movie scene"/> : "Writing your images..."}
        </div>
    )
}

i tried making another state storyFetched to change after the story has changed but no effect.

How to execute a script again after click button

I have a HTML template with a script to manage cookies permissions:

<!DOCTYPE html>
<html lang="fr">
  <head>
    <script id="consentementCookiesScript"></script>

The cookies permissions’ language is set according with the Lang att into the tag html.

I manage creating a btn to change dynamically the Lang att:

<div id="toolbar" class="toolbar">
          <div id="changeLangElement" style="color: white">Français</div>
        </div>

through this function:

 changeLangElement.onclick = function () {
        currentLang = currentLang === "fr" ? "en" : "fr";
        translatePage(currentLang);
        document.documentElement.lang = currentLang;
      };

Is there any way to execute the script again with the right language after click the button?

How to fix an `invalid BigNumber value` in ethers contract interaction?

This is a Nft raffle dapp, which basically allows users to raffle erc720 tokens. I’m trying to implement this function using react.

Contract:
buyTicket

Error: invalid BigNumber value (argument="value", value=undefined, code=INVALID_ARGUMENT    version=bignumber/5.7.0)
at Logger.makeError (index.ts:269:1)
at Logger.throwError (index.ts:281:1)
at Logger.throwArgumentError (index.ts:285:1)
at BigNumber.from (bignumber.ts:289:1)
at NumberCoder.encode (number.ts:25:1)
at array.ts:71:1
at Array.forEach (<anonymous>)
at pack (array.ts:54:1)
at TupleCoder.encode (tuple.ts:54:1)
at AbiCoder.encode (abi-coder.ts:111:1)

But stuck up with an error, and doesn’t even know why.

Here’s the buyTicket handle:
testing-Component-with-basic-logic-implemented

Note: The unit being handled in the contract is in ‘wei’.

Console output:
console-output

P.S: The contract is tested using remix and every function works fine (including the buyTicket function).

How to hover over a node to highlight specific links in Vega

I’m new in VEGA and I am using this example provided by developers to plot a network. However, I’m trying to highlight the links when I hover into nodes.

I have tried to follow the edge bundling example to achieve that. Then, into the signals and Marks:
Signals:

  "signals": [    { "name": "colorIn", "value": "firebrick" },
{ "name": "colorOut", "value": "forestgreen" },
{ "name": "originX", "update": "width / 2" },
{ "name": "originY", "update": "height / 2" },
{
  "name": "active", "value": null,
  "on": [
    { "events": "symbol:mouseover", "update": "datum.id" },
    { "events": "mouseover[!event.item]", "update": "null" }
  ]
}

Marks->”path”->”encode”->”update”

       "stroke": [
            {"test": "datum.source === active", "signal": "colorOut"},
            {"test": "datum.target === active", "signal": "colorIn"},
            {"value": "steelblue"}
          ],

How can I add toppings to a p5.js pizza slice randomly based on size and avoid looping when adding more toppings?

I am creating a pizza in p5.js, and want to add toppings. The toppings I want to add, I want placed randomly on the pizza slice, but I have 3 different pizza sizes, small, medium, and large. I want the toppings to match with the pizza size, as in if the pizza size is small, then I won’t have toppings going over the edge of the pizza circle. I was using a for() loop, and random() to get desired area of the toppings. When I click checkbox1, the color and rectangles appear, but they seem to be looping over and over again. I don’t want the toppings to loop over and over, and I want to put more toppings over top of it. What should I do to stop it from looping?

Html:

<div id="sizeContainer" class="radio-container">Pick a size!<br>
        <input type="radio" name="radionbutton" value="one" id="button1" onchange="checkS()" />
        <label for="button1">Small</label><br>
        <input type="radio" name="radionbutton" value="two" id="button2" onchange="checkM()" />
        <label for="button2">Medium</label><br>
        <input type="radio" name="radionbutton" value="three" id="button3" onchange="checkL()" />
        <label for="button3">Large</label><br>
        </div>
        <div id="toppingContainer" class="checkbox-container">Choose some toppings!
            <input type="checkbox" name="checkbox" value="oneC" id="checkbox1"/>
            <label for="checkbox1">Pepperoni</label>
            <input type="checkbox" name="checkbox" value="twoC" id="checkbox2"/>
            <label for="checkbox2">Cheese</label>
            <input type="checkbox" name="checkbox" value="threeC" id="checkbox3"/>
            <label for="checkbox3">Musrooms</label>
            <input type="checkbox" name="checkbox" value="fourC" id="checkbox4"/>
            <label for="checkbox4">Olives</label>
            <input type="checkbox" name="checkbox" value="fiveC" id="checkbox5"/>
            <label for="checkbox5">Pineapple</label>
        </div>

Javascript:

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
let checkbox1 = document.getElementById("checkbox1");
let checkbox2 = document.getElementById("checkbox2");
let checkbox3 = document.getElementById("checkbox3");
let checkbox4 = document.getElementById("checkbox4");
let checkbox5 = document.getElementById("checkbox5");

function draw() {
  background(175, 40, 33);
  if (button1.checked) {
    fill(227,217,202);
    circle(200,200,100);
  }

  if (button2.checked) {
    fill(227,217,202);
    circle(200,200,200);
  }
  
  if (button3.checked){
    fill(227,217,202);
    circle(200,200,300);
  }
  
  if (checkbox1.checked){
    fill("green");
  }

  if(checkbox2.checked){
    fill("purple");
  }
  
  for (let i = 0; i < 600; i++) {
    push();
    randAng = random(0, 2 * PI);
    distFromCenter = random(0, 40);
    offsetX = distFromCenter * cos(randAng);
    offsetY = distFromCenter * sin(randAng);
    x = 200 + offsetX;
    y = 200 + offsetY;
    translate(x, y);
    rotate(random(0, 2 * PI));
    strokeWeight(0);
    rect(0, 0, 4, 4);
    pop();
  }

}

function checkS() {
  button1.checked;
}

function checkM() {
  button2.checked;
}

function checkL(){
  button3.checked;
}

function setup() {
  myCanvas = createCanvas(400, 400);
}

Thank you.

Image not loading before Javascript+Python function ends

I’m using python with eel to communicate with a local website as frontend. My code should display an image on a web page while in the middle of a long python function. The image only appears after the python function is executed, even though is present in the HTML at the correct time.

Here’s my Javascript code:

eel.expose(set_image);

function set_image() {
    document.getElementById("zoom-animate").innerHTML = '<img src="temp.png">';
}



function generate() {
    let source = document.getElementById("source").value;
    let keyword = document.getElementById("keyword").value;
    eel.generate(source, keyword);
}

And my Python code:

def generate(source, keyword):
    # code that takes a long time to execute 1
        eel.set_image()
    # code that takes a long time to execute 2

Why can’t I open images uploaded to Google Drive using Dropzone and Javascript?

I’ve been trying to upload images using dropzone and save them in google drive. Here is the code

 data = google.drive({
                    version: "v3",
                    auth
                }).files.create({
                    media: {
                        mimeType: uploadFiles[0].type,
                        body: fullpath
                    },
                    requestBody: {
                        name: uploadFiles[0].filename,
                        mimeType: uploadFiles[0].type,
                        parents: [""]
                    },
                    fields: "id,name"
                }).then();

The thing is, it is uploading in google drive but the image is not opening neither on google drive nor when I download it. It says “It appears that we don’t support this file format”

Can anyone help? Thanks

I don’t really know what I can do to make this work. When I coded it at first, it was uploading the wrong format now it seems to be working correctly, just that little thing of not opening

How to build a webpage with multiple autoplay and loop video tags (mp4 files)

I’m looking for ways to make a web page containing many video tags within it.
These mp4 videos are short, about 7 seconds and a size of about 100KB, they are looped and autoplayed.

Here is an example of the video tag I’m using:

<video autoplay loop muted playsinline>
   <source src="my-video.mp4" type="video/mp4">
</video>

The problem is that many times (especially on mobile devices), not all videos are loaded correctly. Sometimes they don’t appear at all, sometimes they appear but they don’t play. The number of videos that are uploaded correctly varies with each refresh, and not always the same videos are loaded correctly. This makes me think it is not an issue of mp4 files.

The question is
Is there a way to ensure that each video is loaded correctly and is autoplayed?
Can it be a correct approach to force loading with javascript if the video is not loaded correctly, and then play it?
Is there a way to achieve this or is it impossible? Maybe a js library?

I tried to force play through javascript, after a period of time after the page is loaded, but it didn’t work

Example:

setTimeout(function() {
    myVideo.play();
}, 5000);

Thanks in advance

Problem declaring in if statement and the use it in functions

My problem lies in defining a variable inside an if statement and using it in a function like:

Why is this not working? Are there any workarounds to the issue?My goal is to use as little variables as possible

let level

function findLevel(){
   if (document.title.indexOf("PageTitle") != -1) {
      level = 1
   }else{
      level = 2
   }
}

if (level == 1) {
  var x = 1
  //more variables like x that are going to be used in more than one functions..
}else{
 var y = 2
//more variables like y that are going to be used in more than one functions..
}

function functionName() {
  console.log(level)    // prints 1
  console.log(x)        // prints undefined
  // ...some Work...
}

function functionName2(){
 //also need x or y
}

//more functions like this
window.onload =function(){ 
 findLevel(); functionName();
}

My goal is to declare as minimum as possible variables I can

Is there a more efficient way to build a simple counter app using addEventListener in JavaScript?

I am wondering if there is a faster way of building a simple counter app. It works just fine but I want to improve it.

HTML

<button class="button">
        Increment
    </button>
    <button class="decrement">
        Decrement
    </button>
    <button class="clear">
        Clear
    </button>
    <p id="counter">
        0
    </p>

JS

const increment = document.querySelector(".button")
decrement = document.querySelector(".decrement"),
clear = document.querySelector(".clear"),
counter = document.getElementById("counter");

clicked = 0;


increment.addEventListener("click", () => {
    clicked++;
    counter.innerHTML = clicked;
    
})

decrement.addEventListener("click", () => {
    clicked--;
    counter.innerHTML = clicked;
})


clear.addEventListener("click", () => {
    clicked = 0;
    counter.innerHTML = clicked;
})

I built one but i feel like it can be more efficient instead of having three separate event listeners. Is there a faster way of doing this?

What is the solution to use route handlers when dealing with forms in Next.js 13?

Next.js 13 brought with it the route handlers and server action update. I am used to using route handlers when dealing with forms, but it seems that route handlers are not an option anymore?

'use server'
import { Product } from "@models/Product";
import clientPromise from "@utils/database";
import { mongooseConnect } from "@utils/mongoose";
import mongoose from "mongoose";
import { NextResponse } from "next/server";

export async function POST(req) {
    'use client'
    mongoose.Promise = clientPromise;
    //await mongooseConnect();
    const {title, description, price} = await req.json();
    const productDoc = await Product.create({
      title,description,price,
    })
    return NextResponse.json({productDoc});
  }

  export async function GET(Request) {
    return NextResponse.json({response: "This is a new API route"});
  }

I will get one of the two errors and these are to do with the ‘use…’ actions:

  1. Error: Cannot access .create on the server. You cannot dot into a client module from a server component. You can only pass the imported name through.

    This happens when there are not a single ‘use…’ written and while there are both written

  2. Error: Attempted to call POST() from the server but POST is on the client. It’s not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.

    This happens when I write ‘use client’ on the first line.

Is there are workaround for this or what would be the best course of action here?

Sending SSL Certificate Using Fetch

I am sending an API call through a browser and I keep hitting this error in the console “Failed to load resource: net:: ERR_CERT_AUTHORITY_INVALID”. The way I was able to get around this is by adding –ignore-certificate-errors, but this is a temporary fix and would only work from my browser. I do have an SSL certificate but I am not sure how to add it into my API call. I am using Javascript fetch to send my request. This is a sample of what my request looks like:

var myHeaders = new Headers();
 myHeaders.append("X-Client-Id", "{CLIENT ID}");
 myHeaders.append("X-Client-Secret", "{CLIENT SECRET}");
 myHeaders.append("Content-Type", "application/json");
 myHeaders.append("", "");
 var raw = JSON.stringify({"Id":"28366327648263"});

  var requestOptions = {
method: ‘POST’,
headers: myHeaders,
body: raw,
redirect: ‘follow’
};
 
fetch(“https://{URL}”, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log(‘error’, error));

How can I validate links with CKEditor using regex?

I’m working on a cms that uses CKEditor and I want to validate links using regex. There was a similar question asked and answered 7 years ago (Validating two inputs in CKEditor dialog) but when I try this, I get an error. I’m not sure whether this is because CKEditor has moved on since then or because my setup is different. I’m using the setup as outlined here (https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/quick-start-other.html#building-the-editor-from-source) to better understand how CKEditor works.

As described in the link above my setup is as follows:

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ Link, Essentials, Paragraph, Bold, Italic, Alignment  ],
        toolbar: [ 'bold', 'italic', 'link', 'alignment' ],
        link: {
            decorators: {
                openInNewTab: {
                    mode: 'manual',
                    label: 'Open in a new tab',
                    defaultValue: true,         // This option will be selected by default.
                    attributes: {
                        target: '_blank',
                        rel: 'noopener noreferrer'
                    }
                }
            }
        }
    } )
    .then( editor => {
        console.log( 'Editor was initialized', editor );
    } )
    .catch( error => {
        console.error( error.stack );
    } );

I then have:

ClassicEditor.on('dialogDefinition', function (ev) {
    console.log("Test")
});

but get the error: “ClassicEditor.on is not a function”

if I instead use:

CKEDITOR.on('dialogDefinition', function (ev) {
    console.log("Test")
});

the error is CKEDITOR is not deifined

Need help finding all occurrences of numbers in a string and then formatting those numbers

I need help finding all occurrences of numbers in a string and then I need to format those numbers and then replace the old unformatted numbers with the new formatted ones in the same string. I can’t hard code the values as I don’t know what the values will be as I’m pulling this data in from an api. Here is an example sentence…

“Chiliz (CHZ) is a cryptocurrency and operates on the Ethereum platform. Chiliz has a current supply of 8,888,888,888 with 7,000,647,158.46161 in circulation. The last known price of Chiliz is 0.10155361 USD and is up 0.76 over the last 24 hours. It is currently trading on 340 active market(s) with $33,201,362.31 traded over the last 24 hours. More information can be found at https://www.chiliz.com/.”

Here is another example…

“Bitcoin (BTC) is a cryptocurrency launched in 2010. Users are able to generate BTC through the process of mining. Bitcoin has a current supply of 19,387,181. The last known price of Bitcoin is 27,840.34813494 USD and is up 2.26 over the last 24 hours. It is currently trading on 10233 active market(s) with $16,962,015,081.95 traded over the last 24 hours. More information can be found at https://bitcoin.org/.”

As you can see, the structure of the sentence is always changing. I already have a format function to format the numbers and currencies using the Intl numberFormat. I’m just not sure how to get each number in the string/sentence and replace it with formatted version of itself. Any help would be greatly appreciated! Thanks!