The django modal window don’t stay with content inside

I’m really lost here.
I build the django model window and when i start to write the content inside, everything it’s out from the modal window. I have no idea what’s going on.

Click here to see the image1

The modal code

<div id="modal_window_new_register" class="modal_window_new_register" >
    <div class="new_register_modal">
        <button class="close" id="close">X</button>
    </div>

    Test Test Test Test Test

</div>

The model css code

/* Modal window */

.modal_window_new_register{
    width: 100vw;
    height: 100vh;
    position: absolute;
    top: 0;
    left: 0;
    background-color: #00000080;
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;

    overflow: auto;
}

.new_register_modal{
    width: 40%;
    min-width: 450px;
    height: 95vh;
    background-color: #ffff;
    padding: 20px;
    border-radius: 10px;
}
.close{
    position: absolute;
    top: -5px;
    right: -5px;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 0;
    background-color: #ffffff96;
    font-size: 20;
    cursor: pointer;
}
.modal_window_new_register.open_new_register_modal{
    display: flex;
}

How can I make parent categories bold in a product table with Woocommerce?

I am using a table products to filter categories.

What I need is to make only the parent categories bold.

In this search result e.g.:

https://demo.motorocker.gr/?swoof=1&antalaktika=scooter

we need to bold only parent categories

I am attaching a pic (https://i.stack.imgur.com/oYEcR.png)

I tried to make it through CSS but it didn’t work.

I tried e.g. this class li#select2-wcpt_filter_product_cat-zx-result-ac7d-elastika

but I see that every time each category comes out with a separate ID.

Any advice?

Why does selecting one item in my React-Native FlatList trigger a re-render of all items?

I’m new to React-Native and trying to investigate why all items in my FlatList are re-rendering when I select one of them.

This is the code of the list:

import React, { useEffect, useState } from 'react';
import { FlatList, StyleSheet } from 'react-native';

import Task from './Task';
import useTasks from '../hooks/useTasks';
import TaskListHeader from './TaskListHeader';

export default function Tasks({ header: Header }) {
    const [title, image, list] = useTasks()
    const [doneTasksCount, setDoneTasksCount] = useState(0)

    const updateCounter = (isDone) => {
        isDone ? setDoneTasksCount(doneTasksCount + 1) : setDoneTasksCount(doneTasksCount - 1)
    }

    useEffect(() => {
        const count = list.reduce((acc, cur) => cur.isDone ? ++acc : acc, 0)
        setDoneTasksCount(count)
    }, [list])

    const renderItem = ({ item }) => {
        return <Task {...item} updateCounter={updateCounter} />;
    };

    const header = () => {
        return (
            <>
                <Header />
                <TaskListHeader
                    title={title}
                    imageURL={image}
                    allTasksCount={list.length}
                    doneTasksCount={doneTasksCount}
                />
            </>
        )
    }

    return <>
        <FlatList
            data={list}
            renderItem={renderItem}
            keyExtractor={({ task }) => task}
            ListHeaderComponent={header}
            style={styles.list}
        />
    </>
}

const styles = StyleSheet.create({
    list: {
        backgroundColor: '#EBFFEE'
    }
})

And the code of the list item is this:

import React, { useState } from "react";
import { Image, StyleSheet, Text, TouchableOpacity, View } from "react-native";

export default function Task({task, icon, isDone, updateCounter}) {
    const [isMarked, setIsMarked] = useState(isDone)

    const handlePress = () => {
        setIsMarked(!isMarked)
        updateCounter(!isMarked)
    };

    return <View style={[styles.content, isMarked ? styles.markedContent : styles.unmarkedContent]}>
        {console.log(`render ${task}`)}
        <View style={styles.info}>
            <Image source={icon} style={styles.icon} />
            <Text style={[styles.title, isMarked ? styles.markedTitle : null]}>{task}</Text>
        </View>
        <TouchableOpacity
            style={[styles.actionButton, isMarked ? styles.markedButton : styles.unmarkedButton]}
            onPress={handlePress}
        >
            <Text style={styles.buttonTitle}>{isMarked ? "Feito" : "Fazer"}</Text>
        </TouchableOpacity>
    </View>
}

const styles = StyleSheet.create({
    content: {
        flexDirection: 'row',
        marginBottom: 14,
        borderRadius: 16,
        justifyContent: 'space-between',
        alignItems: 'center',
        maxHeight: 100,
        overflow: 'hidden',
        marginHorizontal: 16
    },
    icon: {
        width: 22,
        height: 22
    },
    info: {
        paddingLeft: 14,
        paddingVertical: 32,
        flexDirection: 'row',
        alignItems: 'center',
    },
    title: {
        marginLeft: 14,
        fontWeight: 'bold'
    },
    actionButton: {
        height: '100%',
        justifyContent: 'center'
    },
    buttonTitle: {
        fontWeight: 'bold',
        marginHorizontal: 14
    },
    markedButton: {
        backgroundColor: '#00EA17'
    },
    unmarkedButton: {
        backgroundColor: '#FF5D5D'
    },
    markedTitle: {
        textDecorationLine: 'line-through'
    },
    markedContent: {
        backgroundColor: '#E1EFF2'
    },
    unmarkedContent: {
        backgroundColor: '#BDBCFF'
    }
})

The list has a header where I display the number of selected items.

I tried to use React.memo at the Task component but it didn’t work.

Microsoft Cognitive Services – Unsupported Audio Format

I am developing a web app in ASP.net Core MVC.

I am trying to record audio in Javascript through the users microphone and I achieve this by using MediaRecorder(). I send the blob with the audio data to the backend where I receive the data in the form of IFormFile.

Script to record audio:

    navigator.mediaDevices.getUserMedia({ audio: true })
    .then(async function (stream) {
        var recordButton = document.getElementById("record-button");
        var stopButton = document.getElementById("stop-button");

        var microphone = await audioContext.createMediaStreamSource(stream);

        var gainNode = audioContext.createGain();
        var recorder = new MediaRecorder(stream);

        var destination = audioContext.createMediaStreamDestination();

        recordButton.addEventListener("click", function () {
            gainNode.connect(destination);
            recorder.start();
            recordButton.disabled = true;
            recordButton.style.pointerEvents = "none";
        });

        stopButton.addEventListener("click", function () {
            microphone.disconnect();
            gainNode.disconnect();
            recorder.stop();
        });

        recorder.ondataavailable = (event) => 
        {
            var blob = event.data;

            var formData = new FormData();
            formData.append('audioBlob', blob);
            formData.append('sentence', $('#sentence-input').val());

            $.ajax({
                url: '@Url.Action("ProcessAudio", "Sandbox")',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    $('#modalContent').html(data);

                    $('#myModal').modal('show');
                },
            });
        };

I then receive the data, copy it to a byte array, save it in a Temporary File in the desired sample rate that Microsoft Cognitive Services asks for, and send it to my API in Python where I invoke Microsoft’s tool.

@app.route("/pronunciation-assessment", methods=["POST"])
def pronunciation_assessment():
    audioFile = request.files['audio_data']
    reftext = request.form.get("reftext")

audioFile.save("audio.wav")

audioFile = open("audio.wav", "rb")
def get_chunk(audio_source, chunk_size=1024):
    while True:
        chunk = audio_source.read(chunk_size)
        if not chunk:
            break
        yield chunk

referenceText = reftext
pronAssessmentParamsJson = "{"ReferenceText":"%s","GradingSystem":"HundredMark","Dimension":"Comprehensive","EnableMiscue":"True"}" % referenceText
pronAssessmentParamsBase64 = base64.b64encode(bytes(pronAssessmentParamsJson, 'utf-8'))
pronAssessmentParams = str(pronAssessmentParamsBase64, "utf-8")

url = "https://%s.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=%s&usePipelineVersion=0" % (region, language)
headers = {
    'Accept': 'application/json;text/xml',
    'Connection': 'Keep-Alive',
    'Content-Type': 'audio/wav; codecs=audio/pcm; samplerate=16000',
    'Ocp-Apim-Subscription-Key': subscription_key,
    'Pronunciation-Assessment': pronAssessmentParams,   
    'Transfer-Encoding': 'chunked',
    'Expect': '100-continue'
}

response = requests.post(url=url, data=get_chunk(audioFile), headers=headers)

audioFile.close()

return response.json()

I have done unit testing on this endpoint prior with just a standard .wav file that was stored locally and it worked out fine. Furthermore, upon listening to audio.wav, I observe that everything was saved correctly and the audio is playable.

However, when I return the response.json, I get

Expecting value: line 1 column 1 (char 0)

And upon close inspection, the content of response is b’Unsupported audio format’

What shall I do?

How to show php encryted data in database to html using javascript API in expressjs?

I have a website build using php mysql to list a set of activities, Admin might enter their activity title which may contain special characters like smileys.

In php I have used htmlentities to encrypt data to save into the database as given below

$titleToSave = htmlentities($_POST[‘title’]);

Also in the html template, I have used html_entity_decode to display the encrypted value from the database

< h2> < ? php echo html_entity_decode($data[‘title’]) ? ></ h2>

It works correctly in the php driven website, The screenshot of database and html result is given below

enter image description here
enter image description here

For the above website, I have an api service running in nodejs to fetch recent activities to show on a third party website, The problem I am facing here is the data retrieved from the api, is not decoding correctly as it is running in javascript and the code used in given below

    API end point code for decrypting

    let decode      = require('html-entities-decoder')
    response.title  = decode(data.title);

The result I obtained on third party website screenshot is given below

enter image description here

Can someone help me to solve this issue?

How do I hide bubbles in my SVG scatterplot when a checkbox is unchecked?

I want to hide bubbles from my scatterplot when the corresponding checkbox is unchecked. So far I have managed to make it make a console log when the box is unchecked. But apart from that nothing happens.
(I want the bubbles where the json item “vorlagentyp” is equal to “Initiative” to disappear and then come back when the checkbox is checked again.)

 // Get references to the checkboxes
      const initiativeCheckbox = document.getElementById("checkbox-initiative");
      const referendumCheckbox = document.getElementById("checkbox-referendum");
      const obligatorischCheckbox = document.getElementById("checkbox-obligatorisch");
      const gegenentwurfCheckbox = document.getElementById("checkbox-gegenentwurf");

      // Add event listeners to the checkboxes
      initiativeCheckbox.addEventListener("change", initiativeCheckboxChanged);
      referendumCheckbox.addEventListener("change", referendumCheckboxChanged);
      obligatorischCheckbox.addEventListener("change", obligatorischCheckboxChanged);
      gegenentwurfCheckbox.addEventListener("change", gegenentwurfCheckboxChanged);

      // Event listener functions
      function initiativeCheckboxChanged(event) {
        const checkbox = event.target;

        if (!checkbox.checked) {
          const bubbles = document.querySelectorAll('.bubble[vorlagentyp="Initiative"]');
          
          bubbles.forEach(bubble => {
            bubble.remove();
          });
          console.log("Initiative unchecked");
        }
        }

//code for the other checkboxes (so far only console.log)

This snippet is part of a bigger code, where there is a bubble scatterplot. Here is the relevant code for the bubbles

svg.selectAll(".bubble")
      .data(filteredData)    // bind each element of the data array to one SVG circle
      .join("circle")
      .attr("class", "bubble")
      .attr("cx", d => xScale(d.ja_anteil))   
      .attr("cy", d => yScale(d.stimmbeteiligung))  
      .attr("r", 7)  
      .attr("stroke",  d => pubColors[d.vorlagentyp])
      .attr("fill", d =>  pubColors[d.vorlagentyp])  
      .attr("fill-opacity", 0.5)

Erroring out while using ForEach

While using for each, i am getting the error “unhandledRejection: TypeError: data.forEach is not a function”

Solution i tried
I converted the data into JSON format before using for each

const data = JSON.parse(message);

I logged the JSON message and below is the message:

{
  '0': {
    'Id': 4680,
    ’Flgtrue ?': 'Yes',
    'Type': ‘rrrr’,
    RN: '56971',
    'Name': ‘TSN’’s Percussive Arts Centre.Inc’,
    'Start Date': '2022-01-01',
    'End Date': '2023-08-02',
  },
‘1’: {
    'Id': 4681,
    ’Flgtrue ?': ‘No’,
    'Type': ‘rrsrr’,
    RN: '56975’,
    'Name': ‘TSN’’s Percussive Arts Centre.Incffff’,
    'Start Date': '2022-01-01',
    'End Date': '2023-08-02',
  },
  letter_path: ‘Test/File/2050_Sample.pdf'
}

Any help is appreciated

Thank You in Advance

How can I handle click events on a Bootstrap table dropdown menu that controls column visibility?

I’m currently building a table with this Bootstrap table https://bootstrap-table.com/, I’m also using https://bootstrap-table.com/docs/api/table-options/#showcolumns that enables a dropbox to choose which column to show.
Now I need to handle when the user clicks on one of the dropbox items with some custom commands.

I’ve already tried with

$(document).ready(function() {
        $(document).on('click', '.dropdown-item.dropdown-item-marker', function() {
        
        console.log("hello")
  });
});

but it doesn’t work.

How to remember javascript and react codes?

I am learning front end development, where I am trying to learn HTML, CSS, JavaScript and React, but i can’t remember the code after. What is the best way to learn front end development, how to memorize css and js as well as react codes?

I tried to make simple project by watching tutorials but i cannot make it myself after practicing alot.

How to export JavaScript module members to Rust and call them using v8 or deno_core?

Very much simplified, I would like to write a javascript module which exports members like export function sum(a, b) {return a + b} and then use v8 or deno_core in Rust to compile the module and call the sum method when needed. Could someone tell me how to handle this when using modules instead of traditional scripts?

I already made this work when not using modules but scripts that return a namespace with methods. This way, however, I cannot import/require which I need to keep. Also it is very straight forward to call Rust from Javascript but I want to do it the other way around: Call Javascript functions from Rust. Getting Isolates and the JsRuntime to work is not the issue.

I appreciate any help!

Can’t Render my store.ejs file as HTML code

I am following a tutorial, and would like to know what I should do in order to render my views/store.ejs file as HTML? Here is all of my server.js code:

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config()
}

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripePublicKey = process.env.STRIPE_PUBLIC_KEY

const express = require('express')
const app = express()
const fs = require('fs')
const stripe = require('stripe')(stripeSecretKey)

app.set('view engine', 'ejs')
app.use(express.json())
app.use(express.static('public'))

app.get('/store', function(req, res) {
    fs.readFile('items.json', function(error, data) {
        if (error) {
                res.status(500).end()
            } else {
            res.render('store', {
                items: JSON.parse(data)
            })
        }
    })
})

app.listen(3000)

I would also like to know how the node.js application looks for the Views folder, and renders the EJS File as HTML?

If you need more clarity, let me know.

Method 1:

  1. I used const path = require(‘path’) to specify the path.

  2. I tried using app.set(“views”, path.join(_dirname, “views”)) to set the directory of the EJS File I wanted to render.

dinamicly generated divs from json file problems sharing link

I am currently working on a real estate website, i wanted to make it easely maintable. So i decited to create a website where all the listings dinamicly generated from a json file. i gave an id property to the json, and a details button to the listings. to the button on click event i added a function which saves the id to a localstorage variable and opens a details page which is also dinamicly generated using the same json datas. my problem is that if i want to share the link.. it is obliusly unshareable. because the details side needs an id number in order to know which details to be generated. heres my codes so far :

function addElement(appendIn, value){
let div = document.createElement('div');
div.className = "box";

let {num, fokep, utcanev, kerulet, ar, kepekszama, ingtipus, ingallapot, negyzetmeter } = value;

div.innerHTML = `
<div class="thumb">

    <p class="total-images"><i class="far fa-image"></i><span>${kepekszama}</span></p>
    <p class="type"><span>${ingtipus}</span><span>${ingallapot}</span></p>
    <img src="${fokep}" class="img" alt="">
</div>

<h3 class="name">${utcanev}</h3>
<p class="location"><i class="fas fa-map-marker-alt"></i><span class="category">${kerulet}</span> Kerület</p>
<div class="flex" style="justify-content:center; align-items:center">
        <p><span class="price">${ar}</span><i"> M Forint</i></p>
        <p><i class="fas fa-maximize"></i><span>${negyzetmeter} m2</span></p>
 </div>

<a href="property.html" class="btn num" target="_blank" rel="noopener noreferrer" style="text-align:center;" data-filter="${num}" onmousedown="detailsClick(${num})">Részletek</a>

`;
appendIn.appendChild(div);
}

this function generates all the listings on the main page it is called here

fetch('./database/houses.json')
.then(res => res.json())
.then(json => {

    // iterating products
    for(let value of json){
        addElement(grid, value)
    }
    
});

the on click function just saves the num aka id variable in a localStorage

function detailsClick(num) {
localStorage.setItem("idIndex", num);
detailsIdClicked = num;

}

than in the details page i use the same fetch method to get the details from the jason file but only for the matching id numbered property

let num = localStorage.getItem("idIndex");

fetch('./database/houses.json')
 .then(res => res.json())
 .then(json => {

// iterating products
for(let value of json){
    if (num == value.num){

    addDetailedElement(grid, value);
    addheadElement(head,value);

    
}}

Than it generated the detaild div in the details page. But i just realised if i want to share a link from one computer to another, it obiously doesnt have the id number so it doesnt generate the same site. I wonder is there any solution for such problem? I have to admit i am quite new to web developement and never before did any dinamicly generated websites. i just realised this problem and now i am clueless about it. I was thinking of maybe append the url link with the id number and than read the id number from url to generate it, but if i do that the website doesnt load at all since theres no details1.html or details2.html only details.html

Any help would be much appreciated

What’s the best way to use a prop to dynamically name a div id and button data-bs-target in Vue.js and Bootstrap 5?

How to name a div id with a parameter passed as props

I am trying to name the id of a div and the data-bs-target of a button with a name passed as props so that I can use the same component multiple times on the same page with different identifiers.
Because they are buttons and with a general identifier even if I press different buttons, the first button is always pressed, because they all have the same identifier.

Class RestauranteCard.vue
HTML

      <div
          v-if="!noimage"
          id=carouselNumber
          class="carousel slide"
          data-bs-ride="carousel"
          data-interval="false"
      >
        <div class="carousel-inner">
          <div
              v-for="(link, idx) in imagenesLink"
              :key="link"
              class="carousel-item"
              :class="{ active: idx === 0 }"
          >
            <img :src="link" class="d-block w-100" alt="foto" />
          </div>
        </div>
        <button
            class="carousel-control-prev"
            type="button"
            data-bs-target=#carouselNumber
            data-bs-slide="prev"
        >
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="visually-hidden">Previous</span>
        </button>
        <button
            class="carousel-control-next"
            type="button"
            data-bs-target=#carouselNumber
            data-bs-slide="next"
        >
          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="visually-hidden">Next</span>
        </button>
      </div>

JS

  props: {
    restaurante: {
      type: Object,
      required: true,
    },
    carouselNumber: {
      type: String
    }
  },

The class calling RestaurantCard

      <div v-else
          class="card row-cols-1"
          v-for="restaurante in restaurantes"
          :key="restaurante.id"
      >
        <RestauranteCard :restaurante="restaurante" :carouselNumber="restaurante.id"></RestauranteCard>
      </div>

Why I can’t focus on element inside of a contenteditable block?

The problem can clearly be seen in the snippet. I want to listen to a focus/blur events inside of a contenteditable block, but it fires the blur event right after the focus if I use mouse (focusing with tab is kinda works with the tabindex=”-1″ workaround).

I can trigger focus only if I double click on the inner element, which is not the behavior I wanted. Also, even if I focused on the inner element, it will fire blur event when I start typing. Have no ideas how to avoid all this.

const el = document.getElementById('inner')

el.onfocus = onFocus  
el.onblur = onBlur

function onFocus() {
  console.log('Focus')
}

function onBlur() {
  console.log('Blur')
}
<div contenteditable="true" tabindex="-1">
  <div id="inner" tabindex="0">Inner element</div>
</div>

JS input, enter new data and save them

Hello guys, i need help.

So,

HTML

    <div id="profile-popup" class="popup">
        <div class="popup__container">
            <button type="button" class="popup__close" aria-label="Close"></button>
            <h3 class="popup__name">edit profile</h3>
            <form class="popup__form" name="profile" novalidate>
                <label class="popup__label">
                    <input type="text" class="popup__input popup_n" name="username" required placeholder="name" minlength="2" maxlength="20">
                </label>
                <label class="popup__label">
                    <input type="text" class="popup__input popup_d" name="description" required placeholder="about you" minlength="3" maxlength="100">
                </label>
                <button type="submit" class="popup__submit" aria-label="Save">Save</button>
            </form>
        </div>

JS

    let formElement = document.querySelector('.popup__form');
    let username = document.querySelector('input[name="username"]');
    let job = document.querySelector('input[name="description"]');

    function handleFormSubmit (evt) {
    evt.preventDefault(); 
        document.getElementById('input[name="username"]').value;
        document.getElementById('input[name="description"]').value;
        document.querySelector('.popup_n').textContent = username;
        document.querySelector('.popup_d').textContent = job;
}

formElement.addEventListener('popup__submit', handleFormSubmit); 

it is necessary to enter new data and save (NO DB)

my task is to get data from input , enter new data and save them