How to prevent creating new text nodes after ‘Enter’ press in contenteditable element?

Is it possible using some CSS properties
or HTML attributes or JS solution
prevent splitting text node?

I don’t want to call div.normalize() after each ‘Enter’ press
And please don’t suggest using textarea

<!DOCTYPE html><div id=div contenteditable='plaintext-only'>Prevent Creating new textNodes</div>
<style>
div { outline: 1px solid }
</style>
<script>    'use strict';

    console.log('ChildNodes before ENTER press:',div.childNodes.length)

    div.onkeyup=e=>{
      if('Enter'==e.key) console.log('ChildNodes after ENTER press',div.childNodes.length)
    }

    div.focus()

    </script>

Also I don’t want to manually process ‘Enter’ press
in keydown event via event.preventDefault()

I am search a simple solution

Thank You!

visualViewport.scale returns clearly wrong value

I’m trying to determine if a Webview window on an Android device is pinch-zoomed or completely zoomed out. The best way seems to be using visualViewport.scale . It’s straightforward, it should return 1 if it’s zoomed out or some value bigger than 1 if it’s zoomed in. Except it doesn’t, on my Motorola Moto G54 device with Android 13. It’s definitely zoomed out, and it returns something like 0.440… plus a host of more decimal digits. It should be 1.0 . I notice that if I zoom in, it returns a bigger value, which seems to match the zoom level, so it’s consistent in this respect but starts from a value other than 1, which is wrong.

My main question, does anybody know what could be wrong ? I use the property simply by window.visualViewport.scale , which seems to be the right way. Maybe I’m missing something.

Second question, is there a better way of determining pinch zoom level in a Webview on Android ? I searched but couldn’t find one.

Thanks for any help.

Here is a sample code. As said, at begin when it’s zoomed out, on a swipe it should return 1 or 1.0 . which should be visible on the last line of the page (it always shows the result of the last call).

<html>
<head>

<script type="text/javascript">
    <!--

    function OnTouchStart (aEvent)
    {
        Message ("zoom " + window.visualViewport.scale);
    }

    function Message (aMsg)
    {
        var p = document.getElementById ("message");
        p.innerText = aMsg;
    }

    //-->
</script>

</head>

<body style="font-size:4vw;"
  ontouchstart = "OnTouchStart (event)"
>

<p style="font-size:6vw; text-align:center; margin-top:4vw;">
Test swipe events
</p>

<p>
test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events <br/>
test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events test swipe events <br/>
</p>

<p id="message"/>

</body>
</html>

‘npm run dev’ in astrojs fails: “Unexpected token import”

I’m trying to get astro to run.

I’ve installed a project using ‘npm create astro@latest’.
I’ve accepted all the project defaults.

If I then descend into the directory of the new projects and do ‘npm run dev’, I get the following:

/home/bob/play/astroplay/mechanical-mars/node_modules/astro/astro.js:23
        const semver = await import('semver');
                             ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev: `astro dev`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bob/.npm/_logs/2024-04-07T04_34_53_415Z-debug.log

Getting value of an object while passing the object name and key as parameter during runtime

I wish to get the value of Object, by passing the object and key as a parameter during runtime.
Login.page.ts


export const loginPage = {
username= '#userid',
Passwd='#passwd',
login='#login'
}

Login.feature

Given when I click on "loginPage.login" button.

StepDef

given("when I click on {string} button", function (locator: string){
Console.log(locator)
});

Output
undefined
If I am hardcode as console.log(loginPage.login)
Then I am getting the value as
#login

Anyone could you please help as I am new to this.
Appreciate your support in advance.

Title: Issue Implementing ‘!p’ Command in Discord Matchmaking Bot

I’m developing a Discord bot for matchmaking in a game, and I’ve hit a snag with implementing a specific feature. The bot is supposed to allow two randomly selected captains to pick players from a pool in a newly created game channel. However, when issuing the !p command to pick a player, nothing happens—no new embed is generated, and the player isn’t moved to a team.

Here’s a simplified overview of how the feature is supposed to work:

1.Two captains are picked randomly when the game channel is created.

2.The first captain uses !p @user to pick a player from the “Remaining players” pool.

3.An embed should update to reflect the picked player moving to Captain A’s team, and it’s then Captain B’s turn.

4.The process repeats, but Captain B picks two players. The last player automatically joins Captain A’s team.

A final embed displays the teams.

here’s an example of the embed structure:

enter image description here

For some reason, when I issue the !p command, it doesn’t trigger the creation of a new embed or modify the team compositions as expected. I’ve ensured that my code is set up to handle the command and modify the embeds, but it’s not working as intended.

You can find my full code here:

I’m not sure why this isn’t working. Has anyone encountered a similar issue or sees something I might be missing in my implementation? Any help would be greatly appreciated.



{
    title: 'Game(number) — General Queue V3',
    description: 'Start picking!',
    fields: [
        { name: 'Team Alpha', value: '@CaptainAn@pickedUser' },
        { name: 'Team Beta', value: '@CaptainB' },
        { name: 'Remaining Players', value: '@user2n@user3n@user4' },
        { name: 'Current Pick', value: '@CaptainB Use the !p command to pick 2 players' }
    ]
}







asp.net mvc: How to loop through @Model.DataTable rows in javascript

My view uses a dataset as a model.

I need to loop through all the rows in the first table of the dataset in javascript, but can’t get that to work.

    function GetData() {
                var Arr = [];
                for (var i = 0; i < @Model.Tables[0].Rows.Count; i++) {
                    Arr.push({ x: ['@Model.Tables[0].Rows[i]["ProjTaskDateStart"]', '@Model.Tables[0].Rows[i]["ProjTaskDateEnd"]'], y: 'Task @Model.Tables[0].Rows[i]["ProjTaskNum"]', name: '@Model.Tables[0].Rows[i]["ProjTaskTitle"]', TaskStatus: '@Model.Tables[0].Rows[i]["ProjTaskTitle"]'})
                };

console.log(Arr);

             
    }

it’s the javascript variable “i” that is not being read withing the Rows[i]. Totally understand why, but is there a way to get around it and still loop through the rows in javascript?

Trying to generate a PDF file from content from HTML page

I have created a function within Javascript to generate a PDF based on content injected from user inputs. However, whenever I click the button to load the PDF button, it doesn’t run and no errors come up on the console. Looking to get some help, thank you

    // importing jspdf
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>


// the pdf button
 <button class="pdf_button" onclick="generatePDF()">Create PDF Report</button>

  // the javascript code
function generatePDF() {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();

    const imagePath = '/static/img/pic.png';
    const imageFormat = 'PNG';

    const pageWidth = doc.internal.pageSize.getWidth();
    const logoWidth = 30;
    const logoHeight = 20; 
    const margin = 10; 
    const xPosition = pageWidth - logoWidth - margin;
    const yPosition = margin;

    doc.addImage(imagePath, imageFormat, xPosition, yPosition, logoWidth, logoHeight);

    const userName = document.querySelector('text_center').textContent.trim();
    const superScore = document.getElementById('scoreText').getAttribute('data-score');
    const superDecision = document.querySelector('.left-factors dd:first-child').textContent;
    const superRate = document.querySelector('.left-factors dd:nth-child(2)').textContent;
    const advice = document.querySelector('.right-factors dd:nth-child(2)').textContent;
  
    doc.setFontSize(12);
    doc.setFont('Courier')
    doc.text("This is your Report!", 10, 10); 
    doc.text(`Welcome, ${userName}`, 10, 20); 
    doc.text(`Your Score is: ${superScore} out of 900`, 10, 30);
    doc.text(`${superDecision}`, 10, 40);
    doc.text(`Super Rate: ${superRate}`, 10, 50);
    
    let currentY = 60; 
    doc.setFontSize(10);
    doc.text('Contributing Factors:', 10, currentY);
    shapValues.forEach((value) => {
      currentY += 10;
      doc.text(`${value.factor}: ${value.percentage}%`, 10, currentY);
    });
  
    currentY += 10;
    doc.text(`Advice: ${advice}`, 10, currentY);
  
    const safeUserName = userName.replace(/s+/g, '-'); 
    const fileName = `${safeUserName}'s-SuperScore-Report.pdf`;
    doc.save(fileName);
  }

dynamically applied transitions using react-transition-group not appearing

So i am building a react app that contains a slice component, each slice contains 2 project components. when i hover over one project i would like to minimise the one that isnt being focused on and maximise the one that is. but i cant seem to envoke a smooth transition using react transition group. right now nothing happens at all when i hover but the components do re render.

here is my CSS

.minimized-enter{
    opacity: 0;
}
.minimized-enter-active{
    opacity: 1;
    transition: opacity 500ms ease-in-out;
}
.minimized-exit{
    opacity: 1;
}
.minimized-exit-active{
    opacity: 0;
    transition: opacity 500ms ease-in-out;
}
.maximized-enter{
    opacity: 1;
}
.maximized-enter-active{
    opacity: 0;
    transition: opacity 500ms ease-in-out;
}
.maximized-exit{
    opacity: 0;
}
.maximized-exit-active{
    opacity: 1;
    transition: opacity 500ms ease-in-out;
}

here is my Slice.js

import { useState, useEffect } from "react";
import Project from "./Project";
import "./Slice.css";
import { v4 as uuidv4 } from "uuid";
import { CSSTransition } from "react-transition-group";

export default function Slice(props) {
    const data = props.sliceData.projects;
    const [projectElements, setProjectElements] = useState([]);
    const projectUIDs = [uuidv4(), uuidv4()];
    const [animationClassStrings, setAnimationClassStrings] = useState(["", ""]);

    useEffect(() => {
        const elements = [
            document.getElementById(projectUIDs[0]),
            document.getElementById(projectUIDs[1]),
        ];
        setProjectElements(elements);
    }, []);

    const handleMouseOver = (index) => {
        if (animationClassStrings[index] === "maximized" || animationClassStrings[index] === "maximized") return;
        let tempAnimationClassStrings = [...animationClassStrings];
        tempAnimationClassStrings[index] = "maximized";
        tempAnimationClassStrings[index ^ 1] = "minimized";
        setAnimationClassStrings(tempAnimationClassStrings);
    };

    const handleMouseOut = (index) => {
        if (animationClassStrings[index] === "" || animationClassStrings[index] === "") return;
        let tempAnimationClassStrings = [...animationClassStrings];
        tempAnimationClassStrings[index] = "";
        tempAnimationClassStrings[index ^ 1] = "";
        setAnimationClassStrings(tempAnimationClassStrings);
    };

    const generateProjects = () => {
        return data.map((project, index) => (
            <Project
                key={uuidv4()}
                uid={projectUIDs[index]}
                projectData={project}
                animationClassString={animationClassStrings[index]}
                onMouseEnter={() => handleMouseOver(index)}
                onMouseLeave={() => handleMouseOut(index)}
            />
        ));
    };

    return <div className="slice">{generateProjects()}</div>;
}

here is my Project.js

import { useState, useEffect } from "react";
import { CSSTransition } from "react-transition-group";
import { v4 as uuidv4 } from "uuid";
import "./Slice.css";

export default function Project(props) {
    // declare state variables
    let [mainImage, setMainImage] = useState(null); // mainImage is the first image to be displayed in the project
    // declare utilities
    let data = props.projectData; // data is the projectData object passed in from Slice.js
    let elementAry = [
        <img src={mainImage} alt={data.name} />,
        <h1>{data.title}</h1>,
    ];
    const contentOrientation = data.orientation === "image--left" ? 0 : 1;

    import(
        process.env.PUBLIC_URL +
            "/public/assets/ProjectImages/" +
            data.mainImage
    )
        .then((image) => {
            setMainImage(image.default);
        })
        .catch((error) => {
            console.error("Error importing image: ", error);
        });

    let generateContent = () => {
        return (
            <div
                id={props.uid}
                className={"projectWrapper"}
                style={{ backgroundColor: data.color }}
                key={uuidv4()}
                onMouseEnter={props.onMouseEnter}
                onMouseLeave={props.onMouseLeave}
            >
                {elementAry[contentOrientation]}
                {elementAry[contentOrientation ^ 1]}
            </div>
        );
    };

    return (
        <CSSTransition in={true} timeout={500} unmountOnExit classNames={props.animationClassString}>
            {generateContent()}
        </CSSTransition>
    );
}

any help is appreciated

ive tried changing the transition to see if my styles are the issue but that didnt change anything. i would like one to fade out while the other one fades in.

Dynamic Validators

I have a backend app in which the admin is able to determine required fields for every form. the fields are saved in a seperate mongodb collection Fields. and every field has options that are saved in another collections called FieldOptions.

When the user submits the form, the user will submit the fields in the following fashion
[FieldOptionId].

I want to validate those options make sure they all exist and that all the required fields for that form has been provided. if one of the fields is not provided or there is an issue with one of the fields I want the response to be:

{
   "fieldId": [list of errors]
}

I use NestJS and Mongoose.

JavaScript while loop to print even numbers executes one more time after the condition is false

I have a simple while loop to print even numbers from 0 to 10. I would expect this code to print only up to 10. But it goes up to 12. I can modify the code to check for i<10 instead of i<=10. But I do not understand why the while loop goes on to print 12.

I expect the below code to print up to 10. But it prints up to 12.

let i=0;
while (i<=10){
    console.log(i);
    i+=2;
}

Prevent dynamic loading of content in a website when button is clicked

I’m currently developing chrome extension, there is a button on the current page that when click will open a Popup with Product Information and the URL is changed too.
But the issue is that sometimes the button redirect to a new page completely (without reloading the page, it loads content dynamically).

I tried many solutions like using mutation observers to restore back the original HTML but it doesn’t work since the content is dynamically loaded and it breaks the HTML as well as no button works.

How to have some workaround for this?

Edit: Button has no src/href, it loads new site or do the operation from its JS code.
Page loads everything dynamically.

Reliably compress a string of 1s and 0s into a smaller string, and convert it back to the Exact same string. Everytime

I was wondering if there is a better way to do this in NodeJS or plain javascript.

I wrote some functions that can do this by counting how many times they repeat, but i was wondering if there is a better way, or if theres any improvements to be made.

The input will always be a 256 bit number string consisting only of 1s and 0s (‘00001110100101…..’)

function toSmallString(x) { // {{{
  return new Promise((resolve, reject) => {
    // always start with a 0 or a 1 to show bigstring where to start
    var nn = `${x[0]}`;
    var ar = x.split('')
    var n = 0;
    var lv = ar[0];

    // a blank item to iterate, catches the last set of numbers
    ar.push('')

    // 0 means ten and continue since we will always be above 1
    for (const v of ar) {
      // if flipping bits, store number and start over
      if (lv !== v) { nn += n ;lv = v; n = 1 }

      // increment if last value is same as this value, if value becomes 10, add a 0 to nn and start over
      else { n = n + 1;if(n === 10){nn += '0';n = 0} }
    }
    resolve(nn)
  })
}

function toBigString(x) {
  return new Promise((resolve, reject) => {
    var ar = x.split('')
    var sn = parseInt(ar.shift())
    var nn = ''

        // 0 means 10 zeros and continue without bitflipping
        // any other number will expand and then flip bits

    for (const v of ar) {
      var n = parseInt(v)
      var i = 1
      if(n === 0){
        nn += sn.toString().repeat(10)
      } else {
        while(i <= n){
          nn += sn
          i = i + 1
        }
        // bit flip
        sn = (sn === 0) ? 1 : 0;
      }
    }
    resolve(nn)
  })
}

I tried a couple things, im very inexperienced (hexadecimal, scientific notation) but the values would change form when trying to convert it back to the original 256 bits of 1s and 0s.

each 1 and 0 is important, their placing and order is vital to preserve.

My plan is to store hundreds of thousands of these 256 bit strings, so a form of string conpression would be the way to go.

How do I make a vertical line number like in vscode in html css and jquery(or javascript)

I want to be able to do this vertical number thing in html, css and jquery or javascript (any of the two will be fine) becasue I am trying to make a code editor using those languages and I wanted that cool looking vertical number thing on the side when ever the user is typing any code. I tried looking up some tutorials on youtube on how to do it but could not find anything on it.

Example:

enter image description here