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);

how to handle validate form to next page use vue router

a form after validate must go to next author page with vue-Router using this code but not validate

  <form @submit.prevent="handlesubmit">

            <div class="row">
              

                <div class="col-md-4 mb-3">
                    <label>Name</label>
                    <input type="search" class="form-control" placeholder="" v-model.lazy.trim="form.nameTitle">
                    <div class=" text-danger">
                        {{ form.titleNameErrorText }}
                    </div>
                </div>
               

            <div class="row mt-4">
                <div class="col-6 ">
                    <button class="btn btn-primary btn-style" type="submit" >Submit
                        </button>
                </div>

            </div>
        </form>

js code and vue router handle next page after validation


> import { reactive } from "vue";
import { useRoute, useRouter } from 'vue-router'

export default {
    setup() {
        const router = useRouter();
        const form = reactive({
            nameTitle: "",
            familyTitle: "",
            addressTitle: "",
            phoneNumber: "",
            titleNameErrorText: "",
            titleFamilyErrorText: "",
            titleAddressErrorText: "",
            titlePhoneErrorText: "",
            name: "FormAddress",

        });



        function validate() {


            if (form.nameTitle.length < 3) {
                form.titleNameErrorText = "نام حداقل باید دارای 3 حرف باشد   "
            }
            else {
                form.titleNameErrorText = ""
            }
            if (form.familyTitle.length < 3) {
                form.titleFamilyErrorText = "نام خانوادگی حداقل باید دارای 3 حرف باشد   "
            }

            else {
                form.titleFamilyErrorText = ""
            }
            if (form.addressTitle.length < 3) {
                form.titleAddressErrorText = "آدرس حداقل باید دارای 3 حرف باشد   "
            }

            else {
                form.titleAddressErrorText = ""
            }

            const phonepattern = /^09d{9}$/;
            if (!phonepattern.test(form.phoneNumber)) {
                form.titlePhoneErrorText = "شماره وارد شده صحیح نمی باشد"
            }
            else {
                form.titlePhoneErrorText = "";
            }


        }


        function handlesubmit() {

            if (validate()) {
                console.log("amir")
                router.push({ name: 'map' })
            }

        }

        return { form, validate, handlesubmit }



    },



}



submit go to map page and no validate this current page im handle validate page and success form element next page else stay this page
///////////////////

React problem with setting data into constant [duplicate]

I have piece of code to put image URL from server part into JSON payload. I’ll show you what it looks like in code and what output gives the browser:

const url = `${apiUrl}/api/image/${barcode}`;
console.log("variable url:", url);
setPhotoUrl(`${apiUrl}/api/image/${barcode}`);
console.log("photoUrl when i put full url string:", photoUrl);
setPhotoUrl(url);
console.log("photoUrl when i put url variable inside:", photoUrl);

Output from browser:
browser output

Why this url don’t want to set in photoUrl constant even if it’s working in url variable?

How to store the programmitc zoom for mouse zoom not to start at 0,0 scale 1 again

I have a d3 v4 script which draws a windrose / pie chart type graphic which is tweened into to the canvas from x:0, y:0 to the middle of the canvas.

When a User zooms that windorose catapults back to 0,0 and scale 1. How can I make sure the zooming isn’t catapulting the windrose back to 0 again.

Starts like this.

// Zoom Behavior V4.
var zoom = d3.zoom().scaleExtent([0.5, 8]).on( “zoom”, zoomed );

This is the zooming base:

 var svg = d3.select("#group_canvas").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate( 0, 0 )scale(1,1)");

This is the zooming target:

// Container für Zooming
var cont = svg.append("g");

Then the cont is zoomed programmatically and the human interaction zoom is activated on svg:

 function applyZoom() {
        // Zoome die Fläche
    
          // .transition().duration(2000)
          // .call(zoom.translateTo, width/2, height/2);
          cont
          .transition().duration(2000)
          .tween("attr:transform", function() {
            //interpolate from start to end state
            var i = d3.interpolateString("scale(1)translate(0,0)", "scale("+scaleZoom+")translate("+(width/2)/scaleZoom+","+(height/2)/scaleZoom+")");
            return function(t) { 
              cont.attr("transform", i(t)); 
            };
          });
          
          // Call Zoom Behavior.
          svg.call(zoom);
          
        }

And finally this is the zoomed() function declared in the first line for the zoom behavior:

// Funktion die alles Zoomt. 
function zoomed() {
    // Diese Funktkion transformiert und skaliert alles gleichzeitig, welches den Effekt eines Zooms nachahmt.
var transform = d3.event.transform;

cont.attr('transform', transform.toString());

}

Get element by class list doesn’t seem to work in a for loop [duplicate]

I tried to create a for loop which loops through all buttons in an array I made – and it’s supposed to work according to: (https://www.w3schools.com/js/js_loop_for.asp)

But it does not.

I have no idea what should I do, since I haven’t found anything about that on the web.
Thank you for your time.

Here is the code

const buttons = document.getElementsByClassName('zoom-btn');

for (i = 0; i < buttons.length; i++) {
    buttons[i].onmouseover = () => {
        buttons[i].style.backgroundColor = "red";
    }
};
#article-navbar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;

    position: fixed;

    width: clamp(286px, 504px, 506px);
    height: clamp(90px, 182px, 184px);

    top: 36vw;
    left: 4vw;

    background-color: cyan;
}

.zoom-btn {
    background-color: slategray;
    color: white;

    padding: 18px 10px;
    margin-top: 12px;
    margin-left: 10px;

    font-size: 16px;

    position: relative;
}

.reset-btn {
    background-color: blue;
}

.zoom-hover {
    background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="a.css">
</head>
<body>
    <div id="article-navbar">

        <a id="button-RE" ; class="zoom-btn reset-btn">Reset</a>
        <a id="button-A1" ; class="zoom-btn">Block 1</a>
        <a id="button-A2" ; class="zoom-btn btn-deactivated">Block 2</a>
        <a id="button-A3" ; class="zoom-btn btn-deactivated">Block 3</a>
    
        <a id="button-B1" ; class="zoom-btn btn-deactivated">Block 4</a>
        <a id="button-B2" ; class="zoom-btn btn-deactivated">Block 5</a>
    
      </div>

    <script src="a.js"></script>
</body>
</html>