ViTest Mock is not replacing function

For some reason in ViTest mocks are not replacing my real function. I have a main function here

const { handler1 } = require(./path/handler1)

exports.mainFunction = async (event) => {
 try {
    const val1 = await handler1(event)
    console.log(val1)

Handler 1 looks like

exports.handler1 = async (data) => { return "real" }

I am trying to write unit tests for mainFunction where I can mock the response from handler1 (Handler1 already has its own unit tests)

import { handler1} from '../path/handler1.js';
vi.mock('../path/handler1.js');

describe('mainFunction()', function () {
  it("should return fake")  async function () {
    let handlerMock = {
      handler1: () => "Fake",
    };
    handler1.mockResolvedValue(handlerMock);
    await mainFunction("event")
    // mainFunction is outputting real and not fake

  }
}

How to fix vscode replacing words on the right

How to disable vsocde replacing a word next to the right when I hit enter.

A code for example: doSomething(), if go to the back of that function and type functionName and hit enter it replaces the doSomething to functionName().

I’ve tried the insertMode but it’s already in insert by default. I’ve also tried other stuff but nothing works. I need the suggestions when typing but I don’t want it to replace next word, thanks. Sorry for my English.

Swiper component won’t center the slide if freeMode is activated

I have a swiper that contains multiple slides (they don’t fit entirely on screen). I need the Swiper to have freeMode set to true so that on mobile the slides keep scrolling after touchEnd.
My problem is that even by using “sticky: true” inside freeMode{} the swiper won’t center the nearest slide to the center of the screen after the swiper stopped moving.

This is the code

 <Swiper
        slidesPerView={5}
        centeredSlides={true}
        // onSlideChangeTransitionEnd={onSlideChange}
        modules={[Navigation, Pagination, Scrollbar, A11y]}
        spaceBetween={0}
        navigation
        pagination={{ clickable: true }}
        scrollbar={{ draggable: true }}
        className={styles.swiper}
        touchRatio={1.5}
        longSwipes={true}
        grabCursor={true}
        cssMode={true}
        slideActiveClass={styles.selectedSlide}
        freeMode={{
          enabled: true,
          momentumBounce: true,
          sticky: true,
        }}
      >
        {slides}
      </Swiper>

(Three.js) How do I get the eyes to correctly follow the mouse?

I’m new to using Three.js. I want to create eye balls that follow the mouse, I managed to make them move but they don’t follow the mouse perfectly

threeJS mouse follow issue

Here is the part of the code that controls the eyes

class Eyes extends THREE.Group {
  constructor(camera) {
    super();
    this.camera = camera;

    this.plane = new THREE.Plane();
    this.planeNormal = new THREE.Vector3();
    this.planePoint = new THREE.Vector3();

    this.pointer = new THREE.Vector2();
    this.raycaster = new THREE.Raycaster();

    this.lookAt = new THREE.Vector3();

    this.clock = new THREE.Clock();

    this.blink = { value: 0 };

    this.eyes = new Array(2).fill().map((_, idx) => {
      let eye = new EyeBall();
      eye.position.set(idx < 1 ? -0.15 : 0.15, 0.025, 0.9);
      eye.scale.setScalar(0.13);
      this.add(eye);
      return eye;
    });

    document.addEventListener("pointermove", (event) => {
      this.pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
      this.pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
    });

    this.blinking();
  }

  blinking() {
    let duration = 500;
    let delay = Math.random() * 3000 + 2000;
    this.blink.value = 0;
    new TWEEN.Tween(this.blink)
      .to({ value: 1 }, duration)
      .delay(delay)
      .easing(TWEEN.Easing.Exponential.InOut)
      .onComplete(() => {
        this.blinking();
      })
      .start();
  }

  update() {
    this.raycaster.setFromCamera(this.pointer, this.camera);
    this.camera.getWorldDirection(this.planeNormal);

    const eyeWorldPosition = new THREE.Vector3();
    this.eyes[0].getWorldPosition(eyeWorldPosition);

    this.plane.setFromNormalAndCoplanarPoint(
      this.planeNormal,
      eyeWorldPosition
    );

    let tempLookAt = new THREE.Vector3();
    this.raycaster.ray.intersectPlane(this.plane, tempLookAt);
    this.lookAt.lerp(tempLookAt, 0.5);

    this.eyes.forEach((eye) => {
      eye.lookAt(this.lookAt);
    });
  }
}

I’ve tried looking up some solutions but a lot of them use regular html and js and not vite with reactJS. Also they never have the same issue I’m having.

Tools I’m using:
Vite
ReactJS
Javascript
Three.js

cookie related issue in MERN stack web app deployed on Render

I am having an issue about cookies in my mern stack project I use passport local strategy for auth and express-session for session storage and database is deployed on mongodb atlas, actually everything works correctly on the laptop but in incognito mode once I login and go to any protected route it says not authenticated and no cookie is set in application tab and in mobile phone some account works properly like I am able to login and other other operation also but I am not able to login on some accounts, so this is my problem for code base this is public GitHub Repo : https://github.com/Nikhil-Sirsat/LinkSpace

Webpack – Creating files in a sibling directory

I’m in a situation where I want to create “dist” files along a dynamic path but in a specific child directory, which is a sibling to the source directory.

My project structure ideally looks like this:

  • files/
    • directory1/
      • src/
        • index.js
      • dist/
        • index-dist.js
    • directory2/
      • src/
        • index.js
      • dist/
        • index-dist.js

What I have so far in my webpack config:

const path = require( 'path' );
const glob = require('glob');

module.exports = ( env ) => {
    return {
        entry: Object.fromEntries(glob.sync(path.resolve(__dirname, 'files/**/src/index.js')).map((v) => [ v.split('files/')[1], v, ] )),
        resolve: {
            extensions: [
                '.js',
            ],
        },
        output: {
            path: path.resolve( __dirname, 'files' ),
            filename: '[name]-dist.js',
        },
    }
};

However, this is producing:

  • files/
    • directory1/
      • src/
        • index.js <- this is my entry point
        • index.js-dist.js <- this is the output
    • directory2/
      • src/
        • index.js <- this is my entry point
        • index.js-dist.js <- this is the output

I saw there was something with [path] that could theoretically be used, but it just created a folder called “[path]” when I tried that.

Implementing a confirmation dialog for closing a risk based on its impact status Colum: APEX ORACLE

I’m working on an Oracle APEX application where I need to implement a confirmation dialog when closing a risk. The process should work as follows:

When the user clicks the “Close Risk” button, I want to check if the risk has a “High” impact status in the RMA_USER_EVALUATIONS table in the column IMPACT_ACTUAL where there’s a coincidence between P2_ID and the ID_RISK Column value.

If the impact is “High”, I want to show an error message saying “Cannot close this risk because it has a High impact value. The countermeasures were not successful.”
If the impact is not “High”, I want to show a confirmation dialog asking “Are you sure you want to close this risk?”

If the user confirms, I want to proceed with closing the risk (which involves updating a status in the database).

I’m using a Dynamic Action on the “Close Risk” button, with a PL/SQL action to check the risk status, and JavaScript to handle the server response and show the appropriate messages.

However, I’m encountering the following issues:

I’m getting a “parsererror” when trying to parse the JSON response from the server.
The P2_ID item (which contains the risk ID) seems to be undefined when the JavaScript code runs.
Here’s my current PL/SQL code:

DECLARE
  l_count NUMBER;
  l_message VARCHAR2(4000);
BEGIN
  apex_json.open_object;
  
  BEGIN
    SELECT COUNT(*)
    INTO l_count
    FROM RMA_USER_EVALUATIONS
    WHERE ID_RISK = :P2_ID
      AND (IMPACT_ACTUAL = 'High' OR IMPACT_FORECAST = 'High');

    IF l_count > 0 THEN
      l_message := 'Cannot close this risk because it has a High impact value. The countermeasures were not successful.';
      apex_json.write('status', 'ERROR');
    ELSE
      l_message := 'Risk can be closed.';
      apex_json.write('status', 'SUCCESS');
    END IF;

    apex_json.write('message', l_message);
  EXCEPTION
    WHEN OTHERS THEN
      apex_json.write('status', 'ERROR');
      apex_json.write('message', 'An unexpected error occurred: ' || SQLERRM);
  END;
  
  apex_json.close_object;
END;

And here’s my JavaScript code:

console.log('P2_ID value:', $v('P2_ID'));
    
    apex.server.process(
     
    
         'CLOSE_RISK',
          {x01: $v('P2_ID')},
          {
            dataType: 'json',
            success: function(data) {
              console.log('Server response:', data);
              if (data.status === 'ERROR') {
                apex.message.showErrors({
                  type: 'error',
                  location: 'page',
                  message: data.message
                });
              } else if (data.status === 'SUCCESS') {
                apex.message.confirm("Are you sure you want to close this risk?", function(okPressed) {
                  if (okPressed) {
                  
                    console.log('Closing risk...');
                    apex.message.showPageSuccess('Risk closed successfully');
                    
                  }
                });
              } else {
                apex.message.showErrors({
                  type: 'error',
                  location: 'page',
                  message: 'Unexpected response from server.'
                });
              }
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.error('AJAX error:', textStatus, errorThrown);
              apex.message.showErrors({
                type: 'error',
                location: 'page',
                message: 'An error occurred while processing your request: ' + textStatus
              });
            }
          }
        );

And to identify a Risk as closed I have this process PL/SQL

BEGIN
    UPDATE RMA_RISK_INCIDENTS
    SET IS_CLOSED = 'Y'
    WHERE ID = :P2_ID;
END;

Can anyone help me identify what I’m doing wrong and how to correctly implement this functionality in APEX?

Compare multidimensional arrays from diferent files. Automatically send results to AI generated image [closed]

I have an html questionnaire with 6 questions and each question can be answered with 1, 2 or 3.

I have a file gv18.js (in javascript with 18 multidimensional arrays divided into 6 senses, with 3 sensations for each).

I have a file w100.js (in javascript with 100 multidimensional arrays and each one has a name corresponding to a word).

I want to implement an algorithm as follows:
If the user chooses the radio button “1” in the questionnaire at question I, all sub-arrays from multidimensional arrays COLD from gv18.js; If the user chooses the radio button “2” in the questionnaire at question I, all sub-arrays from multidimensional arrays MTO (from mixed touch) from gv18.js are kept. If the user chooses the radio button “3” in the questionnaire at question I, all sub-arrays from multidimensional arrays HOT from gv18.js are kept. The logic follows for all questions.

All files are at: https://mindgraphy.eu/SYS10. Respectively gv18.js and w100.js

Compare the resulting multidimensional array that will be kept with all arrays in w100.js. Find the 5 names of the closest arrays.

I want these 5 names of the closest arrays to be sent to: https://deepai.org/ with the request to generate an image. For this I press the FIND button.

When I press another SHOW button on the html page, the image appears.

how to make the render on vue2 equals to the render on vue3

I have the same code, but if I run it on vue2/vuetify2 the render will be:

enter image description here

If I run it on vue3/vuetify3 I get:

enter image description here

The color is not black anymore, “informativa privacy” is red and the “Entra nel sito libero” is blue, and the icon are different too;

this is my code:

<template>
    <v-container>
      <v-row>
        <v-col>
          <v-flex>
            <v-card>
              <v-card-title  >
                <div>Informazioni</div>
              </v-card-title>
              <v-card-text>
                <li>
                  <router-link  
                     :to="'/privacy_information'"
                    >Informativa Privacy</router-link
                  >
                </li>
                <li>
                  <a href="https://www.libero.it/" target="_blank"
                    >Entra nel sito libero</a
                  >
                </li>
              </v-card-text>
            </v-card>
          </v-flex>
        </v-col>
        <v-col offset="4">
          <v-flex >
            <v-card >
              <v-card-title>
                <div>Seguici su</div>
              </v-card-title>
              <v-card-text>
                <v-btn
                  href="https://twitter.com/liberoGroupIT"
                  target="_blank"
                  class="ma-2"
                  tile
                  large
                  color="#1DA1F2"
                  icon
                >
                  <v-icon >mdi-twitter</v-icon>
                </v-btn>
                <v-btn
                  href="https://www.linkedin.com/company/libero-italia"
                  target="_blank"
                  class="ma-2"
                  tile
                  large
                  color="#2867B2"
                  icon
                >
                  <v-icon large>mdi-linkedin</v-icon>
                </v-btn>
                <v-btn
                  href="https://www.facebook.com/liberoGroup/"
                  target="_blank"
                  class="ma-2"
                  tile
                  large
                  color="#3C5A99"
                  icon
                >
                  <v-icon large>mdi-facebook</v-icon>
                </v-btn>
              </v-card-text>
            </v-card>
          </v-flex>
        </v-col>
      </v-row>
    </v-container>

</template>

I’ve tried to add almost any class, try to set color as in

<router-link 
                    color="black"
                     :to="'/privacy_information'"
                    >Informativa Privacy</router-link
                  >

but nothing will change, and no idea how to go futher!!! the icon are the same, no css is specified.

How I can render the color black in vue3 and How I can rendere the icon in the same way (with background trasparent)

Choices are not shown i modal – Django

I have a modal used for adding a new record to the database. However the choices are not being rendered in the choice fields.

The modal:

{% load crispy_forms_tags %}



<li class="nav-item">
  <a class="nav-link active text-white ms-2" data-bs-toggle="modal" data-bs-target="#add_recordModal">Tilføj sag</a>
</li>

<div class="modal fade" id="add_recordModal" tabindex="-1" aria-labelledby="add_recordModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form method="post" action="{% url 'add_record' %}">
        {% csrf_token %}
        <div class="modal-header">
          <h5 class="modal-title" id="add_recordModalLabel">Tilføj sag</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body" style="margin-left:1.5%">
          <form method="POST" action="{% url 'add_record' %}" id="addRecordForm">
            <h6 style="color: black;"><strong>Standardoplysninger</strong></h6>
            <br>
            <div class="row">
                <div class="col-md-6">
                  <label for="id_BFE_Nummer" style="color:black; font-size: 14px;">BFE Nummer*</label>
                  <input type="number" id="id_BFE_Nummer" name="BFE_Nummer" value="{{ customer_record.BFE_Nummer }}" placeholder="BFE Nummer" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Adresse" style="color:black; font-size: 14px;">Adresse</label>
                  <input type="text" id="id_Adresse" name="Adresse" value="{{ customer_record.Adresse }}" placeholder="Adresse" class="form-control">
                  <br>
                </div>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Mail" style="color:black; font-size: 14px;">By</label>
                  <input type="text" id="id_By" name="By" value="{{ customer_record.By}}" placeholder="By" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Kommune" style="color:black; font-size: 14px;">Kommune</label>
                  <input type="text" id="id_Kommune" name="Kommune" value="{{ customer_record.Kommune}}" placeholder="Kommune" class="form-control">
                  <br>
                </div>                
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Postnummer" style="color:black; font-size: 14px;">Postnummer</label>
                  <input type="text" id="id_Postnummer" name="Postnummer" value="{{ customer_record.Postnummer}}" placeholder="Postnummer" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Region" style="color:black; font-size: 14px;">Region</label>
                  <input type="text" id="id_Region" name="Region" value="{{ customer_record.Region}}" placeholder="Region" class="form-control">
                  <br>
                </div>                
              </div>

              <h6 style="color: black;"><strong>Kontaktinfo</strong></h6>
              <br>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Kontaktperson" style="color:black; font-size: 14px;">Kontaktperson*</label>
                  <input type="text" id="id_Kontaktperson" name="Kontaktperson" value="{{ customer_record.Kontaktperson }}" placeholder="Kontaktperson" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Mail" style="color:black; font-size: 14px;">Mail*</label>
                  <input type="text" id="id_Mail" name="Mail" value="{{ customer_record.Mail }}" placeholder="Mail" class="form-control">
                  <br>
                </div>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Telefonnummer" style="color:black; font-size: 14px;">Telefonnummer</label>
                  <input type="text" id="id_Telefonnummer" name="Telefonnummer" value="{{ customer_record.Telefonnummer }}" placeholder="Telefonnummer" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Resights" style="color:black; font-size: 14px;">Resights</label>
                  <input type="text" id="id_Resights" name="Resights" value="{{ customer_record.Resights }}" placeholder="Resights" class="form-control">
                  <br>
                </div>
              </div>
              <h6 style="color: black;"><strong>Sagsoplysninger</strong></h6>
                <br>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Status" style="color:black; font-size: 14px;">Status*</label>
                  <select id="id_Status" name="Status" class="form-control">
                      {% for choice in customer_record.Typen %}
                          <option value="{{ choice.0 }}" {% if customer.Status == choice.0 %}selected{% endif %}>{{ choice.1 }}</option>
                      {% endfor %}
                  </select>
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Lead" style="color:black; font-size: 14px;">Lead*</label>
                  <select id="id_Lead" name="Lead" class="form-control">
                      {% for choice in add_record.Ansvarlig %}
                          <option value="{{ choice.0 }}" {% if add_record.Lead == choice.0 %}selected{% endif %}>{{ choice.1 }}</option>
                      {% endfor %}
                  </select>
                  <br>
                </div>
              </div>
            <div class="row">
              <div class="col-md-6">
                  <div id="opfolgningsdato-input-wrapper">
                    <label for="id_Opfølgningsdato" style="color:black; font-size: 14px;">Opfølgningsdato</label>
                    <input type="date" id="id_Opfølgningsdato" name="Opfølgningsdato" value="{{ customer_record.Opfølgningsdato|date:'Y-m-d' }}" placeholder="Opfølgningsdato" class="form-control">
                    <br>
                  </div>
                </div>
                <div class="col-md-6">
                  <div id="lukket-aftale-status-wrapper">
                    <label for="id_Lukket_aftale_Status" style="color:black; font-size: 14px;">Status på aftale</label>
                    <select id="id_Lukket_aftale_Status" name="Lukket_aftale_Status" class="form-control">
                      {% for choice in customer_record.Aftale %}
                      <option value="{{ choice.0 }}" {% if record.Lukket_aftale_Status == choice.0 %}selected{% endif %}>{{ choice.1 }}</option>
                      {% endfor %}
                    </select>
                    <br>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <div id="opfolgningsdato-input-wrapper">
                    <label for="id_Opfølgningsdato" style="color:black; font-size: 14px;">Opfølgningsdato</label>
                    <input type="date" id="id_Opfølgningsdato" name="Opfølgningsdato" value="{{ customer_record.Opfølgningsdato|date:'Y-m-d' }}" placeholder="Opfølgningsdato" class="form-control">
                  </div>
                </div>
                <div class="col-md-6">
                  <div id="moedestatus-wrapper">
                    <label for="id_Moedestatus" style="color:black; font-size: 14px;">Mødestatus</label>
                    <select id="id_Moedestatus" name="Moedestatus" class="form-control">
                      {% for choice in customer_record.Mstatus %}
                      <option value="{{ choice.0 }}" {% if customer_record.Moedestatus == choice.0 %}selected{% endif %}>{{ choice.1 }}</option>
                      {% endfor %}
                    </select>
                    <br>
                  </div>
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Kommuneplan" style="color:black; font-size: 14px;">Kommuneplan</label>
                  <input type="text" id="id_Kommuneplan" name="Kommuneplan" value="{{ customer_record.Kommuneplan }}" placeholder="Kommuneplan" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Lokalplan" style="color:black; font-size: 14px;">Lokalplan</label>
                  <input type="text" id="id_Lokalplan" name="Lokalplan" value="{{ customer_record.Lokalplan}}" placeholder="Lokalplan" class="form-control">
                  <br>
                </div>
              </div>
              <div class="row">
              </div>
              <div class="row">
                <div class="col-md-6">
                  <label for="id_Formaal" style="color:black; font-size: 14px;">Formål</label>
                  <input type="text" id="id_Formaal" name="Formaal" value="{{ customer_record.Formaal}}"  placeholder="Formål" class="form-control">
                  <br>
                </div>
                <div class="col-md-6">
                  <label for="id_Salgssum" style="color:black; font-size: 14px;">Salgssum</label>
                  <input type="number" id="id_Salgssum" name="Salgssum" value="{{ customer_record.Salgssum}}" placeholder="Salgssum" class="form-control">
                  <br>
                </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuller</button>
          <button type="submit" class="btn btn-secondary">Tilføj sag</button>
        </div>
      </form>
    </div>
  </div>
</div>

Script:

<script>
  $(function() {
  $.datepicker.setDefaults($.datepicker.regional['da']);
  $('.datepicker').datepicker({
    dateFormat: 'yy-mm-dd'
  });
  $( "#id_Forfaldsdato" ).datepicker({
    dateFormat: 'yy-mm-dd',
    monthNames: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December'],
    monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'],
    dayNamesMin: ['Sø', 'Ma', 'Ti', 'On', 'To', 'Fr', 'Lø'],
    changeYear: true,
    changeMonth: true
  });
  });
</script>
<script>
  $(function() {
  $.datepicker.setDefaults($.datepicker.regional['da']);
  $('.datepicker').datepicker({
    dateFormat: 'yy-mm-dd'
  });
  $( "#id_Opfølgningsdato" ).datepicker({
    dateFormat: 'yy-mm-dd',
    monthNames: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December'],
    monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'],
    dayNamesMin: ['Sø', 'Ma', 'Ti', 'On', 'To', 'Fr', 'Lø'],
    changeYear: true,
    changeMonth: true
  });
  });
</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Get the date input field
    const dateInput = document.querySelector('input[name="Forfaldsdato"]');
    const statusSelect = document.getElementById('id_Status');
    const lostStatusWrapper = document.getElementById('lost-status-wrapper');
    const lukketAftaleStatusWrapper = document.getElementById('lukket-aftale-status-wrapper');
    const moedestatusWrapper = document.getElementById('moedestatus-wrapper');
    const forfaldsdatoInput = document.getElementById('forfaldsdato-input-wrapper');
    const opfolgningsdatoInput = document.getElementById('opfolgningsdato-input-wrapper');
    const m2Input = document.getElementById('id_m2');
    const bebyggelsesprocentInput = document.getElementById('id_Bebyggelsesprocent');
    const arealBm2Input = document.getElementById('id_areal_bm2');
    const byggemeterprisInput = document.getElementById('id_Byggemeterpris');
    const salgssumInput = document.getElementById('id_Salgssum');

    // Form submission validation
    document.querySelector('form').addEventListener('submit', function(event) {
        if (!/^d{2}-d{2}-d{4}$/.test(dateInput.value)) {
            alert('Datoformat skal være yyyy-mm-dd');
            event.preventDefault();
        }
    });

    // Date input blur event
    dateInput.addEventListener('blur', function() {
        if (!/^d{2}-d{2}-d{4}$/.test(dateInput.value)) {
            dateInput.setCustomValidity('Datoformat skal være yyyy-mm-dd');
        } else {
            dateInput.setCustomValidity('');
        }
    });

    // Status change event
    statusSelect.addEventListener('change', function() {
        if (this.value === 'Lukket aftale') {
            lukketAftaleStatusWrapper.style.display = 'block';
            moedestatusWrapper.style.display = 'none';
            forfaldsdatoInput.style.display = 'block';
            opfolgningsdatoInput.style.display = 'none';
            lostStatusWrapper.style.display = 'none';
        } else if (this.value === 'Møde booket') {
            lukketAftaleStatusWrapper.style.display = 'none';
            moedestatusWrapper.style.display = 'block';
            forfaldsdatoInput.style.display = 'none';
            opfolgningsdatoInput.style.display = 'block';
            lostStatusWrapper.style.display = 'none';
        } else {
            lukketAftaleStatusWrapper.style.display = 'none';
            moedestatusWrapper.style.display = 'none';
            forfaldsdatoInput.style.display = 'none';
            opfolgningsdatoInput.style.display = 'block';
            lostStatusWrapper.style.display = 'block';
        }
    });
    statusSelect.dispatchEvent(new Event('change'));

    // Calculate Areal BM2
    m2Input.addEventListener('input', calculateArealBm2);
    bebyggelsesprocentInput.addEventListener('input', calculateArealBm2);

    function calculateArealBm2() {
        if (m2Input.value && bebyggelsesprocentInput.value) {
            const m2 = parseFloat(m2Input.value);
            const bebyggelsesprocent = parseFloat(bebyggelsesprocentInput.value);
            const arealBm2 = m2 * (bebyggelsesprocent / 100);
            arealBm2Input.value = arealBm2.toFixed(0);
        } else {
            arealBm2Input.value = 0.2 * (m2Input.value || 0);
        }
    }

    // Limit Bebyggelsesprocent to 100
    bebyggelsesprocentInput.addEventListener('input', function() {
        if (this.value > 100) {
            this.value = 100;
        }
    });

    // Calculate Salgssum
    byggemeterprisInput.addEventListener('input', calculateSalgssum);
    salgssumInput.addEventListener('input', calculateSalgssum);
    arealBm2Input.addEventListener('input', calculateSalgssum);

    function calculateSalgssum() {
        if (arealBm2Input.value && byggemeterprisInput.value) {
            const arealBm2 = parseFloat(arealBm2Input.value);
            const byggemeterpris = parseFloat(byggemeterprisInput.value);
            const salgssum = arealBm2 * byggemeterpris;
            salgssumInput.value = salgssum.toFixed(0);
        } else {
            salgssumInput.value = 0;
        }
    }
});
</script>

View:

def add_record(request):
    if not request.user.is_authenticated:
        messages.error(request, "Du skal være logget ind for at se siden")
        return redirect('home')
    if not request.user.is_staff:
        messages.error(request, "Du har ikke rettigheder til dette område")
        return redirect('home')

    form = AddRecordForms(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            bfe_nummer = form.cleaned_data['BFE_Nummer']
            if not Record.objects.filter(BFE_Nummer=bfe_nummer).exists():
                add_record = form.save()
                messages.success(request, "Registrering er tilføjet...")
                return redirect('Record', pk=add_record.pk)
            else:
                messages.error(request, "Registreringen findes allerede...")
                return render(request, 'add_record.html', {'form':form})
    return render(request, 'add_record.html', {'form':form})

I’ve tried changing the view, how i render it and the naming of the model in the modal. Nothing seems to work. Also tried running it through AI, and that did nothing

Playwright Anchor Element click fails but Press Enter works

I have following anchor Element on the page for which I am writing Playwright Tests

 <a _ngcontent-ng-c643490139="" mat-menu-item="" tabindex="0" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted" href="/event-partner" role="menuitem" aria-disabled="false" style="">
<span class="mat-mdc-menu-item-text"><span _ngcontent-ng-c643490139="">Eventpartner</span></span><div matripple="" class="mat-ripple mat-mdc-menu-ripple"></div>
<!---->
</a>

Its an anchor Tag with a role of menuitem. Accessing it via following locator should work:

//Open the Menu whose name is Daten
await page.locator('a').filter({ hasText: 'Daten' }).click();

await page.getByRole('menuitem', { name: 'Eventpartner' }).click();

But I get the following error in my Test:

Error: locator.click: Test timeout of 30000ms exceeded.

Call log:

  • waiting for getByRole(‘menuitem’, { name: ‘Eventpartner’ })
    • locator resolved to …
  • attempting click action
    2 × waiting for element to be visible, enabled and stable

    • element is visible, enabled and stable
    • scrolling into view if needed
    • done scrolling
    • … from … subtree intercepts pointer events
    • retrying click action
    • waiting 20ms
    • waiting for element to be visible, enabled and stable
  • element was detached from the DOM, retrying

How can I fix this issue?

The website here removes the Element referred to by locator resolved to in the above error message.

<a tabindex="0" role="menuitem" mat-menu-item="" href="/event-partner" aria-disabled="false" _ngcontent-ng-c2888663785="" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted">…</a>

Following does work,but not always, say 8 out of 10 times.

 await page.locator('a').filter({ hasText: 'Daten' }).click();


await page.getByRole('menuitem', { name: 'Eventpartner' }).press('Enter');

How can I solve this issue?

Next.js 15 – need to click on cancel twice in Modal

Hi i have problem with my Next.js app specifically on frontend. I have user management and when i click Add user it will open Modal windows but after that when i focus Password button it will show password requirements and if im focused on password inputbox i need to click Cancel button twice. Because first click will remove showing password requirements and second one click will close the modal the window and i would like to close it on first click.

This is the code for the modal:

const [showPasswordRequirements, setShowPasswordRequirements] = useState(false);
const handlePasswordFocus = () => {
   setShowPasswordRequirements(true);
 };

 const handlePasswordBlur = () => {
   setShowPasswordRequirements(false);
 };
const handleCancelAddUser = (e) => {
   setPasswordStrength({
       score: 0,
       feedback: "",
       color: "gray",
       requirements: {
           length: false,
           uppercase: false,
           lowercase: false,
           number: false,
           special: false,
       },
   });

   setNewUser({ name: "", email: "", password: "", confirmPassword: "", role: "Read-only" });
   setEmailError("");
   setBackendError(null);
   setFieldErrors({});
   setShowPasswordRequirements(false);
   setIsAddingUser(false);
};

useEffect(() => {
   if (isAddingUser || isEditingUser) {
     if (nameInputRef.current) {
       nameInputRef.current.focus();
     }
   }
 }, [isAddingUser, isEditingUser]);

{isAddingUser && (
       <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center">
         <div className="bg-white dark:bg-slate-700 p-6 rounded-lg w-full max-w-md">
           <h2 className="text-lg font-medium mb-4 text-slate-800 dark:text-white">Add New User</h2>
           {fieldErrors.general && <p className="text-red-500 mb-2">{fieldErrors.general}</p>}
           <div className="mb-4">
             <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
               Name:
             </label>
             <input
               type="text"
               name="name"
               value={newUser.name}
               onChange={handleNewUserChange}
               placeholder="Name"
               ref={nameInputRef} 
               className="mt-1 block w-full border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-slate-800 dark:text-slate-200"
             />
           </div>
               <div className="mb-4">
                 <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                   Email:
                 </label>
                 <input
                   type="email"
                   name="email"
                   value={newUser.email}
                   onChange={handleNewUserChange}
                   placeholder="Email"
                   className="mt-1 block w-full border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-slate-800 dark:text-slate-200"
                 />
                 {emailError && <p className="text-red-500 mt-1">{emailError}</p>}
               </div>
               <div className="mb-4">
                 <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                   Password:
                 </label>
                 <input
                   type="password"
                   name="password"
                   value={newUser.password}
                   onChange={handleNewUserChange}
                   placeholder="Password"
                   className="mt-1 block w-full border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-slate-800 dark:text-slate-200"
                   onFocus={handlePasswordFocus}
                   onBlur={handlePasswordBlur}
                   ref={passwordInputRef}
                 />
                 {showPasswordRequirements && (
                   <div className="mt-2">
                     <div className={`h-2 rounded-full ${passwordStrength.color === "green" ? "bg-green-500" : passwordStrength.color === "orange" ? "bg-orange-500" : "bg-red-500"} w-${passwordStrength.score * 20}/100`}></div>
                     <p className="text-xs mt-1">{passwordStrength.feedback}</p>
                     <ul className="list-disc list-inside text-xs mt-2">
                       <li className={passwordStrength.requirements.length ? "text-green-500" : "text-red-500"}>At least 8 characters</li>
                       <li className={passwordStrength.requirements.uppercase ? "text-green-500" : "text-red-500"}>Uppercase letter</li>
                       <li className={passwordStrength.requirements.lowercase ? "text-green-500" : "text-red-500"}>Lowercase letter</li>
                       <li className={passwordStrength.requirements.number ? "text-green-500" : "text-red-500"}>Number</li>
                       <li className={passwordStrength.requirements.special ? "text-green-500" : "text-red-500"}>Special character</li>
                     </ul>
                   </div>
                 )}
               </div>
               <div className="mb-4">
                       <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
                           Confirm Password:
                       </label>
                       <input
                           type="password"
                           name="confirmPassword"
                           value={newUser.confirmPassword}
                           onChange={handleNewUserChange}
                           placeholder="Confirm Password"
                           className="mt-1 block w-full border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-slate-800 dark:text-slate-200"
                       />
                       {fieldErrors.confirmPassword && <p className="text-red-500 mt-1">{fieldErrors.confirmPassword}</p>}
                   </div>
           <div className="mb-4">
             <label className="block text-sm font-medium text-slate-700 dark:text-slate-300">
               Role:
             </label>
             <select
               name="role"value={newUser.role}
               onChange={handleNewUserChange}
               className="mt-1 block w-full border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-slate-800 dark:text-slate-200"
               >
               <option value="Admin">Admin</option>
               <option value="Read-only">Read-only</option>
               </select>
               </div>
               <div className="flex justify-end">
               <button
               onClick={handleAddNewUser}
               className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded mr-2"
               >
               Add
               </button>
               <button
                   onClick={handleCancelAddUser}
              className="text-slate-500 hover:text-slate-600 px-4 py-2 rounded"
               >
               Cancel
               </button>
               </div>
               {backendError && <p className="text-red-500 mt-2">Error: {backendError}</p>}
               {error && <p className="text-red-500 mt-2">Error: {error}</p>}
               </div>
               </div>
               )}
   

How can i user add picture and text on my website? :D [closed]

enter image description here

Help 😀

  1. i want that u drag and drop from desktop a picture into the image div

2.bit more complicated i want to save the image and the “enter your favorite” text. Maybe add a little button where you can go like in edit mode. So the answer isnt always changable via one click if you catch my drift

Here my simple code:

<!----1 Rank--->
        
        <div class="container">
          <div class="row">
            <div class="col-sm">
              <div class="rankbox">
                <h2>1</h2>
                <input type="image" style="height: 200px; width: 200px;">
                <br>
                <br>
                <input type="text" id="rank_1" placeholder="Enter your favourite" style="text-align:center;"> 
              </div>
            </div>
          </div>
        </div>     

thanks for ur attention

How to handle large number of data coming from back-end, without pagination [closed]

Let’s say I call an API to fetch some data from the database, based on certain query parameters, and that API queries the database and gets a large number of results, for example 1 million.

Whats the best way for the client to receive the results, without using pagination (limit/offset) ? I mean from the network stand-point. JSON is slow, and I was wondering if there’s a better alternative. I know browsers can stream videos for example, which are large and have no issues. Could I send the data in some kind of binary format that is faster to put into the client browser memory than JSON ?

Client is Svelte app and doesn’t display all the results, it only displays like 40 at a time, but during scrolling, it displays the next 40 and so on…

If I added pagination on server, then scrolling would be laggy.