How can i Duplicate a slide using office js?

I am trying to develop a powerpoint add-in using officejs and it seems the simplest of the things, duplicating a slide, is not available. Anyone faced this issue before and has found a workaround it ?

I have tried to add a new slide and copy all the shapes of the slide I want to copy. But it is not working. Also, when should we use .load() function and for what items ??

Thank you for your help.

Next.js 14: Hydration Error | Warning: Only plain objects can be passed to Client Components from Server Components

I’m developing an app with Next.js 14, TypeScript, Mongoose & MongoDB.

I fetched users from my database and rendered them in cards with some of their information, like tags displayed in badges.

I also used the Link component to make the cards and the badges clickable.

Here is some of my relevant code:

  • “componentscardsUserCard.tsx”:
import Link from "next/link";
import Image from "next/image";

import { getTopInteractedTags } from "@/lib/actions/tag.action";
import { Badge } from "../ui/badge";
import RenderTag from "../shared/RenderTag";

interface Props {
  user: {
    _id: string;
    clerkId: string;
    picture: string;
    name: string;
    username: string;
    // orgId?: string;
  };
}

const UserCard = async ({ user }: Props) => {
  const interactedTags = await getTopInteractedTags({ userId: user._id });

  return (
    <Link
      href={`/profile/${user.clerkId}`}
      className="shadow-light100_darknone w-full max-xs:min-w-full xs:w-[260px]"
    >
      <article className="background-light900_dark200 light-border flex w-full flex-col items-center justify-center rounded-2xl border p-8">
        <Image
          src={user.picture}
          alt="image profil utilisateur"
          width={100}
          height={100}
          className="rounded-full"
        />

        <div className="mt-4 text-center">
          <h3 className="h3-bold text-dark200_light900 line-clamp-1">
            {user.name}
          </h3>
          <p className="body-regular text-dark500_light500 mt-2">
            @{user.username}
          </p>
          {/* {user.orgId && (
            <p className="body-regular text-dark500_light500 mt-2">
              Org ID: {user.orgId}
            </p>
          )} */}
        </div>

        <div className="mt-5">
          {interactedTags.length > 0 ? (
            <div className="flex items-center gap-2">
              {interactedTags.map((tag) => (
                <RenderTag key={tag._id} _id={tag._id} name={tag.name} />
              ))}
            </div>
          ) : (
            <Badge>Pas encore d’étiquettes</Badge>
          )}
        </div>
      </article>
    </Link>
  );
};

export default UserCard;
  • “componentssharedRenderTag.tsx”:
import React from "react";
import Link from "next/link";

import { Badge } from "@/components/ui/badge";

interface Props {
  _id: string;
  name: string;
  totalQuestions?: number;
  showCount?: boolean;
}

const RenderTag = ({ _id, name, totalQuestions, showCount }: Props) => {
  return (
    <Link href={`/etiquettes/${_id}`} className="flex justify-between gap-2">
      <Badge className="subtle-medium background-light800_dark300 text-light400_light500 rounded-md border-none px-4 py-2 uppercase">
        {name}
      </Badge>

      {showCount && (
        <p className="small-medium text-dark500_light700">{totalQuestions}</p>
      )}
    </Link>
  );
};

export default RenderTag;

However, I get this error:

Error: Hydration failed because the initial UI does not match what was
rendered on the server. See more info here:
https://nextjs.org/docs/messages/react-hydration-error

Expected server HTML to contain a matching in .

I tried many solutions, like replacing the article with a div or passing the suppressHydrationWarning property to the related elements to remove this warning.
However, these solutions didn’t help me fix this issue.

Therefore, I came out with another alternative which is using useRouter instead of Link for the navigation.

Here is my code:

  • “componentssharedRenderTag.tsx”:
"use client";

import { useRouter } from "next/navigation";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
interface Props {
  _id: string;
  name: string;
  totalQuestions?: number;
  showCount?: boolean;
}

const RenderTag = ({ _id, name, totalQuestions, showCount }: Props) => {
  const router = useRouter();
  return (
    <Button
      className="flex justify-between gap-2"
      onClick={() => router.push(`/tags/${_id}`)}
    >
      <Badge className="subtle-medium background-light800_dark300 text-light400_light500 rounded-md border-none px-4 py-2 uppercase">
        {name}
      </Badge>
      {showCount && (
        <p className="small-medium text-dark500_light700">{totalQuestions}</p>
      )}
    </Button>
  );
};

export default RenderTag;

Now, the hydration error disappears, but I get this warning in my terminal:

Warning: Only plain objects can be passed to Client Components from
Server Components. Objects with toJSON methods are not supported.
Convert it manually to a simple value before passing it to props.
<… _id={{buffer: …}} name=”next.js”>

Where this error is coming from, especially this part <... _id={{buffer: ...}} name="next.js">?

I guess it is related to my database “tags” collection whis has the following data:

{"_id":{"$oid":"66a476d397749b79a8140e72"},"__v":{"$numberInt":"0"},"createdOn":{"$date":{"$numberLong":"1722054355742"}},"followers":[],"name":"next.js","questions":[]}
{"_id":{"$oid":"66a5164197749b79a8a3258b"},"__v":{"$numberInt":"0"},"createdOn":{"$date":{"$numberLong":"1722095169919"}},"followers":[],"name":"React","questions":[]}

But, why I get this error only when I use useRouter?

Google Translate is not working in popupWin.document.write

I am trying to call google translate inside window.open but it’s not working. When adding the Google translate script it showing blank page. I have shared with you the script code.

<script type="text/javascript">
    function print() {
        var tableHtml = `<table>
                            <tr>
                                <th>Items</th>
                                <th class='number-left'>Qty</th>
                            </tr>`;
        items.forEach(function(item) {
            tableHtml += `<tr>
                            <td>${item.name}</td>
                            <td class='number-left'>${item.qty}</td>
                        </tr>`;
        });
        tableHtml += `</table>`;
        tableHtml += `<script>
                        function googleTranslateElementInit() {
                            new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');}
                            </sc'+'ript>
                            <script src='https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'></sc'+'ript>
                     `;
        tableHtml += `<br><div id="google_translate_element"></div>`;
        var divToPrint = document.getElementById('divToPrint');
        var popupWin = window.open('', '_blank', 'width=400,height=400');
        popupWin.document.open();
        popupWin.document.write('<html><head>'+
                                '<style>' +
                                '.number-right{text-align: right;}' +
                                '</style>'+
                                '</head><body onload="window.print()">' + tableHtml + 
                                '</html>');
        popupWin.document.close();
    }
</script>

I need to display Google Translate in popupWin.document.write. How I can achive that.

How can I post a message to an iframe loaded later without violating CORS policies?

I need to send a message to an iframe that is loaded after a user clicks a link.

The nature of the error message makes me believe that this is Javascript that is angry and not nginx. It seems like it didn’t even attempt the postMessage.

javascript console

(index):6 loading site2 iframe ...
(index):8 sending message from site1 to site2 ...
(index):9 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://site2.example.com') does not match the recipient window's origin ('http://site1.example.com').

site1.example.com/index.html

<html>
<head>
<script type="text/javascript">

    function loadIFrame() {
        console.log( "loading site2 iframe ..." );
        document.getElementById('myiframe').src = "http://site2.example.com";
        console.log( "sending message from site1 to site2 ..." );
        document.getElementById('myiframe').contentWindow.postMessage( "Hello World!", 'http://site2.example.com');
    }

</script>
</head>
<body>
    <h2>Site1</h2>

    <a href="#" onclick="loadIFrame()">load iframe</a>
    <br/><br/><br/>

    <iframe id="myiframe" style="width:600px; height: 400ps;"></iframe>

</body>
</html>

site2.example.com/index.html

<html>
<head>
<script type="text/javascript">
  window.addEventListener( 'message', event => {
    if ( event.origin === 'http://site1.example.com' ) {
      const item = event.data;
      console.log( "site2 received message: " + item );
    }
  });
</script>
</head>
<body>
<h2>Site2</h2>

<body>
</html>

site1.example.com nginx config

server {
    listen 80;
    server_name site1.example.com;

    location / {
        root /home/user/test-sites/site1;

    }
}

site2.example.com nginx config

server {
    listen 80;
    server_name site2.example.com;

    set $cors "";
    if ($http_origin ~* (.*.example.com)) {
        set $cors "true";
    }

    location / {
        root /home/user/test-sites/site2;

        if ($cors = "true") {
            add_header 'Access-Control-Allow-Origin' "$http_origin" always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
            add_header 'Access-Control-Allow-Credentials' 'true' always;
            add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
        }

        if ($request_method = OPTIONS) {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }
}

I should also mention that this header shows up in site2.example.com within the iframe

Referrer Policy:
strict-origin-when-cross-origin

I’m not sure if that should be different given my attempted configuration.

Any idea why this function always returns undefined for the third key:value pair? [closed]

I am trying to map multiple Lists of Strings together, however this function always ignores the last “parameter”, in this case j: any.

ListofARBR,ListofSENENG and ListofSENGER are all Lists of Strings

this.WebShopList = ListofARBR.map( function(x: any, i: any, j: any){
      return {"brar": x, "sen_eng": ListofSENENG[i], "sen_ger": ListofSENGER[j]}
    }.bind(this));

The return im getting is this:

enter image description here

As u can see the last parameter returns undefined even tho ListofSENGER(shown above) has 2 entrys

Can somebody point out my oversight? i feel like im missing something here

Ive tried switching ListofSENGER and ListofSENENG with the same outcome of the last attribute returning undefined

Google Maps Sidebar doesn’t wait for map to load (map fails to load completely)

I have a Google Maps Map with a HBM info box on one page of my WordPress Website.

The goal is to have the map load after the user accepts our cookies. We are using the Complianz plugin for the cookies.

When I visit the website and accept the cookies and head for the site where the map is located, the map is not loading (grey screen) and I’m getting thrown this error:

hbm_gmap_infobox.js?ver=1.0.0:128 Uncaught TypeError: Cannot read properties of undefined (reading 'OverlayView')
    at hbm_gmap_infobox.js?ver=1.0.0:128:37

jquery.min.js?ver=3.7.1:2 Uncaught TypeError: Cannot read properties of undefined (reading 'Map')
    at Object.init (hbm_gmap.js?rnd=449&ver=1.0.0:224:40)
    at Object.init (hbm_js.js?rnd=357&ver=1.0.0:22:18)
    at HTMLDocument.<anonymous> (hbm_js.js?rnd=357&ver=1.0.0:437:13)
    at e (jquery.min.js?ver=3.7.1:2:27028)
    at t (jquery.min.js?ver=3.7.1:2:27330)
init @ hbm_gmap.js?rnd=449&ver=1.0.0:224
init @ hbm_js.js?rnd=357&ver=1.0.0:22
(anonymous) @ hbm_js.js?rnd=357&ver=1.0.0:437
e @ jquery.min.js?ver=3.7.1:2
t @ jquery.min.js?ver=3.7.1:2
setTimeout (async)
ce.readyException @ jquery.min.js?ver=3.7.1:2
(anonymous) @ jquery.min.js?ver=3.7.1:2
e @ jquery.min.js?ver=3.7.1:2
t @ jquery.min.js?ver=3.7.1:2
setTimeout (async)
(anonymous) @ jquery.min.js?ver=3.7.1:2
c @ jquery.min.js?ver=3.7.1:2
fireWith @ jquery.min.js?ver=3.7.1:2
fire @ jquery.min.js?ver=3.7.1:2
c @ jquery.min.js?ver=3.7.1:2
fireWith @ jquery.min.js?ver=3.7.1:2
t @ jquery.min.js?ver=3.7.1:2
setTimeout (async)
(anonymous) @ jquery.min.js?ver=3.7.1:2
c @ jquery.min.js?ver=3.7.1:2
fireWith @ jquery.min.js?ver=3.7.1:2
fire @ jquery.min.js?ver=3.7.1:2
c @ jquery.min.js?ver=3.7.1:2
fireWith @ jquery.min.js?ver=3.7.1:2
ready @ jquery.min.js?ver=3.7.1:2
P @ jquery.min.js?ver=3.7.1:2

I also got this error, but now it suddenly disappeared:


 ReferenceError: google is not defined at hbm_gmap_infobox.js?ver=1.0.0:128:25

If you reload the website a couple times the map will show up. There you can also see the infobox when you click on the eye-icon. It seems that the the infobox script does not wait for the google api to load first.

In the Complianz Plugin’s Script center I can whitelist scripts, so that they only get loaded when the user accepts our cookies. I put both scripts on that whitelist, but it didn’t help at all. I even wrote a custom script that you can find below. It also didn’t change the behaviour of our map.

// Custom Google Maps Initialization Script, written by Erick Holz, 21.06.2024

// Load Google Maps JavaScript API into website
function loadGoogleMapsAPI() {
    var script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?key=OUR_API_KEY&libraries=places&callback=initMap';
    script.async = true;
    script.defer = true;
    document.head.appendChild(script);
}

// Map initialisation, if Google API was successfully loaded
function initMap() {
    var mapOptions = {
        center: new google.maps.LatLng(51.1657, 10.4515), // Preset map-coordinates of the geographical center of Germany
        zoom: 8,
    };
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);

    // Load scripts, which depend on the Google Maps API
    var infoboxScript = document.createElement('script');
    infoboxScript.src = '/wp-content/plugins/hopfenheldenbeermap/public/js/hbm_gmap_infobox.js'; // Path to Infobox JavaScript for Google Maps
    infoboxScript.async = true;
    infoboxScript.onload = function() {
        // To make sure that the script was successfully loaded
    };
    document.head.appendChild(infoboxScript);
}

// Load Google Maps API after consent was given by user
if (typeof cmplzHasConsent === 'function' && cmplzHasConsent()) {
    loadGoogleMapsAPI();
} else {
    document.addEventListener("cmplz_event_functional", function() {
        loadGoogleMapsAPI();
    });
}

Here’s the link to our website: https://www.hopfenhelden.de/

And here to the Map: https://www.hopfenhelden.de/wo-gibt-es-craft-beer/

I tried using only the script center inside of the Complianz plugin, then the custom script alone and then both together. Nothing worked or changed any behaviour. I really tried any solution that I could come up with.

I’m also having messages like:

If I remove the custom script I’m getting a message that the custom script from before can’t be loaded. So it clearly sees the script. Down below is the message I get, when I remove the script from its location.

custom-google-maps.js:1 
        
        
Failed to load resource: the server responded with a status of 404 ()

wo-gibt-es-craft-beer/:1 Refused to execute script from 'https://www.hopfenhelden.de/wp-content/themes/x-child/js/custom-google-maps.js' 
because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

I cleared the cache and all, but it’s still there. Just for your information.

Thank you.

is there a way to open a popup when CLICKING on a html5 table CELL?

I have a html5 table and am wondering if anyone can point me in the right direction when it comes to opening a popup when the user clicks on the CELL inside of the table? I already understand that I will have to use js/jq – so I went and got the recent release of JQ and inside of my table, attached to the cell I am using this: <td><a href="details.html"></a></td> – but nothing happens 🙁

I want to be able to present a popup form when the user clicks on a single cell within a html5 table. I have tried to embed href tag to the cell, I have tried making each cell (contenteditable) – but that just allows me to type into the cell directly and this is not what I want to do. I need them to type into the FORM that will open when clicking on the cell.

CSS Animation from one element to another

good day all , please i need help to design animation that move from 1 element to another element

   IMGONE
     ↑
    11
   11 11
 11 11 11
11 11 11 11
    ↓
 IMGTWO

also exmple

  +-----------------+
  |     IMGONE      |  <-- Target Image
  +-----------------+
         ↑
         |
         |   Dots move upwards in a curved path
         |
         ↓
  +-----------------+
  |     IMGTWO      |  <-- Source Image

more like tapswap boost from the tap circle to the coin at the top

here is what i have tried here is what i want to achieve, not the tap but the coin entry

How to Make a Button Redirect to Employer Website Using URL from Custom Field?

I’m working on a WordPress project where I need a button to redirect users directly to an employer’s website. The URL for the website is stored in a custom field called employer-website.

Here’s the scenario:

The custom field employer-website contains the URL of the employer’s website.
I want a button on the employer’s profile page that, when clicked, takes the user to the URL specified in the employer-website custom field.
How can I achieve this functionality in WordPress?

Any help or guidance on how to implement this would be greatly appreciated. Thank you!

This is the button

How to clone Trix default link button?

I would like to add a button to Trix editor that would insert YouTube video using custom HTML attribute. It seems to me that default link button is exactly what I need. I would need to just modify little bit what is done once someone click the link button after text is entered.
enter image description here

The standard link button

  • has Trix menu button
  • has input field
  • has input value validation
  • link and unlink functionality. I might want to remove the unlink button
  • inserts text into editor

I was searching the net but did not find any example how to achieve what I want. The closest solution is https://www.kindleman.com.au/blog/advanced-actiontext-modifications-for-cms-use/ the embed, image, and link buttons are basically what I want. But it is coded in RoR. I know nothing about RoR.

Could someone help me to create my link (embed) button in Trix?

Delete a specific field meeting specific conditions from an object in a collection

I have searched the web for possible solutions. Basically a field needs to be deleted where the id of an object in an array of objects meets a specific condition.

As a newbie to Mongodb I am not sure where exactly to look for relevant examples.

I want to delete the object where id = 0. The language used will be Javascript.

Not quite sure how to go about it though.

enter image description here

open ai api key not working i’m unable get any data [closed]

Task: Create a simple web application that integrates a chatbot using a language model API.
Requirements:

  1. Frontend:
    • Design a simple chat interface using HTML, CSS, and JavaScript
    • Implement a text input field for user messages
    • Display chat history (bot and user messages)
  2. Backend:
    • Set up a basic server using Node.js and Express.js
    • Implement an API endpoint to handle user messages
  3. AI Integration:
    • Integrate a language model API (e.g., OpenAI’s GPT-3.5 or a similar service)
    • Send user messages to the language model and receive responses
  4. Database:
    • Store chat history in a simple database (e.g., MongoDB or postgre )
  5. Deployment:
    • Deploy the application to a free hosting service (e.g., Heroku or Vercel)

This is my task i did all the frontend part and this is the output i got for frontendfrontend output
and when i add api key from openai and when i run on the node js server i’m not getting the response This is the error i,m getting
give me the solution how will i rectify this error and get the correct output like how chatgpt works in that way i want my chatbot to work.
[this is my server.js code]:

const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const app = express();
const port = 3000; // You can change this port if needed

app.use(cors()); // To allow cross-origin requests from your client
app.use(bodyParser.json());

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

// Define your chat API endpoint
app.post('/api/chat', async (req, res) => {
    const { message } = req.body;

    const apiUrl = "https://api.openai.com/v1/chat/completions";
    const apiKey = "sk-None-60qqAyJu0nEC1Ux7hB4MT3BlbkFJR6VwhrQJS5mwENY8qnLc"; // Replace with your actual OpenAI API key

    const data = {
        "model": "gpt-3.5-turbo",
        "messages": [
            { "role": "system", "content": "Welcome to Curious Advisor! How can I assist you today?" },
            { "role": "user", "content": message }
        ]
    };

    try {
        const response = await axios.post(apiUrl, data, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            }
        });

        if (response.data && response.data.choices && response.data.choices.length > 0) {
            res.json({ response: response.data.choices[0].message.content });
        } else {
            res.status(500).json({ error: 'No response from OpenAI API' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'An error occurred while sending the chat message.' });
    }
});

// Serve index.html for the root route
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});



[This is my chatbot.js file]
document.addEventListener("DOMContentLoaded", function (e) {
    let chatbotName = "";
    let chatLog = document.getElementById("chat-log");
    let scrollPosition = 0;
    let sendBtn = document.getElementById("send-btn");
    let userInput = document.querySelector(".user-input");
    const serverUrl = "http://localhost:3000/api/chat"; // Update to your server URL if different

    function showWelcomeMessage(chatName) {
        const welcomeMessage = document.getElementById("welcome-message");
        welcomeMessage.textContent = `Welcome to ${chatName}! How can I assist you today?`;
    }

    function generateChatbotName() {
        const adjectives = ["Amazing", "Brilliant", "Creative", "Dynamic", "Energetic"];
        const nouns = ["Bot", "Assistant", "Companion", "Guide", "Helper"];

        const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
        const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];

        return `${randomAdjective} ${randomNoun}`;
    }

    function setChatBotName() {
        chatbotName = generateChatbotName();
        document.querySelector(".chatbot-name").textContent = chatbotName;
        document.title = chatbotName;
        showWelcomeMessage(chatbotName);
    }

    setChatBotName();

    function processSpecialCommand(command) {
        if (command === "/help") {
            displayMessage("sent", "You can ask questions or seek assistance. How may I help you?");
        } else if (command === "/about") {
            displayMessage("sent", "I am a chatbot designed to assist you. Feel free to ask me anything!");
        } else {
            displayMessage("sent", "I'm sorry, I don't understand that command. Type /help for assistance.");
        }
    }

    sendBtn.addEventListener("click", async function () {
        let userMessage = userInput.value.trim();
        if (userMessage !== "") {
            if (!checkInternetConnection()) {
                displayMessage("error", "Sorry, you're offline. Please check your internet connection.");
                return;
            } else {
                if (userMessage.startsWith("/")) {
                    const command = userMessage.toLowerCase();
                    processSpecialCommand(command);
                } else {
                    try {
                        displayMessage("sent", userMessage);
                        let response = await sendChatMessage(userMessage);
                        if (response) {
                            displayMessage("received", response.response);
                            scrollChatLog();
                        }
                    } catch (error) {
                        console.error(error);
                        displayMessage("error", "Error: Failed to fetch response from the server.");
                    }
                    userInput.value = "";
                }
            }
        }
    });

    async function sendChatMessage(message) {
        showLoadingIndicator();
        try {
            let response = await fetch(serverUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({ message })
            });
            hideLoadingIndicator();
            if (!response.ok) {
                throw new Error("An error occurred while sending the chat message.");
            }
            let responseData = await response.json();
            return responseData;
        } catch (error) {
            hideLoadingIndicator();
            console.error(error);
            throw error;
        }
    }

    function displayMessage(type, message) {
        let messageContainer = document.createElement("div");
        messageContainer.classList.add("message", type);
        let messageText = document.createElement("p");
        messageText.textContent = message;
        messageContainer.appendChild(messageText);
        chatLog.appendChild(messageContainer);
        chatLog.scrollTop = chatLog.scrollHeight;
    }

    function checkInternetConnection() {
        return navigator.onLine;
    }

    function showLoadingIndicator() {
        document.getElementById("loading-indicator").style.display = "flex";
    }

    function hideLoadingIndicator() {
        document.getElementById("loading-indicator").style.display = "none";
    }

    function scrollChatLog() {
        let isScrolledToBottom = chatLog.scrollHeight - chatLog.clientHeight <= chatLog.scrollTop + 1;
        chatLog.scrollTop = chatLog.scrollHeight;
        if (isScrolledToBottom) {
            restoreScrollPosition();
        }
    }

    function restoreScrollPosition() {
        chatLog.scrollTop = scrollPosition;
    }
});

check if i have any error in my code

i’m trying to make a chatbot by using html,css,js by using api key from openai . but i’m not getting response. i don’t know weather i have problem with my code or the api key. but i this i have problem with my openai api key. can you please tell hoe to fetch data from openai api key

Why is the animated circle in canvas not perfectly full?

I have a problem: I am trying to animate a circle. The circle should start shrinking from the top right to bottom left, until its perfectly full. The problem is – that its not.

const canvas = document.getElementById("circle");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#000000";
ctx.lineWidth = 7;

const speed = 40;

const drawCircle = (
  x,
  y,
  r,
  startPoint = 0,
  endPoint = 2 * Math.PI,
  fill = true
) => {
  ctx.beginPath();
  ctx.arc(x, y, r, startPoint, endPoint);
  if (fill) ctx.fill();
  ctx.stroke();
};

let endPoint = 1.75 * Math.PI;
let startPoint = 1.75 * Math.PI;

function animateCircle() {
  if (startPoint >= 0.75 * Math.PI && endPoint <= 2.75 * Math.PI) {
    drawCircle(280, 210, 20, startPoint, endPoint);
    endPoint += Math.PI / speed;
    startPoint -= Math.PI / speed;
    requestAnimationFrame(animateCircle);
  }
}
requestAnimationFrame(animateCircle)
#circle {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  <canvas id="circle" height="450px" width="450px"></canvas>
  <script src="script.js"></script>
</body>
</html>

fiddle.

I tried logging the values of startPoint and endPoint into console and it logged slightly different values (for example, at the end, the value of startPoint should be 0.75, but its something like 0.7492840947). Idk if why is that happening and if its the reason.

webkit-linear-gradient :: Setting Relative Colors With Javascript

My goal is to retain the same distance between the colors by any given color.

So in that specific case I want to set the end color to:

#bb0303

and get

#e13c3b

without the need to set it statically off-course 🙂

(or vice versa)

so iow…

I need the mathematical equation to set one color and get the other one RELATIVELY to that color.

So the start given color #bb0303 would set #e13c3b at the end color.

(OR vice versa)

the end given color #e13c3b would set #bb0303 at the the start color.

Here is my code:

function setRelativeColor(myElement,refColor)
{
    myElement.style.background='-webkit-linear-gradient(270deg,#e13c3b 0%,#'+refColor+' 100%)';
}


const myDiv=document.createElement('div');

myDiv.style.width='300px';
myDiv.style.height='80px';

setRelativeColor(myDiv,'bb0303');

document.body.appendChild(myDiv);