Treating mongodb string values as numbers

enter image description here

I’m working with MongoDB and Node.js. I have scraped a bunch of HTML tables and inserted them into preexisting records using

await collection.updateOne({ "_id": m._id }, { $set: m.myObj });

Unfortunately, these are in string format. I’d like to do some mongo filtering by treating them as numbers. Is there a way to do this?

VSCode Find and Replace with varying pattern

I have a bunch of instances in a codebase that has this patterns

translate(k.SOME_KEY)

translate(k.ANOTHER_KEY)

and I want to find and replace this pattern to:

translate('SOME_KEY')

translate('ANOTHER_KEY')

Is this possible using regex and the VSCode find and replace?

How does Grammarly know where to position the red underline?

I’ve recently become fascinated with how tools like LanguageTool and Grammarly show red underlines on mispelled words on the screen. I’d like to do something similar but to show rich popovers with things like synonyms on hover of a word after first showing an underline on said word.

I know Grammarly is using the Shadow DOM with slots to wrap the textarea, but I still can’t tell how they’re able to (efficiently) determine the position of a specific word in the textarea. LanguageTool doesn’t use the Shadow DOM.

Neither duplicate show cloned HTML when I inspect it, which I thought they might in order to some how break the text into tokens that they could get bounding rects for — but that doesn’t appear to be it.

The result of using <grammarly-editor-plugin><textarea></textarea></grammarly-editor-plugin>
enter image description here

LanguageTool example:
enter image description here

I tried using the Canvas API to get the dimensions of a specific word, but that isn’t enough to determine its position in the textarea because the word could be on a line greater than the first.

In order to make this approach work, they have to be getting all the words in the textarea, computing their dimensions, and using the dimensions of the textarea to determine which line a target word is in the textarea; together with the dimensions, specifically the width, of the word, they would then have the x & y positions within the textarea. However, this seems too expensive and slow to pull off as fast as their underlines appear to show.

I could go with contenteditable by just wrapping each word in its own span, but that seems less than ideal.

Does anyone else know how else they could be able to determine the X & Y position of a word in a textarea.

Making checkboxes required when a check box is clicked [duplicate]

I have two check boxes that behave like radio buttons. Below is the code:

<form>

    <input type="checkbox" id="FirstBox" onclick="clickMe(this)" />Is this the first time, you are visiting this web site.
    <input type="checkbox" name="test" id="SecondBox"  onclick="interest(this) />Yes
    <input type="checkbox" id="ThirdBox" name="test"  onclick="interest(this) />No
  
    <button type="submit">Submit</button>
</form>

If the checkBox with id firstbox is clicked then user is required to click on either SecondBox or ThirdBox. SecondBox and ThirdBox
are behaving like a radio button with below code:

function interest(checkbox){

            var checkboxes = document.getElementsByName('test')
            checkboxes.forEach((item) => {
                if (item !== checkbox) item.checked = false
            })

            }

I want a required message to display when the user does not click on either Second or third checkbox. Below is what I tried to write:

function clickMe(fb)
    {
        var sb = document.getElementById("SecondBox");
        var tb = document.getElementById("ThirdBox");
        if(fb.checked == true{

            if (sb.checked == false && tb.ariaChecked == false)
            {
                Message saying that one of the check box is required right under the checkboxes.

            }
        }

    }

below is the screenshot:

enter image description here

any help will be appreciated.

WKWebView: elementFromPoint evaluateJavaScript not working

I’m trying to simulate a click at a specific point on a WKWebView, and found evaluateJavaScript’s elementAtPoint suited what I needed. However it wouldn’t operate correctly in my project — doing nothing besides printing error messages such as nil is not an element, so I tried to run it in a test project on various websites, where it also failed.

I’m using the following code (where the user activates the run action with a button):

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!
    
    @IBAction func run(_ sender: Any) {
        DispatchQueue.main.async { [self] in
            webView.evaluateJavaScript("document.elementFromPoint(219, 23).click();", completionHandler: { [self] (element, error) in
                if error != nil {
                    print(error)
                } else {
                }
            })
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.navigationDelegate = self
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        webView.load(URLRequest(url: URL(string: "https://theage.com.au")!))
        
    }
}

Can anyone spot the issue here? Am I missing a property change or something?

I’ve also linked the test project here (https://github.com/TheIntelCorei9/DOMTest) so you can see the issue in a bit more depth.

Thanks!

How does ID3 editors work under the hood? [closed]

I want to try making a ID3 metatag editor as a fun project using JavaScript, and Tauri. I know there are libraries out there, but I was wondering how it acturally works under the hood. I am between the range of a beginner and a indeterminate, so it’s hard for me to comprehend a lot of the code with my limited skill and experience. I just want to know the very basics of how they work, and possibly, how I can use JS to code it; if it is not too complicated.

I tried browsing YouTube, Reddit, and Google, but I cannot seem to find an explanation of how they acturally work. Some that I found were of other languages, which I do not understand.

Thanks in advance.

The button to update the ‘hp’ variable in my website works internally, but for some reason the javascript doesn’t update the footer on first click

app.py:

@app.route("/dealers", methods=["GET", "POST"])
@login_required
def dealers():
    if request.method == "POST":
        id = int(request.form['user_id'])

        #initialize rows with user data
        rows = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])

        # making sure user has enough hp
        if rows[0]["hp"] < 1:
            return jsonify({'success': False})
        
        # minus users hp and add dealers hp
        db.execute("UPDATE users SET hp = hp - 1, lucky = lucky + 1 WHERE id = ?", session["user_id"])
        db.execute("UPDATE users SET hp = hp + 1 WHERE id = ?", id)

        session["hp"] = rows[0]["hp"]
        hp = session["hp"]

        return jsonify({'success': True, 'hp': hp})
    else:
        return render_template("dealers.html")

@app.route("/players", methods=["GET", "POST"])
@login_required
def players():
    if request.method == "POST":
        id = int(request.form['user_id'])

        #initialize rows with user data
        rows = db.execute("SELECT * FROM users WHERE id = ?", session["user_id"])
        
        # minus users hp and add dealers hp
        db.execute("UPDATE users SET hp = hp - 10, lucky = lucky + 10 WHERE id = ?", session["user_id"])
        db.execute("UPDATE users SET bounty = bounty + 1 WHERE id = ?", id)

        session["hp"] = rows[0]["hp"]
        hp = session["hp"]

        return jsonify({'success': True, 'hp': hp})
    else:
        players = db.execute("SELECT * FROM users ORDER BY hp")
        # add OFFSET int for skipping first few users^
        
        return render_template("players.html", players=players)

script.js:

function tip(user_id) {
    $.ajax({
        type: 'POST',
        url: '/dealers',
        data: {'user_id': user_id},
        success: function(data) {
            if (data.success) {
                $("#dialog-message").dialog({
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $("#dialog-message").text("You have successfully tipped");
                setTimeout(function() {
                    $("#dialog-message").dialog("close");
                }, 4000); // close dialog after 5 seconds

                // update HP value in #value-container element
                if (data.hp !== undefined) {
                    $('#value-container').text("HP: " + data.hp);
                }
            } 
    });
}

function placeBounty(user_id) {
    $.ajax({
        type: 'POST',
        url: '/players',
        data: {'user_id': user_id},
        success: function(data) {
            if (data.success) {
                $("#dialog-message").dialog({
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog("close");
                        }
                    }
                });
                $("#dialog-message").text("You have successfully placed a bounty!");
                setTimeout(function() {
                    $("#dialog-message").dialog("close");
                }, 4000); // close dialog after 5 seconds 
                $('#value-container').html("HP: " + data.hp);
            } 

layout.html:


//some code
<footer>
    <div id="value-container"> HP: {{ session["hp"] }} </div>
</footer>

So, the variables are updated internally for every click of the button, as it should, but the footer only starts updating after the first click, and when I switch to the players page to place a “bounty”, the first click ends up decreasing the footer value by 1 (which should be the tipping function) and only decreasing the hp value by 10 after the first click. What might be the cause of this?

Stoping Propagation In JS REACT

I have a component that adds an item to a dashboard. I added a modal to the item to see more information. But when you click the modal it also adds the item to the dashboard. I tried to use e.stopPropagation() but that did not work.

For example I tried adding to const handleOpen = () => setOpen(true)

and onClick={handleOpen}

But no luck, the page crashes.

Any suggestions?

import { useState } from 'react'
import { AssetExport } from '../assets/AssetsExport'
import './styles.scss'
import { connect } from 'react-redux'
import { addComponent } from '../../../../redux/actions/app-actions'
import { TypeTag } from '../Tags/Tags'
import { CatagoryTag } from '../Tags/Tags'
import Modal from '@mui/material/Modal'

const Itemv3 = ({ item, openInfo, ...props }) => {
  const [open, setOpen] = useState(false)
  const handleOpen = () => setOpen(true)
  const handleClose = () => setOpen(false)
  const { title, description, isFavourite = false } = item

  const [expanded, setExpanded] = useState(false)
  const handleAddComponent = () => {
    const component = {
      // config: item,
      title: title,
      type: title,
      spec: { ticker: 'AAPL', state: {} },
      data: [],
    }

    props.addComponent(component)
  }

  const handleExpandItem = e => {
    setExpanded(!expanded)
  }

  return (
    <div className="Item1">
      <div className="ContainerTitle1" onClick={() => handleAddComponent()}>
        <div className="Item-Title1">{title}</div>
        <button onClick={handleOpen}>Preview</button>
      </div>
      <div className="ItemIconsContainer1">
        <TypeTag entry={item}></TypeTag>
        {item?.category && <CatagoryTag entry={item}></CatagoryTag>}
      </div>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <div className="item-modal-background">
          <div className="item-modal">
            <button onClick={handleClose}>Close</button>
            <div className="item-modal-title">{title}</div>
            <div className="item-modal-description">{description}</div>
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default connect(null, {
  addComponent,
})(Itemv3)

Using Javascript forEach second argument thisValue to do something

I am struggling to understand some Javascript code. Here the forEach statement provides a loop over each element found by querySelectorAll. It attaches an onclick response to each of these elements.

this.container.querySelectorAll('.some_class').forEach(element => {
            element.onclick = event => {                                        
                event.preventDefault();                                                                  
                element.querySelector('span').innerHTML = 'Clicked!';            
            };                                                                                                                   
            element.querySelector('span').innerHTML = 'Other value';                                                                        
        });

I am confused by the last part. Here, the second (optional) argument is provided to the forEach constructor. I read that this argument is called thisValue, and it assigns a value to the this keyword. But in this code example, we pass a statement instead of a value. (Of course the statement will evaluate to a value, but nothing useful.) It seems to execute the statement at the time that the forEach loop is run. Is this a correct usage of the thisValue argument?

I can´t toggle a class on an element

I was working on a project where i need to toggle on and off the class “off” of an element, whose class is “no-active-resources”, so it can “display: none”, but for some extrange reason I can’t manage to toggle on and off the class via my javascript code, I tried grabbing the element with “getElementByClassName” and “querySelector” but none seems to work, I also tried using the “add” and “remove” functions but it also didn’t work

Here’s the HTML code

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minecraft Menu Replica</title>
    <link rel="icon" href="../img/Minecraft-Launcher_Icon.png" type="image/x-icon">
    <link rel="stylesheet" href="../css/style.css">
    <script defer src="../javascript/main-menu.js"></script>
    <script defer src="../javascript/general-menu.js"></script>
    <script defer src="../javascript/avanzado-menu.js"></script>
    <script defer src="../javascript/multijugador-menu.js"></script>
    <script defer src="../javascript/cheats-menu.js"></script>
    <script defer src="../javascript/resourcePacks-menu.js"></script>
    <script defer src="../javascript/music.js"></script>
</head>
<body>
    <div id="side-b">
        <div class="menu off">
            <div class="menu-division resources-div">
                <div id="local-resources" class="resources-menus">
                    <ul class="grid-list">
                        <li class="no-active-resources resources-alerts">
                            <div class="coupling-div">
                                <p class="section-title">No hay ningun pack de recursos activo</p>
                                <p class="resources-desc">¿Quieres que tu mundo se vea diferente? Intenta activar un pack de recursos en "Disponibles".</p>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

Here’s the CSS code

.no-active-resources.off{
    display: none;
}
.no-active-resources>.coupling-div>.section-title{
    margin-bottom: 8px;
    margin-left: 0px;
}
.no-active-resources>.coupling-div>.resources-desc{
    display: block;
    color: #D0D1D4;
    font-size: 11.5px;
    margin-left: 0px;
}
.grid-list .no-active-resources{
    display: flex;
    align-items: center;
    border-top: 2px solid #1E1E1F;
    height: 72px;
    justify-content: center;
    background-color: #313233;
}

ANd here’s the JavaScript code

'use strict';
let resourcesSliders = document.querySelectorAll('.resources-slider')
let resourcesMenus = document.querySelectorAll('.resources-menus');
let resourcesOptions = document.querySelectorAll('.resources-option');
let grid_lists = document.querySelectorAll('.grid-list');
let list_positions = document.querySelectorAll('.list-position');
var noActiveResourcesAlert = document.querySelector('.no-active-resources')
let noActResAlSelector = 1;
var noInactiveResourcesAlert = document.querySelector('.no-inactive-resources');
let noInactResAlSelector = 0;
let resourcesSelector = 0;
let arrows;
let list_arrows;
let resourceAmount;
let activateElementBtn;
let deleteElementBtn;
let sharedPacksSelector = 0;
let reverseResourcePacks = [...resourcePacks].reverse();
let InactiveLocalResources = [];
let ActiveLocalResources = [];
let globalResources = [];

document.addEventListener('click', e=>{
    if(e.target==resourcesOptions[0] || e.target==resourcesOptions[0].firstElementChild){
        if(resourcesSelector>0){
            resourcesOptions[resourcesSelector].classList.toggle('clicked');
        }
        for(let i=0;i<resourcesMenus.length;i++){
            resourcesMenus[i].classList.toggle('off');
        }
        resourcesOptions[0].classList.toggle('clicked');
        resourcesSelector=0;
    }else if(e.target==resourcesOptions[1] || e.target==resourcesOptions[1].firstElementChild){
        if(resourcesSelector<1){
            resourcesOptions[resourcesSelector].classList.toggle('clicked');
            for(let i=0;i<resourcesMenus.length;i++){
                resourcesMenus[i].classList.toggle('off');
            }
        }
        resourcesOptions[1].classList.toggle('clicked');
        resourcesSelector=1;
    }else if(e.target==resourcesSliders[0].firstElementChild || e.target==resourcesSliders[0].lastElementChild.firstElementChild || e.target==resourcesSliders[0].lastElementChild.lastElementChild){
        if(sharedPacksSelector==0){
            resourcesSliders[0].firstElementChild.classList.toggle('clickedTwice');
            resourcesSliders[0].firstElementChild.classList.toggle('clickedOnce');
            sharedPacksSelector = 1;
        }
        else if(sharedPacksSelector==1){
            resourcesSliders[0].firstElementChild.classList.toggle('clickedOnce');
            resourcesSliders[0].firstElementChild.classList.toggle('clickedTwice');
            sharedPacksSelector = 0;
        }
    }
})

LoadResourcePacks();
arrows = document.querySelectorAll('.arrow');
list_arrows = document.querySelectorAll('.list-arrow');
resourceAmount = document.querySelector('.local-resource-amount');
activateElementBtn = document.querySelectorAll('.activate-element');
deleteElementBtn = document.querySelectorAll('.delete-element');
resourceAmount.textContent = `(${InactiveLocalResources.length})`;
console.log(noActiveResourcesAlert, noActiveResourcesAlert.classList, noInactiveResourcesAlert, noInactiveResourcesAlert.classList)

document.addEventListener('click', e=>{
    for(let i=0;i<arrows.length;i++){
        if(e.target==arrows[i]){
            if(arrows[i].dataset.open==0){
                let listElement;
                if(arrows[i].dataset.section==0){
                    listElement = arrows[i].parentElement.parentElement.parentElement.parentElement;
                }else if(arrows[i].dataset.section==1){
                    listElement = arrows[i].parentElement.parentElement.parentElement;
                }
                let desc = listElement.lastElementChild;
                let descHeight = desc.offsetHeight;
                descHeight += 64;
                listElement.style.height = `${descHeight}px`
                arrows[i].dataset.open = 1;
                arrows[i].textContent = '<';
            }else if(arrows[i].dataset.open==1){
                let listElement;
                if(arrows[i].dataset.section==0){
                    listElement = arrows[i].parentElement.parentElement.parentElement.parentElement;
                }else if(arrows[i].dataset.section==1){
                    listElement = arrows[i].parentElement.parentElement.parentElement;
                }
                let desc = listElement.lastElementChild;
                let listElementHeight = listElement.offsetHeight;
                let descHeight = desc.offsetHeight;
                listElementHeight -= descHeight;
                listElement.style.height = `${listElementHeight}px`
                arrows[i].dataset.open = 0;
                arrows[i].textContent = '>';
            }
        }
    }
})

document.addEventListener('click', e=>{
    for(let i=0;i<list_arrows.length;i++){
        if(e.target==list_arrows[i] || e.target==list_arrows[i].parentElement.parentElement){
            if(list_arrows[i].dataset.open==0){
                let listElement = list_arrows[i].parentElement.parentElement.parentElement;
                listElement.style.height = 'auto';
                listElement.style.marginBottom = '14px';
                list_arrows[i].dataset.open=1;
                list_arrows[i].textContent='<'
            }else if(list_arrows[i].dataset.open==1){
                let listElement = list_arrows[i].parentElement.parentElement.parentElement;
                listElement.style.height = '46px'
                listElement.style.marginBottom = '0px';
                list_arrows[i].dataset.open=0;
                list_arrows[i].textContent='>'
            }
        }
    }
});

document.addEventListener('click', e=>{
    for(let i=0;i<activateElementBtn.length;i++){
        if(e.target==activateElementBtn[i] || e.target==activateElementBtn[i].firstElementChild || e.target==activateElementBtn[i].lastElementChild){
            let listElement = activateElementBtn[i].parentElement.parentElement;
            ActivateElement(listElement.dataset.position);
            RemoveListElements();
            RearrangeLists();
        }
    }
})

document.addEventListener('click', e=>{
    for(let i=0;i<deleteElementBtn.length;i++){
        if(e.target==deleteElementBtn[i] || e.target==deleteElementBtn[i].firstElementChild || e.target==deleteElementBtn[i].lastElementChild){
            let listElement = deleteElementBtn[i].parentElement.parentElement;
            console.log(listElement.dataset.position);
            DeactivateElement(listElement.dataset.position);
            RemoveListElements();
            RearrangeLists();
        }
    }
})

function ActivateElement(position){
    for(let i=0;i<reverseResourcePacks.length;i++){
        if(InactiveLocalResources[i]==reverseResourcePacks[position]){
            InactiveLocalResources.splice(i,1);
            reverseResourcePacks[position].active=true;
            console.log(reverseResourcePacks[position], reverseResourcePacks[position].active)
            break;
        }
    }
}

function DeactivateElement(position){
    for(let i=0;i<reverseResourcePacks.length;i++){
        if(ActiveLocalResources[i]==reverseResourcePacks[position]){
            ActiveLocalResources.splice(i,1);
            reverseResourcePacks[position].active=false;
            console.log(reverseResourcePacks[position], reverseResourcePacks[position].active)
            break;
        }
    }
}

function RemoveListElements(){
    while(grid_lists[2].children.length>2){
        grid_lists[2].removeChild(grid_lists[2].lastChild);
    }
    while(grid_lists[1].children.length>0){
        grid_lists[1].removeChild(grid_lists[1].firstChild);
    }
    while(grid_lists[0].children.length>1){
        grid_lists[0].removeChild(grid_lists[0].lastChild);
    }
}

function RearrangeLists(){
    let active_count = 0;
    ActiveLocalResources = [];
    InactiveLocalResources = [];
    for(let i=0;i<reverseResourcePacks.length;i++){
        if(reverseResourcePacks[i].global){
            createGlobalListElement(reverseResourcePacks[i], i);
        }else if(reverseResourcePacks[i].active){
            active_count++
            ActiveLocalResources.unshift(reverseResourcePacks[i]);
            createActiveListElement(reverseResourcePacks[i], i, active_count)
        }else{
            InactiveLocalResources.unshift(reverseResourcePacks[i]);
            createLocalListElement(reverseResourcePacks[i], i)
        }
    }
    turnOnAndOffAlerts();
    arrows = document.querySelectorAll('.arrow');
    list_arrows = document.querySelectorAll('.list-arrow');
    resourceAmount = document.querySelector('.local-resource-amount');
    activateElementBtn = document.querySelectorAll('.activate-element');
    deleteElementBtn = document.querySelectorAll('.delete-element');
    resourceAmount.textContent = `(${InactiveLocalResources.length})`;
    console.log(activateElementBtn);
    console.log(deleteElementBtn);
    console.log(ActiveLocalResources);
    console.log(InactiveLocalResources);
}

function LoadResourcePacks(){
    let active_count = 0;
    for(let i=0;i<reverseResourcePacks.length;i++){
        if(reverseResourcePacks[i].global){
            globalResources.unshift(reverseResourcePacks[i]);
            createGlobalListElement(reverseResourcePacks[i], i);
        }else if(reverseResourcePacks[i].active){
            active_count++;
            ActiveLocalResources.unshift(reverseResourcePacks[i]);
            createActiveListElement(reverseResourcePacks[i], i, active_count);
        }else{
            InactiveLocalResources.unshift(reverseResourcePacks[i]);
            createLocalListElement(reverseResourcePacks[i], i);
        }
    }
    turnOnAndOffAlerts();
}

function turnOnAndOffAlerts(){
    if(InactiveLocalResources.length==0 && noInactResAlSelector==0){
        noInactiveResourcesAlert.classList.toggle('off');
        noInactResAlSelector=1;
        console.log("noInactiveResourcesAlert activated");
    }else if(InactiveLocalResources.length>0 && noInactResAlSelector==1){
        noInactiveResourcesAlert.classList.toggle('off');
        noInactResAlSelector=0;
        console.log("noInactiveResourcesAlert deactivated");
    }
    if(ActiveLocalResources.length==0 && noActResAlSelector==0){
        noActiveResourcesAlert.classList.toggle('off');
        noActResAlSelector=1;
        console.log("noActiveResourcesAlert activated");
    }else if(ActiveLocalResources.length>0 && noActResAlSelector==1){
        noActiveResourcesAlert.classList.toggle('off');
        noActResAlSelector=0;
        console.log("noActiveResourcesAlert deactivated");
    }
}

function createLocalListElement(object, count){
    grid_lists[2].innerHTML += `
    <li class="list-element" data-position="${count}">
        <div class="inline-list-element">
            <div class="list-option">
                <img src=${object.img}>
                <p>${object.name}</p>
                <span>
                    <p class="arrow" data-open="0" data-section="0">></p>
                </span>
            </div>
            <div class="activate-element">
                <img src="../img/activate-resource-icon.png">
                <p>Activar</p>
            </div>
        </div>
        <div class="element-description">
            <p>${object.description}</p>
        </div>
    </li>`;
}

function createActiveListElement(object, count, listPosition){
    if(object.config){
        grid_lists[0].innerHTML += `
        <li class="list-element" data-position="${count}">
            <div class="inline-list-element">
                <div class="element-grab">
                    <img src="../img/element-grab-icon.png">
                    <p class="list-position">${listPosition}</p>
                </div>
                <div class="list-option active">
                    <img src=${object.img}>
                    <p>${object.name}</p>
                    <span><p class="arrow" data-open="0" data-section="0">></p></span>
                </div>
                <div class="element-config">
                    <img src="../img/resource-config-icon.png">
                    <p>Config</p>
                </div>
                <div class="delete-element">
                    <img src="../img/delete-resource-icon.png">
                    <p>Eliminar</p>
                </div>
            </div>
            <div class="element-description">
                <p>${object.description}</p>
            </div>
        </li>`
    }else{
        grid_lists[0].innerHTML += `
        <li class="list-element" data-position="${count}">
            <div class="inline-list-element">
                <div class="element-grab">
                    <img src="../img/element-grab-icon.png">
                    <p class="list-position">${listPosition}</p>
                </div>
                <div class="list-option no-config">
                    <img src=${object.img}>
                    <p>${object.name}</p>
                    <span><p class="arrow" data-open="0" data-section="0">></p></span>
                </div>
                <div class="delete-element">
                    <img src="../img/delete-resource-icon.png">
                    <p>Eliminar</p>
                </div>
            </div>
            <div class="element-description">
                <p>${object.description}</p>
            </div>
        </li>`
    }
}

function createGlobalListElement(object, count){
    grid_lists[1].innerHTML += `
    <li class="list-element" data-position="${count}">
        <div class="list-option">
            <img src=${object.img}>
            <p>${object.name}</p>
            <span><p class="arrow" data-open="0" data-section="1">></p></span>
        </div>
        <div class="element-description">
            <p>${object.description}</p>
        </div>
    </li>`
}

Also sorry if my English is bad, I’m still learning.

I was expecting the element to disspaear after another “li” element was added to the “ul” list and for the element to re-appear after all other “li” elements were gone

add coustom class by index in jQuery

As someone new to JS and jQuery, I’m working on a table with multiple columns that contain numbers, except for the last one which has text. My goal is to first add the “custom-sortable” class to all elements in the last column that include the word “Camp”, and then add the “custom-sortable” class to all elements in the entire table where the last column contains “Camp”. I’ve tried different approaches, but haven’t had success. My latest idea is to use the index of elements in the last column that include the word “Camp”. Any help or hints would be appreciated.

$(document).ready(function() {
            var targetIndex = -1;
            $('.custom-sortable .rank-list-item').each(function(index) {
            if ($(this).text() === 'Camp') {
            targetIndex = index;
            $(this).addClass('custom-sortable rank-list-item-Camp');
        }
        });
        if (targetIndex >= 0) {
        $('.custom-sortable .rank-list-item').eq(targetIndex).addClass('custom-sortable');
        }
        });

React router 6 not displaying correct route, how to fix?

I am making routes with react router 6 so old stack post arent helpful to me I tried. The parent route / is diplaying on all routes no matter what. exact dosent work, and ordering the other routes (* and /today) before / dosent work. It still shows the / route no matter what


   <Routes>
    //route /
   <Route path='/' element={
   <>
    <BasicSocketContext.Provider value={{socket,UserName,setUserName,selectedpfp,updatepfp,globalpfp,updateglobalpfp}}>
   {UserName === "" || null || undefined && globalpfp === "" || null || undefined ? <Login/> : <Testhi/>}
   </BasicSocketContext.Provider>
   </>
   }/>

   //Route error
   <Route path='*' element={<><h1>its not there bro</h1></>}/>
   <Route path='/today' element={<><h1>Today</h1></>}/>

   </Routes>

if it helps i am using hash router

onAuthRequired in chrome extension

I am currenlty trying to catch the auth-request from a proxy and either fill the credentials, or post a notification to the user and cancel the request.

Currently my code looks like this


function provideCredentialsAsync(details) {
    return new Promise(resolve => {
        const key = details.challenger.host;
        console.log(key)
        chrome.storage.session.get([key], function (items) {
            if (chrome.runtime.error || !(key in items)) {
                chrome.notifications.create({
                    type: 'basic',
                    iconUrl: '../assets/logo128.png',
                    title: 'Credentials not found',
                    message: 'Credentials not found for ' + details.challenger.host + '. Please add them in the extension options. The proxy usage will be cancelled.',
                }, function(notificationId) {
                    console.log('Notification created with ID:', notificationId);
                });
                resolve({cancel: true});
            }
            else resolve({authCredentials: items[key]});
        });
    });
}

chrome.webRequest.onAuthRequired.addListener(
    provideCredentialsAsync,
    { urls: ["<all_urls>"] },
    ["blocking"]
);

Unfortunatelly the extension neither cancels the auth request nor fills the data if i provide them to the session storage. Alternativelly I had this function to handle the session storage prepared, but even if using it, i could make the code work

function sessionGet(key) {
    return new Promise(resolve => {
        chrome.storage.session.get([key], function (items) {
            if (chrome.runtime.error || !(key in items)) resolve(undefined);
            // if (chrome.runtime.error || !(key in items)) resolve({cancel: true});
            else resolve(items[key]);
        });
    });
}

Do you please have any idea on how to fix this ? I tried following the documentation, but so far I haven’t been very lucky 🙁

WebSocket connections failing on GCloud server

I’m running a Node server using Express and socket.io on Google Cloud. The page loads but the connection to the server gets refused immediately. I suspect I either have to configure my environment to allow a connection to that URL, which I’m sure on how to do, or I have to locally download socket.io.

server.js

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const fs = require("fs");

async function getCount() {
    return new Promise((resolve, reject) => {
        fs.readFile("count.json", (err, data) => {
        if (err) {
            reject(err);
        } else {
            const count = JSON.parse(data).count;
            resolve(count);
        }
        });
    });
}

async function writeCount(count) {
    const data = {
        count: count
    };

    return new Promise((resolve, reject) => {
        fs.writeFile("count.json", JSON.stringify(data), (err) => {
        if (err) {
            reject(err);
        } else {
            resolve();
        }
        });
    });
}


app.use(express.static("public"));

io.on("connection", (socket) => {
    socket.on("error", console.error);

    getCount().then(count => {
        io.emit("init", count);
    }).catch(err => {
        console.log(err);
    })

    socket.on("serversync", (receivedSync) => {
        console.log("received " + receivedSync);
        if (receivedSync >= 120) {
            console.log("not using " + receivedSync);
            return;
        }
        
        getCount().then(count => {
            let total = count + parseInt(receivedSync);
            io.emit("clientsync", total);
            writeCount(total);
        }).catch(err => {
            console.log(err);
        })
    });
});

app.get("/init", (req, res) => {
    let files = fs.readdirSync("./public/audio");
    res.json([files]);
})

const PORT = process.env.PORT || 8080;

server.listen(PORT, () => {
    console.log(`Listening on port ${PORT}.`);
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Kalam:wght@700&display=swap" rel="stylesheet">
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <link rel="stylesheet" href="css/index.css">
  </head>
  <body class="center">
    <div>
      <h1 id="global"></h1>
      <h2 id="globalText">Global Pikas</h2>
    </div>

    <div>
      <img id="buttonImg" src="images/button.gif" alt="Pika" onclick="onClick()">
    </div>  

    <div id="counterDiv">
      <h3 id="counter">0</h3>
      <h4 id="counterText">Times Pika'd</h4>
    </div>

    <script src="js/index.js"></script>
    <script src="js/animator.js"></script>
  </body>
</html>

Errors

My p5.js Drawing app is not functioning probably on chrome, but it works fine in all other browsers

My P5.js drawing application used to work fine in Chrome previously, but now I can’t use any of the tools in the sidebar at all. I have updated my p5.min library to the newest version, but the problem still exists.

I also got this uncaught type error in my code that does not show up in any other browser when I run it live.
here are the screenshots for it
[[enter image description here](https://i.stack.imgur.com/yEglY.png)](https://i.stack.imgur.com/xbzSk.png)

this drawing app template is an old p5.js templete, so the firt thing i did was to update the library,but nothing changed, i also double-checked the bug in the code and rewrote the whole section again