How exactly “locale” param affects the result of Intl.Segmenter execution in JavaScript?

I had a task to parse Chinese and Japanese text to find the most precise amount of words. I didn’t know about Intl.Segmenter and once I found it, I thought “ah I cannot use it since my text can have a lot of different locales at the same time”. But I tried to use “en” locale with many languages including Chinese and Japanese in a single text source, and it seems to work fine. Actually I’m not a native speaker of Chinese and Japanese, but it looked to work correctly, or at least almost correctly, and that’s ok for me.

So what does a locale param really do? I also checked the spec, but didn’t find any information on exactly how different Intl.Segmenter locales affect the result.

I don’t understand why the swiper script don’t work

thanks for the help. I can’t understand why the script don’t work.
It’s my first time in using Swiper.

<div class="home" id="home">
        <div class="swiper homeSlider">
            <div class="swiper-warpper warpper">
                <div class="swiper-slide slide slide1">
                    <div class="content">
                        <img src="#" alt="#">
                        <h3>Ipsum latum</h3>
                        <h1>Ipsum latum</h1>
                        <p>ispum latum</p>
                        <a href="#" class="btn">Réserver</a>
                    </div>
                </div>
                <div class="swiper-slide slide slide2">
                    <div class="content">
                        <img src="#" alt="#">
                        <h3>RACLETTE</h3>
                        <h1>Plat savoyard</h1>
                        <p>Venez goûter ce plat typique de la Savoie</p>
                        <a href="#" class="btn">Réserver</a>
                    </div>
                </div>    
                <div class="swiper-slide slide slide3">
                    <div class="content">
                            <img src="#" alt="#">
                            <h3>RACLETTE</h3>
                            <h1>Plat savoyard</h1>
                            <p>Venez goûter ce plat typique de la Savoie</p>
                            <a href="#" class="btn">Réserver</a>
                    </div>
                </div>        
                        
            </div>
            <div class="swiper-pagination"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"></script>
   
   <script>
    var swiper = new Swiper(".homeSlider", {
      spaceBetween: 30,
      centeredSlides: true,
      autoplay: {
        delay: 7500,
        disableOnInteraction: false,
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },
      loop: true,
    }); 
  </script> 
    
   
</body>
</html>

I try to change class name or take the script src at the begining.
I watched lot of video on Youtube, review my code, search on the internet but nothing work.

How to Specify what form to display on template literals?

I’ve been hammering at this for the last few days and manage to:
fetch data from external json,
create a template and populated with template literals,
display all I want to see on the frontend.

the issue here is I need to be able to click a button and to change the display property from none to block to only the specific html element related to the button.

what would be the best way of relating both the button and the form so that when I click button 1, form 1 get display and no the last one?

// to fetch data from backend.
// const link = 'https://jsonplaceholder.typicode.com/users';
const link = './data.json';

// const container = document.getElementById('.item-container');
fetch(link)
  .then(res => {
    return res.json();
  })
  .then(data => {
    console.log(data);

    data.forEach(gun => {
      const template = `
    <div class="ticket ticket-${gun.ticket}">
    <div class="id card"><p>${gun.gunId}</p>
  </div>
    <div class="location card">
      <p class="gun-id">${gun.location}</p> 
    </div>
    <div class="description card">
      <button class="view" value="${gun.gunId}">Details</button>
      <div  class="modal" id="modal-${gun.ticket}" data-value="${gun.gunId}">
      <form class="modal-content" id="" data-value="${gun.gunId}"onsubmit="event.preventDefault(); validateForm();">
        <div class="form-header">
          <h1 id="" class="gun-form-name">${gun.gunId}</h1>
          <span id="" class="close" onclick="closeModal()">×</span>
          <span id="" class="back-arrow fa-lg" type="button" onclick="goBack()" role="button" aria-label="Go Back Button"><i class="fa-solid fa-arrow-left"></i>
           </span></div>
        <section class="main-content">
          <div class="container">
            <div class="card">
                <div class="wrapper">
                  <h3>${gun.gunId}</h3>
                    <div class="img">

                        <img class="gun-image"src="gun image.PNG" alt="test">
                        <div class="btn-overlay">

                        <button class="overlay-btn btn-1" value="${gun.partId.lightPipeId}"type="button">${gun.partId.lightPipeId}</button>
                        <button class="overlay-btn btn-2" value="${gun.partId.lightbugId}"type="button">${gun.partId.lightbugId}</button>
                        <button class="overlay-btn btn-3" value="${gun.partId.batteryId}"type="button">${gun.partId.batteryId}</button>
                        <button class="overlay-btn btn-4" value="${gun.partId.triggerId}"type="button">${gun.partId.triggerId}</button>
                        <button class="overlay-btn btn-5" value="${gun.partId.triggerPcb}"type="button">${gun.partId.triggerPcb}</button>
                        <button class="overlay-btn btn-6" value="${gun.partId.triggerSpring}"type="button">${gun.partId.triggerSpring}</button>
                        <button class="overlay-btn btn-7" value="${gun.partId.grayCable}"type="button">${gun.partId.grayCable}</button>
                        <button class="overlay-btn btn-8" value="${gun.partId.powerCableid}"type="button">${gun.partId.powerCableid}</button>
                        <button class="overlay-btn btn-9" value="${gun.partId.stockPcb}"type="button">${gun.partId.stockPcb}</button>
        
                    </div>
                    </div>
                    <div class="details">
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p>
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p>  
                    </div>
                    <div class="btn">
                        <button class="close-ticket"type="button">Close Ticket</button>
                    </div>
                </div>
            </div>
        </div>
        </section>
        
      </form>
    </div>
  
    </div>
  <div class="close-bt card">
    <button class="delete-button"id="${gun.gunId}">Close</button>
    </div>
    </div>
  </div>`
      document.getElementById('item-container').insertAdjacentHTML('beforeend', template);

      const modal = document.querySelectorAll(`#modal-${gun.ticket}`);
      const btns = document.querySelectorAll('.view').value;
      console.log(btns);
      for (let i = 0; i < modal.length; i++) {
        let child = modal[i];
        console.log(child);
      // switch()
    };
  });
    document.getElementById('open-tickets').innerHTML = data.length;
let gun = data;
console.log(gun);

    document.querySelectorAll('button').forEach(button => {
   
      button.addEventListener('click', () => {
          const fired_button = button.value;
          const test = document.getElementsByClassName("modal");
          let arrayModal= Array.from(test);
          arrayModal.forEach(function(element) {

            // For example, change the display from none to block
            element.style.display = "block";
            console.log(element);
            });
          console.log(arrayModal);
          // test.style.display = "block";
          // fired_button.classList.add('active');
          alert(fired_button);
          // modal.style.display = "block";
          // modal2.style.display = "none";
      });
  
        
  });

at the moment, when I click on any button it will only show one form.

any help would be great.

Enters conditional even though its undefined

I have a conditional that should not be entered unless there is a value for the variable gName. However, sometimes it is entering, but when it displays it to the screen its showing undefined. This should be impossible.

I’ve tried changing the conditional to other forms like if(gName.length > 0) etc but the same result. It happens intermittently. If I refresh the screen it shows the sentence with the actual value.

How can I resolve this so it only shows if their is a value?

JS:

var newMsg = document.createElement('div');
newMsg.innerHTML = "<span style='color: #3d8fcd;'>" + '&emsp;' + '<b>' + "Dr. " + prLastName + '</b>' + " is now chatting with " 

if (gName) { newMsg.innerHTML += "<span style='color: #3d8fcd;'>" + '<b>' + gName + '</b>' + " on behalf of " + '<b>' + pName + '</b>'; }
else { newMsg.innerHTML += "<span style='color: #3d8fcd;'>" + '<b>' + pName + '</b>' }

How it appears:

enter image description here

pathname won’t change the pathname

I got this test that is not passing

Basically when I click in the logo, is supposed to take you to the page. It does work, but in the tests the pathname won’t change:

export const Logo = () => {
  const getUrl = 'https://fake-url.com/'
  return (
    <div className={styles.logo}>
      <a
        href={`${getUrl()}homepage`}
        aria-label="Go to the homepage"
        data-testid="logo"
      >
        <img src={Logo} loading="eager" width="220" height="29" />
      </a>
    </div>
  );
};

And this is my test

  it('should redirect when clicking the logo', async () => {
    const { getByTestId } = render(<Logo />);

    const logo = getByTestId('logo');
    await userEvent.click(logo);
    expect(window.location.pathname).toEqual('/homepage');
  });

I played around a lot with window.location.href, trying to mock it.
I tried changing the host
Many solutions that I have seen in Slack doesn’t apply in my case or won’t work, many of them outdated.

Map object exported as a module in one file results in a Type error or undefined when imported . Node.js

I have two files one is launches.model.js and controller.js, The contents of the files are show below alongwith the output of the files.

The launches Map object imported in the controller.js results in an error or undefined

code of launches.model.js

const launches = new Map();
const launch = {
  flightNumber: 100,
  mission: "Kepler Exploration X",
  rocket: "Explorer IS1",
  launchDate: new Date("December 27,2030"),
  destination: "Kepler-442 b",
  customer: ["ZTM", "NASA"],
  upcoming: true,
  success: true,
};
launches.set(launch.flightNumber, launch);
console.log(launches);
module.export = {
  launches,
};   

//the output of the console.log is as below

[Map Iterator] {
  {
    flightNumber: 100,
    mission: 'Kepler Exploration X',
    rocket: 'Explorer IS1',
    launchDate: 2030-12-26T18:30:00.000Z,
    destination: 'Kepler-442 b',
    customer: [ 'ZTM', 'NASA' ],
    upcoming: true,
    success: true
  }
}

code of launches.controller.js

const { launches } = require("../../models/launches.model");
console.log(launches.values());

//the output of the console.log is as below
c:UserskuljiBoxPROJECTSNODENASA-PROJECTserversrcrouteslauncheslaunches.controller.js:3
console.log(launches.values());
                     ^
 
TypeError: Cannot read properties of undefined (reading 'values')

JavaScript Subtle Crypto – No Padding for AES-CTR

I am encrypting some data using window.crypto.subtle in JavaScript and I am trying to decrypt it in Python. From what I have read I was expecting Subtle Crypto to use PKCS#7 padding with AES-CTR, but it doesn’t seem to be padding it at all, which is then causing me a problem as I am expecting padding in Python.

I have the following example code which encrypts the plaintext “plain” using a password of “password”:

function bufferToHex(buffer) {
  return [...new Uint8Array(buffer)].map(b => b.toString(16).padStart(2, '0')).join ('');
}


window.crypto.subtle.importKey('raw', new TextEncoder().encode('password'), 'PBKDF2', false, ['deriveKey']).then(function(key) {
  var salt = window.crypto.getRandomValues(new Uint8Array(32));

  window.crypto.subtle.deriveKey({ name: 'PBKDF2', salt: salt, iterations: 10000, hash: 'SHA-256' }, key, { name: 'AES-CTR', length: 256 }, false, ['encrypt']).then(function(ekey) {
    var iv = window.crypto.getRandomValues(new Uint8Array(16));

    window.crypto.subtle.encrypt({ name: 'AES-CTR', counter: iv, length: 64 }, ekey, new TextEncoder().encode('plain')).then(function(ciphertext) {
      console.log('ciphertext is ' + bufferToHex(ciphertext));
    });
  });
});

However, this results in a 5 byte ciphertext len(ciphertext) == len(plaintext), but I was expecting 16 bytes with PKCS#7 padding? The documentation seems a little light when it comes to padding. I am currently using CryptoJS, but I was trying to reduce my dependency on external modules and migrate to Subtle Crypto.

How to make a fixed position of appended and prepended element?

I am trying to create a list of thumbnails. Due to look and feel conditions scroll bars are supposed to be hidden using overflow hidden property. in this list the first and last item are dynamically added using jQuery with the help of append and prepend functions.

 $(".woocommerce-product-gallery > ol.flex-control-nav").append("<li class='arrowLi right'>
     <i class='fa fa-arrow-right nextThumbProdGal navArrow'></i></li>");
        $(".woocommerce-product-gallery > ol.flex-control-nav").prepend("<li class='arrowLi left'>

“);

is there any possibility so that i can fix the position of the the dynamically added appended and prepended

  • elements.

    Currently i am getting the following output that scrolls the purple arrows with the scroll bar, i need them to fixed at one position and dont want to let them move with the movement of scrollbar.
    Initial position of right and left arrows

    Notice the right and left arrows they also move with the movement of scroll

  • Why is my Express server returning a 404 when submitting the form and not displaying console.log messages?

    Trying to create multi-user sessions (think Google Docs) but for some reason my server file doesn’t do anything, I’ve made sure my fetch function is correct yet nothing is changing. Even console.log from the server file commands are not showing. I’m not sure what I am missing here. I’m also using using a random link generator function but I do not think that is relevant as the link generates properly, nevertheless I will include it in my code.

    Server.js

    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const fs = require('fs');
    
    
    const app = express();
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(cors());
    
    
    
    app.post('/api/session', (req, res) => {
        const name = req.body.name;
        const sessionLink = req.body.sessionLink;
      
        // Create a data object to store the name and session link
        const data = {
          name,
          sessionLink,
        };
      
        // Write the data to a file
        fs.writeFile('data.json', JSON.stringify(data), (err) => {
          if (err) {
            console.error(err);
            res.status(500).send('Error writing to file');
          } else {
            res.send('Success');
          }
        });
      });
      
      app.listen(3000, (error) => {
        if (error) {
          console.log('Error starting server:', error);
        } else {
          console.log('Server is listening on port 3000');
        }
      });
      
    

    mainpage.js

     const generateSessionLink = () => {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < 8; i++) {
          result += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        return 'https://mywebsite.io/session/' + result;
      };
    
     
      const handleNameChange = (event) => {
        setName(event.target.value);
      };
    
      const handleSessionLinkChange = (event) => {
        setSessionLink(event.target.value);
      };
    
      const handleEnterSession = () => {
        if (name.trim() === '') {
          alert('Please enter your name or nickname.');
          return;
        }
        
      
        if (sessionLink.trim() === '') {
          alert('Please enter a session link or join an existing one.');
          return;
        }
      
        // Make a POST request to the session endpoint
        fetch('/api/session', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name,
            sessionLink
          })
        })
        .then(response => {
          if (response.ok) {
            // Store the name and session link in local storage
            localStorage.setItem('name', name);
            localStorage.setItem('sessionLink', sessionLink);
      
            // Redirect to the app page
            window.location.href = "/app";
          } else {
            throw new Error('Network response was not ok');
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('An error occurred while trying to join the session. Please try again later.');
        });
      };
    

    How to combine files into 1 download as opposed to having multiple pop-ups

    I have a solution in a system for group reporting where I have a selected number of datatables rendered out of view and I provide download links to each table, i.e.:

    let singlePDFdownload = function (table_id) {
        $(`.toolbar${table_id} .custom-pdf`).trigger('click')
    }
    

    This works fine for single downloads, but I also want to enable a quick button so all downloads can be generated at once. I currently do this with the .custom_pdf class so I can group the buttons that execute the datatable export of said table. This is a problem with the way I currently have this, because it initiates multiple downloads in the browser with multiple pop-ups (occasionally showing a warning).

    How do I go about combining those ‘clicks’ into a single download?

    Can I capture the download that occurs because of the trigger('click;) and then combine the PDFs somehow, or how can this be accomplished?

    Here is the code that triggers the multiple downloads:

    const $massPDFExport = $('#massPDFExport')
    $massPDFExport.on('click', () => {
        // remember all tables shown have this class
        $(`.custom-pdf`).trigger('click')
    })
    
    

    Debugging in vscode with chrome browser

    I have an issue with debugging in vscode my app is running on https://localhost:4200
    I get an empty page with no errors in the console, and all the developer tools tabs are empty too. Technologies – MEAN stack
    Launc.json file:

    {
    "name": "browser",
    "request": "launch",
    "type": "chrome",
    "cwd": "${workspaceRoot:supervisionclient}",
    "url": "https://localhost:4200", "webRoot": "${workspaceRoot:supervisionclient}" 
    }
    

    only in debugging its happen.

    enter image description here

    Thanks

    I try to change this configuration file, restart, clean chace, etc.. this does not help

    Rotating a camera to face a plane in Three.js

    so basically I have a problem in Three.js that I just can’t solve.
    The input coordinates are points in a 3d space that are all in one plane. The plane is tilted in the 3d space (in the image, the grey lines are only supposed to show how it could be tilted). I need to move the camera so that it is facing the middle of that object from the top down view (in the picture, the camera is red).
    The problem

    The desired output is the second image. Basically, it should represent the obejct as if it was in 2d. I know this is a loaded question, but even a small lead on how to do some part of the problem would be really helpful. If anyone needs more information, I’ll be happy to share.
    Desired output
    Thanks everyone for the help.
    Best regards,
    Thomas

    pgpromise converting number to string

    i use a select from my database with pg-promise to send my data into a server and use this data in my web application, but the numbers coluns, like a aggregation functions are formatting as string in my server,:
    Follow the code and sorry for bad english:

    const pgp = require("pg-promise")();
    const database = require("./DataBase");
    
    exports.ChequeGrouped = function (cheque) {
      let Select = `
    SELECT     
        COALESCE(nome_devedor, '_TOTAL') AS nome_devedor,
        CAST(SUM(valor_titulo) as numeric) AS valor_titulo,
        COUNT(id_movimento_cheque) AS contagem_movimento
    FROM public.__vwfw_movimento_cheque
        WHERE  tipo_movimento = 2 
            AND  nome_devedor ILIKE $1
        GROUP BY nome_devedor
        ORDER BY nome_devedor desc    `;
     return database.manyOrNone(Select, cheque);
    }
    

    i receive all data as string format,