VueDatePcker, adding a custom button

im using @vuepic/vue-datepicker”: “^7.4.1” and I want to add a custom close button in the mobile view like this(I want to add the close button where the red square is).

enter image description here

I tried using action-row to add a button, but when I added auto-apply the action row disappeared. any idea how to do this? this is my current code

<template>
  <VueDatePicker
    v-model="dates"
    range
    :enable-time-picker="false"
    :multi-calendars="{ solo: true }"
    placeholder="Select date range"
    :max-date="new Date()"
    :auto-apply="true"
    :format="`dd MMM yyyy`"
    :preset-dates="presetDates"
    :end-year="new Date().getFullYear()"
    @internal-model-change="onchange"
  >
    <template #preset-date-range-button="{ label, value, presetDate }">
      <span
        role="button"
        :tabindex="0"
        @click="presetDate(value)"
        @keyup.enter.prevent="presetDate(value)"
        @keyup.space.prevent="presetDate(value)"
      >
        {{ label }}
      </span>
    </template>
  </VueDatePicker>

</template>

I cannot access my database using docker [Python]

I am not the most knowledgeable on the subject, my friend did the entire Docker setup. I am trying to connect to a Database using Python. This database is accessed by JavaScript, who sends information about clients to the db. However, whenever I try accessing the db through Python:

from dotenv import load_dotenv
import os
import psycopg2
import sys
import time

print(sys.path)

load_dotenv()  # Load environment variables from .env file

# Accessing environment variables
DB_NAME = os.getenv("POSTGRES_DB")
DB_USER = os.getenv("POSTGRES_USER")
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD")
DB_HOST = 'db'  # Service name defined in Docker Compose
DB_PORT = "5432"  # Port exposed by PostgreSQL container

def get_users():
    try:
        time.sleep(10)
        # Attempt to establish a database connection
        print(DB_HOST)
        print(DB_NAME)
        print(DB_PASSWORD) 
        print(DB_PORT)
        print(DB_USER)
        conn = psycopg2.connect(
            dbname=DB_NAME,
            user=DB_USER,
            password=DB_PASSWORD,
            host=DB_HOST,
            port=DB_PORT
        )
        print("Database connection successful")
        
        # Perform database operations
        try:
            with conn.cursor() as cur:
                cur.execute("SELECT * FROM users")
                users = cur.fetchall()
                return users
        except psycopg2.Error as query_error:
            print(f"Failed to query database: {query_error}")
        
        finally:
            # Close the database connection
            conn.close()

    except psycopg2.Error as connection_error:
        print(f"Database connection failed: {connection_error}")

I get Database connection failed: could not translate host name “db” to address: Name or service not known

When I try using the IP address instead of ‘db’ it works so I know that the access to my .env file is fine. Additionally, the index.js file that accesses the db does:

const dbConfig = {
  host: 'db', // the database server
  port: 5432, // the database port
  database: process.env.POSTGRES_DB, // the database name
  user: process.env.POSTGRES_USER, // the user account to connect with
  password: process.env.POSTGRES_PASSWORD, // the password of the user account
};

And it successfully connects to the db. I am unsure why it is not working. Here is also my docker-compose.yaml:

version: '3.9'
services:
  db:
    image: postgres:14
    env_file: .env
    expose:
      - '5432'
    volumes:
      - lab-09-web-services:/var/lib/postgresql/data
      - ./init_data:/docker-entrypoint-initdb.d
  web:
    image: node:lts
    user: 'node'
    working_dir: /home/node/app
    env_file: .env
    environment:
      - NODE_ENV=development
    depends_on:
      - db
    ports:
      - '3000:3000'
    volumes:
      - ./:/home/node/app
    command: 'npm start'
  python-app:
    build: .
    env_file: .env
    depends_on:
      - db
      - web
# This defines our volume(s), which will persist throughout startups.
# If you want to get rid of a hanging volume, e.g. to test your database init,
# run `docker-compose rm -v`. Note that this will remove ALL of your data, so
# be extra sure you've made a stable backup somewhere.
volumes:
  lab-09-web-services:

I have already tried adding a Dockerfile for python and a bunch of different things but everything gets me the exact same error

I have tried multiple approaches with the help of GenAI to no success. I only want to access the db and get the information I need

Webpack and Jest in a project using imports

I’m working on a Node project and using imports and exports all over the place.

I’m using Webpack to package the frontend code. So far as I can tell, it has to run as common JS.

I’m also using Jest, which forced me to set "type": "module" in package.json.

These two don’t mix well: Webpack can’t run as a module and Jest refuses to process my code as common JS. What can I do to reconcile this?

I tried other ways to run Jest with modules like modifying the test script:

"node --experimental-vm-modules --experimental-default-type=module node_modules/jest/bin/jest.js"

and naming the test files as *.mjs, but continued getting SyntaxError: Cannot use import statement outside a module.

webpack.config.js is written with require and relies on __dirname, unavailable in modules. I tried rewriting it with module syntax, but it complains about either not having a default export or not having exported a config object.

Having an asynchronous issue with my javaScript code when using a timeout with Node.js

So the purpose of the code is to import json questions and read them to the user in the terminal. The user gets 5 seconds to answer the question until the next question is displayed. The issue I am running into is that after the timer is triggered, the next question automatically times out even is the user enters an answer. Here is an example of my log:

Definition: A term used to describe a file or directory location on a drive

  1. name
  2. separator
  3. path
  4. prompt

Please answer within 5 seconds
Definition: A term used to describe a file or directory location on a drive

  1. name
  2. separator
  3. path
  4. prompt

3
Please answer within 5 seconds
Definition: A term used to describe a file or directory location on a drive

  1. name
  2. separator
  3. path
  4. prompt

3
Correct

Complete: Score – 2/2

And here is my function:

async function vocabularyDrillMode() {
    const definitions = loadJsonFile('definitions.json');
    let score = 0;
    const defBegin = definitions.length;

    async function drillTerm(currentDefinition) {
        console.log(`Definition: ${currentDefinition.definition}`);
        currentDefinition.possibleTerms.forEach((term, index) => console.log(`${index + 1}. ${term}`));

        return new Promise((resolve) => {
            const timer = setTimeout(() => {
                resolve({ success: false, term: "timeout" });
            }, 5000);

            rl.question(" > ", (userAnswer) => {
                clearTimeout(timer);

                const selectedAnswer = parseInt(userAnswer, 10) - 1;

                // Check if the user entered 'q'
                if (userAnswer.toLowerCase() === "q") {
                    resolve({ success: false, term: "q" });
                } else if (!isNaN(selectedAnswer) && selectedAnswer >= 0 && selectedAnswer <= 3) {
                    // If user entered a valid numeric answer
                    resolve({ success: selectedAnswer === currentDefinition.correctDefinition, term: selectedAnswer });
                } else {
                    // If user entered an invalid numeric answer or non-numeric input
                    resolve({ success: false, term: userAnswer });
                }
            });
        });
    }

    let quitDrill = false;

    while (definitions.length > 0 && !quitDrill) {
        const randomIndex = Math.floor(Math.random() * definitions.length);
        const currentDefinition = definitions[randomIndex];

        const result = await drillTerm(currentDefinition);

        if (result.success) {
            score++;
            definitions.splice(randomIndex, 1);
            console.log("Correctn");
        } else if (result.term === "q") {
            quitDrill = true;
        } else if (result.term === "timeout") {
            console.log("Please answer within 5 seconds");
        } else if (isNaN(result.term) || result.term > 3 || result.term < 0) {
            console.log("Please enter a number 1-4 or 'q' to quit the program");
        } else {
            console.log("Incorrect.");
        }
    }

    const statusMessage = quitDrill ? `Incomplete: User quit the drill. Score: ${score}/${defBegin}` : `Complete: Score - ${score}/${defBegin}`; console.log(`${statusMessage}`);
}

I have tried pausing and resuming the readline and I have also tried reordering the console.log of the question and terms to inside the promise and neither solved the issue

trying to change images when hovering over an icon in react

I am trying to change the src of an image while hovering over it with the mouse,
I don’t know whether I should loop over an array or if there is a simpler way to perform what I am trying to do. Currently I have an image that is regular and one that is filled with a color. So there are two images.
they are both svg files and are located in my assets/images/ folder.

what is the best way to go about changing the state of the image when hovering over it ?

import { Link } from "react-router-dom"
import { useState } from "react"

export default Navigation = () => {

    const icons = ["home", "movies", "tv-series", "bookmark"]
    const [ changeImage, setChangeImage] = useState([...icons])

    const onMouseHover = (event) => {
        setChangeImage(image => {
            image = event.target
            image = `/asseets/images/icon-nav-${}.svg`;
        })
    }

    const navIcons = icons.map(icon => (
        <Link>
            <img 
            src={`../../public/assets/images/icon-nav-${icon}.svg`}
            className="nav-icons home-icons"
            onMouseOver={onMouseHover}
            alt="home"
        />
        </Link>
    ))
    
    return (
        <div className="navigation">
           {navIcons}
        </div>
    )
}

I have tried creating a function to map over the icons and hovering over in state.
but all of the icons change. I just want the one that is hovered over. I know it has to do with event.target.src. I was thinking of creating a regexpression because the full source path is http://localhost:5173. I have created some other state of whether the image is hovered being true or false.
but it changes the fill state of all images and not just one.

How to add, subtract, multiply and divide two or more negative numbers on a Javascript calculator

I am new to Javascript and built a basic calculator. I want to add a function that allows me to input negative numbers using a toggle feature. However, when I try to use it, it only makes the first number negative. Whenever I add a symbol (i.e, +,-,*,/) and try to make the following number negative by clicking the toggle button, everything is wiped, only leaving the first number with the opposite value. Here is my HTML, CSS and JS so you can test it out for yourself:

HTML:

<!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="stylecalc.css">
</head>
<body>
    
    <div id="calculator">
        <input id="display" readonly> <!-- Cannot type anything inside inputbox-->
        <div id="keys">
            <button onclick="appendToDisplay('+')" class="operator-btn">+</button> <!--Onclick is a javascript function-->
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('-')" class="operator-btn">-</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('*')" class="operator-btn">x</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('/')" class="operator-btn">÷</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="clearDisplay()" class="operator-btn">C</button>
            <button onclick="appendToDisplay('π')" class="operator-btn">π</button>
            <button onclick="appendToDisplay('τ')" class="operator-btn">τ</button>
            <button onclick="toggleNumber('-')" class="operator-btn">+/-</button>
        </div>
    </div>

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


CSS:

body{
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh; /*makes it 100% in the center of page, viewport height = vh*/
    background-color: hsl(0, 0%, 95%);
}

#calculator{
    font-family: Arial, sans-serif;
    background-color: hsl(0, 0%, 15%);
    border-radius: 15px;
    max-width: 500px;
    overflow: hidden;
}

#display{
    width: 100%;
    padding: 20px;
    font-size: 5rem;
    text-align: left;
    border: none;
    background-color: hsl(0, 0%, 20%);
    color: white;
}

#keys{
    display: grid; /* organises everyhting in class to grid (vertical)*/
    grid-template-columns: repeat(4, 1fr); /*first number says num. of columns and other is frac. value(Space between buttons)*/
    gap: 10px;
    padding: 25px;
}

button{
    width: 100px;
    height: 100px;
    border-radius: 50px;
    border: none;
    background-color: hsl(0, 0%, 30%);
    color: coral;
    font-size: 3rem;
    font-weight: bold;
    cursor: pointer;
}

button:hover{
    background-color: hsl(0, 0%, 40%);
    color: aquamarine;
}

button:active{
    background-color: hsl(0, 0%, 50%); /*make button flash white when click for a second*/
}

.operator-btn{
    background-color: rgb(79, 56, 117);
    color: rgb(119, 183, 238);
}

.operator-btn:hover{
    background-color: rgb(111, 80, 161);
    color: rgb(255, 0, 0);
}

.operator-btn:active{
    background-color: rgb(139, 100, 201);
}

JS:

const display = document.getElementById("display");

τ = 6.2831853071
π = 3.1415926535


function appendToDisplay(input){
    display.value += input;
}

function clearDisplay(){
    display.value = "";
}

function calculate(){
    try{
        display.value = eval(display.value);
    }
    catch(error){
        display.value = "Error";
    }
}

function toggleNumber(input) {
    var currentValue = parseFloat(display.value)

    if (currentValue > 0) {
        display.value = -Math.abs(currentValue);
        currentValue += input;
    } else if (currentValue < 0) {
        display.value = Math.abs(currentValue);
        currentValue += input;
    } 
    
}

I tried to google it, but a lot of the results either wouldn’t work or would return the number as ‘undefined.’ Once again, I am new to javascript and the help would be very much appreciated 🙂

Exclude specific Enum values from JSON Schema/Swagger

I’m working with a JavaScript API defined using JSON Schema. The API has an enum field with the following values.

enum: ['apple', 'banana', 'grape', 'tester'].

The schema also describes the swagger. I want to hide the value tester from Swagger but display the other values.
Similar to this question in C# Exclude specific Enum values from Swagger

Is there a way to achieve this in JavaScript?

Posting part of an API in a certain area [duplicate]

I have it so in the console it posts:

{
  success: true, 
  base: "XAU", 
  timestamp: 1708387199, 
  rates: {
    USD: 2019.6397851265
  }
}

But I have no clue how to fetch the ‘2019.6397851265’ part, round it 2019.64, and post it in a specific area.
My code to fetch for the api is:

var settings = {
  "url": "https://api.metalpriceapi.com/v1/latest?api_key=[INSERT_KEY_HERE]&base=XAU&currencies=USD",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});

Everything I tried kept either doing nothing or giving me errors.

The reason why AJAX response is not logging in the browser

Firstly, this is a project utilizing JSP and involves POSTing with AJAX.
Specifically, the options I used for AJAX are as follows:

type: 'POST', contentType: 'application/json', async: false, dataType: 'json',

The issue arises when attempting to POST via AJAX, as the response isn’t enter code herelogged in the browser, and the following message is displayed:

Failed to load response data: No resource with given identifier found

What could be the reason for this?

Just for reference, when I console.log the response within the success callback of AJAX, the response is properly logged in the console window.

i ave given this property to my body for a modal that opens up which is named showRenderModal

useEffect(() => {document.body.style.overflow = showRenderModal ? "hidden" : "visible";}, [showRenderModal]);

but on iphone safari and sometimes on gogle chrome its still scrolling behind the modal,
plz help

i tried playing with other property no luck your textfor now, i am also setting dom overflow to visible somewhere inside the div also maybe that is causing the issue, let me know what property can be applied that it works for all browsers and devices and stays non scrollable

TypeError: variable.hasAttribute is not a function… Conway’s Game of Life, issues with determining surrounding alive cells

I’m back… So, I’m trying to recreate Conway’s Game of Life, using js, html, and css. I’m having issues with the js part, specifically with the method .hasAttribute, from my understanding, it returns a Boolean value, depending on if the element it’s targeting has a certain attribute; in my case, I want to target all the cells surrounding the main cell (the center one) who have the class “badMario”.

First, I want to clarify that my code for this game interpretation is sub-optimal, however I really just want to finish it now, and I’ll appreciate any kind of feedback and I would also like it if this feedback was chill; in any case, thanks.

Secondly, I’ll explain how the code (in theory) should function, specifically a little html and a lot js.

HTML: The HTML part is basically some instructions and an empty table without rows nor columns.

Javascript: The Javascript code is somewhat complicated, and again, it’s probably sub-optimal, but that’s how I would like to remain per se.

So first it makes the rows of the table, and 20 tds per row with unique ids. Then it assigns them all the “goodMario” class and when you hit the button “iniciar conflicto bélico” it should do the following:

  1. Assign the class “badMario” on a coin toss for each cell.
  2. Check how many cells surrounding the priority cell (center one) exist, starting on cell 1 (or cell 0 in this case).
  3. Check how many cells surrounding the priority cell that exist, have the “badMario” class.
  4. Add 1 to the incremental variable that counts how many cells have the “badMario” class.
  5. Depending on the value of the incremental variable it will:
    a. With 2 or 3 alive cells: Keep the center cell alive.
    b. With 4 cells: Make a dead cell alive.
    c. With more than 4 cells: Kill the alive cell (due to overpopulation)
  6. Repeat.

Now, the part that is confusing to me is basically any part that uses the js method .hasAttribute that for some reason is understanding as a function of sorts. For example, there’s the following code block:

                if(campo1 == null){
                    console.log("feo1");
                }
                else
                console.log(campo1.hasAttribute("class"));

So, from line 157 to 203 or so, it’s purely for understanding how it’s interpreting the cells and what not, it’s not fundamental to the functioning of the game. What I intend for it to do here is to put in the console whether the space 1 (“campo1”) was detected in the first place (if not, then write “feo1”), and if so to check if it has the class “badMario” (I only put class there to try and learn the syntax, but to be honest I have no idea how to use it). And that’s pretty much my issue, I do believe that the logic with the surrounding cells is good enough for it to work, but if it isn’t I’ll manage to fix it eventually; but yeah, this issue with .hasAttribute has been rough and has me certainly dumbfounded.

here’s a codepen link to the whole code: https://codepen.io/Lucky737V/pen/rNRbVGv

Again, any help would be appreciated. In case of needing any translations from the code to English (referring to the Spanish segments and names)

Strange DevTools behaviour – two variables with the same name and different values

I have a code from below screenshot and as you can see, there are two selectableTarget local variables and actually the “wrong” one is used by the code… More specifically, selectable target should be target dom (or its parent) with data-copyable attribute. What is interesting, when I sebug step by step, on hover the selectable target is undefined while on right hand tab its not. I don’t get it, what am I doing wrong?

enter image description here