I am trying to share a TamperMonkey script and I don’t want them to share it with their friends, how can I do that?

I was wondering if you can share a TamperMonkey script to only certain people if you get their fingerprint so they can’t share the script with anyone else. Is it possible?

I’ve done researching and asked other people and no where on the internet gives me a hint to know where to start from on a Tampermonkey script. I need help.

I can’t toggle on/off a class name from an element, What am I doing wrong?

I was working on a project where I need to toggle on/off the class name “off” of two elements but for some reason I can’t manage to do it via JavaScript, and I know that css is not the problem because if I do it manually it works, so I can’t seems to find the problem in my code…

Here’s the HTML code

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
    <link rel="stylesheet" href="style.css">
    <script defer src="javascript.js"></script>
</head>
<body>
    <div id="side-b">
        <div class="menu">
            <div class="menu-division">
                <p>First List</p>
                <div id="local-resources">
                    <ul class="grid-list">
                        <li class="no-active-resources">
                            <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 class="menu-division">
                <p>Second List</p>
                <div id="inactive-local-resources">
                    <ul class="grid-list">
                        <li class="no-inactive-resources off">
                            <div class="coupling-div">
                                <p class="section-title">Ya activaste todos los packs</p>
                                <p class="resources-desc">Ya se activaron todos tus packs. ¡Obten más packs en el mercado o en línea!</p>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>  
    </div>
</body>
</html>

Here’s the CSS code

*{
    margin: 0;
    padding: 0;
    font-size: 15px;
    font-family: cursiva;
}
#side-b{
    display: flex;
    position: fixed;
    top: 64px;
    left: 476px;
    right: 53px;
    width: 857px;
    height: 89.63%;
    overflow-y: auto;
    overflow-x: hidden;
}
.menu{
    color: white;
    display: block;
    width:837px;
    height: fit-content;
    background: #48494A;
    border: 2px solid #1E1E1F;
    z-index: 1;
}
.menu-division{
    padding: 14px 24px 14px 24px;
    border-bottom: 2px solid #333334;
    border-left: none;
    border-right: none;
    border-top: 2px solid #5A5B5C;
}
.coupling-div{
    display: block;
    text-align: center;
}
.no-active-resources>.coupling-div>.section-title, .no-inactive-resources>.coupling-div>.section-title{
    margin-bottom: 8px;
    margin-left: 0px;
}
.resources-desc{
    display: block;
    color: #D0D1D4;
    font-size: 11.5px;
    margin-left: 0px;
}
#local-resources{
    display: grid;
    grid-template-columns: 600px;
    grid-template-rows: auto;
    grid-template-areas:
    "grid-list grid-list";
    margin-bottom: 7px;
}
.grid-list{
    grid-area: grid-list;
    display: block;
    height: auto;
    border: 2px solid #1E1E1F;
    border-top: none;
    list-style: none;
}
.grid-list .list-element{
    height: 64px;
    overflow-y: hidden;
}
.grid-list .list-element>.inline-list-element{
    display: flex;
    align-items: center;
}
.grid-list .list-element>.inline-list-element>.element-grab, .grid-list .list-element>.inline-list-element>.element-config, .grid-list .list-element>.inline-list-element>.activate-element, .grid-list .list-element>.inline-list-element>.delete-element{
    cursor: pointer;
    display: flex;
    align-items: center;
    padding: 7px 8px 7px 8px;
    height: 48px;
    border-top: 2px solid #1E1E1F;
    background-color: #48494A;
    box-shadow: inset 2px 2px rgba(255, 255, 255, .1), inset -2px -2px #333334;
}
.grid-list .list-element>.inline-list-element>.element-grab:hover, .grid-list .list-element>.inline-list-element>.element-config:hover, .grid-list .list-element>.inline-list-element>.activate-element:hover, .grid-list .list-element>.inline-list-element>.delete-element:hover, .grid-list .list-element>.list-option:hover, .grid-list .list-element>.inline-list-element>.list-option:hover{
    background-color: #58585A;
}
.grid-list .list-element>.inline-list-element>.activate-element>p, .grid-list .list-element>.inline-list-element>.delete-element>p{
    user-select: none;
    margin-top: 3px;
    font-size: 8px;
}
.grid-list .list-element>.inline-list-element>.element-config, .grid-list .list-element>.inline-list-element>.activate-element, .grid-list .list-element>.inline-list-element>.delete-element{
    flex-direction: column;
    padding: 7px 14px 7px 14px;
}
.grid-list .list-element>.inline-list-element>.element-config>img{
    user-select: none;
    margin-top: 10px;
}
.grid-list .list-element>.inline-list-element>.activate-element>img, .grid-list .list-element>.inline-list-element>.delete-element>img{
    user-select: none;
    margin-top: 5px;
}
.grid-list .list-element>.inline-list-element>.element-config>p{
    user-select: none;
    margin-top: 3px;
    font-size: 10px;
}
.grid-list .list-element>.inline-list-element>.element-grab>p{
    user-select: none;
    margin-left: 5px;
    font-size: 13px;
}
.grid-list .list-element>.inline-list-element>.list-option, .grid-list .list-element>.list-option{
    display: flex;
    align-items: center;
    padding: 7px 8px 7px 8px;
    height: 48px;
    border-top: 2px solid #1E1E1F;
    background-color: #48494A;
    box-shadow: inset 2px 2px rgba(255, 255, 255, .1), inset -2px -2px #333334;
}
.grid-list .list-element>.inline-list-element>.list-option>img{
    user-select: none;
    height: 48px;
    width: 48px;
}
.grid-list .list-element>.inline-list-element>.list-option>p{
    user-select: none;
    margin-left: 8px;
    width: 660px;
}
.grid-list .list-element>.inline-list-element>.list-option.active>p{
    user-select: none;
    width: 573px;
}
.grid-list .list-element>.inline-list-element>.list-option.no-config>p{
    user-select: none;
    width: 628px;
}
.grid-list .list-element>.list-option>p{
    user-select: none;
    margin-left: 8px;
    width: 689px;
}
.grid-list .list-element>.list-option>span, .grid-list .list-element>.inline-list-element>.list-option>span, .grid-list .list-opener>span{
    display: flex;
    transform: rotate(100grad);
    height: 48px;
    width: 48px;
}
.grid-list .list-element>.list-option>span>p, .grid-list .list-element>.inline-list-element>.list-option>span>p, .grid-list .list-opener>span>p{
    user-select: none;
    cursor: pointer;
    text-align: center;
    line-height: 48px;
    width: 48px;
}
.grid-list .element-description{
    height: auto;
    padding: 16px 12px 16px 12px;
    border-top: 2px solid #1E1E1F;
    background-color: #313233;
}
.grid-list .element-description>p{
    user-select: none;
    font-size: 13px;
}
.grid-list .no-active-resources, .grid-list .no-inactive-resources{
    display: flex;
    align-items: center;
    border-top: 2px solid #1E1E1F;
    height: 72px;
    justify-content: center;
    background-color: #313233;
}

.no-active-resources.off, .no-inactive-resources.off{
    display: none;
}

And here’s the JavaScript code

let grid_lists = document.querySelectorAll('.grid-list');
let list_positions = document.querySelectorAll('.list-position');
let noActiveResourcesAlert = document.querySelector('.no-active-resources')
let noInactiveResourcesAlert = document.querySelector('.no-inactive-resources')
let noActResAlSelector = 1;
let noInactResAlSelector = 0;
let InactiveLocalResources = [];
let ActiveLocalResources = [];
let resourcePacks = [
    {
        img: '../img/minecraft-resource-pack-icon.png',
        name: 'Pack de textura de Minecraft',
        description: '¡Los graficos prdeterminados de Minecraft, actualizados con nuevas texturas modernas!',
        config: false,
        active: true
    },
    {
        img: '../img/3d-items-icon.png',
        name: '- 3D Items v6 | Subpacks!! -',
        description: 'Laterns,Torchs,Campfires and More items 3D | By Hirx's',
        config: true,
        active: true
    },
    {
        img: '../img/faithful-icon.png',
        name: 'Faithful 32x - July 2022 Pre-release',
        description: 'The go-to 32x texture pack for Minecraft. Now for Bedrock Edition',
        config: false,
        active: false
    },
    {
        img: '../img/improv-default-icon.png',
        name: 'Improved Default Textures v9.1 1.19',
        description: 'Bedrock 1.19 v9.1 - Simple textures tweaks to improve some of Minecraft's rough or bland textures! B/LG and NEW dark UI settings available via subpacks. Made by IonicXHaze!',
        config: true,
        active: false
    },
    {
        img: '../img/js-legacy-icon.png',
        name: 'Jonh Smith Legacy Bedrock 1.19.50',
        description: '32x32 Textures by JimStoneCraft',
        config: false,
        active: false
    },
    {
        img: '../img/paper-cut-out-icon.png',
        name: 'Paper Cut-Out 1.19 -0.7 Texture bedrock',
        description: 'java by superalgae MCPE by @chengzzi89',
        config: false,
        active: false
    },
    {
        img: '../img/pollacius-icon.png',
        name: 'Pollacius v1.9.0',
        description: 'Vibrant and boxy. by CheezLordy',
        config: false,
        active: false
    },
]
let reverseResourcePacks = [...resourcePacks].reverse();
LoadResourcePacks();
let arrows = document.querySelectorAll('.arrow');
let activateElementBtn = document.querySelectorAll('.activate-element');
let deleteElementBtn = document.querySelectorAll('.delete-element');

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<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;
            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;
            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;
            break;
        }
    }
}

function RemoveListElements(){
    while(grid_lists[0].children.length>1){
        grid_lists[0].removeChild(grid_lists[0].lastChild)
    }
    while(grid_lists[1].children.length>1){
        grid_lists[1].removeChild(grid_lists[1].lastChild)
    }
}
function RearrangeLists(){
    let active_count = 0;
    ActiveLocalResources = [];
    InactiveLocalResources = [];
    for(let i=0;i<reverseResourcePacks.length;i++){
        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');
    activateElementBtn = document.querySelectorAll('.activate-element');
    deleteElementBtn = document.querySelectorAll('.delete-element');
}

function LoadResourcePacks(){
    let active_count = 0;
    for(let i=0;i<reverseResourcePacks.length;i++){
        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;
    }else if(InactiveLocalResources.length>0 && noInactResAlSelector==1){
        noInactiveResourcesAlert.classList.toggle('off');
        noInactResAlSelector=0;
    }
    if(ActiveLocalResources.length==0 && noActResAlSelector==0){
        noActiveResourcesAlert.classList.toggle('off');
        noActResAlSelector=1;
    }else if(ActiveLocalResources.length>0 && noActResAlSelector==1){
        noActiveResourcesAlert.classList.toggle('off');
        noActResAlSelector=0;
    }
}

function createLocalListElement(object, count){
    grid_lists[1].innerHTML += `
    <li class="list-element" data-position="${count}">
        <div class="inline-list-element">
            <div class="list-option">
                <p>${object.name}</p>
                <span>
                    <p class="arrow" data-open="0" data-section="0">></p>
                </span>
            </div>
            <div class="activate-element">
                <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">
                    <p class="list-position">${listPosition}</p>
                </div>
                <div class="list-option active">
                    <p>${object.name}</p>
                    <span><p class="arrow" data-open="0" data-section="0">></p></span>
                </div>
                <div class="element-config">
                    <p>Config</p>
                </div>
                <div class="delete-element">
                    <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">
                    <p class="list-position">${listPosition}</p>
                </div>
                <div class="list-option no-config">
                    <p>${object.name}</p>
                    <span><p class="arrow" data-open="0" data-section="0">></p></span>
                </div>
                <div class="delete-element">
                    <p>Eliminar</p>
                </div>
            </div>
            <div class="element-description">
                <p>${object.description}</p>
            </div>
        </li>`
    }
}

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

What I wanted to happen is that when any of the two lists had more than one element, the elements with classes “no-active-resources” and “no-inactive-resources” would disappear, but when they didn’t have more than one they would reappear.

Ranking an array of numbers [closed]

The following block of code (JavaScript) is the solution of a Ranking function which accepts an array of numbers and returns an array of their ranks. Could anybody clearly explain how it works ?

function rankingSystem(arr) {
    return arr.map((x, y, z) => z.filter(w => w > x).length + 1);
}
 

Mongodb faster execution for $in

I have two mongodb collections:
1). First collection is: sourcequeuemanualupload . It contains all records with statuses either Unworked or Assigned. This contains records when data is uploaded. Example of one of the Assigned item record in DB:

{
        "_id" : ObjectId("63e0e46a6047d75b9c20d8ec"),
        "Properties: Name" : "Hangman - Guess Words",
        "Appstore URL" : "https://itunes.apple.com/app/id1375993101?hl=None",
        "Region" : "na",
        "Create Date" : "na",
        "AHT" : "1",
        "sourceId" : "63e0e3719b4f812ba5333a31",
        "type" : "Manual",
        "uploadTime" : "2023-02-06T11:28:42.533+0000",
        "status" : "Assigned",
        "batchId" : "63e0e3719b4f812ba5333a31_746f22e4319b4d81b8ab255f5e653c2c_612023112842"
}

2). Second collection is queuedata. It contains the data(questions, responses user takes on tool) for items(from sourcequeuemanualupload collection) worked upon and they are all saved in this collection with a status of Completed. The _id of the record in sourcequeuemanualupload is stored here as “id” field as an identifier. Example of completed item:

{
        "_id" : ObjectId("63e0e4b19b4f812ba5333a34"),
        "templateId" : "63e0e28e9b4f812ba5333a30",
        "id" : "63e0e46a6047d75b9c20d8ec",
        "moderator" : "kodaga",
        "startTime" : "2023-02-06T11:29:46.048Z",
        "endTime" : "2023-02-06T11:29:52.438Z",
        "status" : "Completed",
        "AHT" : NumberLong(6),
        "userInput" : [
                {
                        "question" : "Is the URL leading to the desired store page link?",
                        "response" : "yes"
                },
                {
                        "question" : "Comments, if any.",
                        "response" : "test 1"
                }
        ]
}

There was a mistake made by the DBA initially as he did not update the status of Assigned items that were completed to Completed in sourcequeuemanualupload collection. So the Assigned items are left as Assigned itself. We are working on a fix for this to mark all the Assigned items(that have been worked upon) to Completed.

Volume of data currently:

> db.sourcequeuemanualupload.count()
414781

> db.sourcequeuemanualupload.count({"status":"Assigned"})
306418

> db.queuedata.count()
298128

Script I have written currently to identify the completed records and mark them as completed:


var assigned_tasks_arr = []

db.sourcequeuemanualupload.find({"status":"Assigned"}).forEach(function(rec){
    assigned_tasks_arr.push(rec._id.str);
});

print(assigned_tasks_arr.length)
> 306418

db.queuedata.count({id: {$in: assigned_tasks_arr}, "status":"Completed"})     <------------- STEP 1

var completed_items = db.queuedata.find({id: {$in: assigned_tasks_arr}, "status":"Completed"},{_id:0,id:1}).toArray();       <------------- STEP 2

var completed_items_ids = []

completed_items.forEach(function(rec){
    completed_items_ids.push(rec.id)
})

var completed_items_unique_objectid = []

completed_items.forEach(function(item){
    completed_items_unique_objectid.push(new ObjectId(item));
});

db.sourcequeuemanualupload.updateMany({_id:{$in: completed_items_unique_objectid}}, {$set:{"status":"Completed"}})  <------------- STEP 3

Basically, I fetch all the _ids of Assigned status items from sourcequeuemanualupload collection and store them in an array. Next to find if they actually have been completed and record is present in queuedata, I perform a search using $in and assigned_tasks_arr to get the actually completed items. Once i get the completed ids list, i would like to go ahead and update the statuses in sourcequeuemanualupload.

However, my STEP 1 and STEP 2 are taking>30 minutes for execution. It must be taking more than an hour or longer(but i could not get exact time as my session got terminated). I think the $in with array find query execution takes (N*log(M)), where N is the length of input array and M is the size of the collection. As you see my value of N is in millions and M is also in millions, this query will take a longer time. How do i optimize this query or write a faster query to find the ids and update at once?

I need help with faster execution of STEP 1, STEP 2 and STEP 3 in above script so that I dont have to wait for hours. Can we write a better join query here or any other way to optimize the query?

Thanks

I tried searching online for faster ways to optimize. I added index as ‘id’ to queuedata collection but it is still taking a long time 🙁
Need help for the above query

NOTE: using AWS documentDB 4.0.0 as if you are providing any suggestions on query , please check link: https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html as some commands are not supported

react page doesn’t load on ubuntu but does on local wsl

I’m having a strange issue where code that works perfectly on my local and runs without any issues doesn’t work on an ubuntu server

When running npm start, my local shows “Compiled successfully!” while the server shows “Compiled with warnings.” and a whole laundry list of issues

The console of my local shows nothing, no errors. The server shows all of the following errors:
errors

None of these errors are present on my local

Things I’ve tried:

  1. I made sure both node versions were on their latest (18.x)
  2. All packages are up to date and installed

I’m simply lost as to what the solution would be

Can’t get the list of items from a axios request

I’m trying to get the list of the items (pokemon) from the api using axios, and map to return just the name of the pokemon, but I just get the Promise, I have no idea what I’m doing wrong.

import axios from "axios";

class Pokemon {
    async all() {
        try{
            const response = await axios.get("https://pokeapi.co/api/v2/pokemon?limit=9")
            return await response.data.results.map(item => item.name)
        }catch (error){
            console.log(error);
        }
    }
}

const pokemon = new Pokemon
const listPokemon = pokemon.all();
console.log(listPokemon); // Promise { <pending> }

Javascript – Scans Text Corresponding to a Certain Label

I have the text below:

This is a code update

* Official Name:  Noner


* Pub: https://content.upcodes.co/viewer/washington/wa-mechanical-code-2021

* Agency:  Agency Ni

* Reference: 

https://web.archive.org/web/20230226234118/https://lawfilesext.leg.wa.gov/law/wsr/agency/BuildingCodeCouncil.htm

https://web.archive.org/web/20230303022030/https://lawfilesext.leg.wa.gov/law/wsr/2023/02/23-02-055.htm (#1)

* Citation: WAC 51-52 / WSR 23-02-055

* Draft Doc Title: 

 WSR 23-02-055 (#1)

* Draft Source Doc: https://web.archive.org/web/20230303022030/https://lawfilesext.leg.wa.gov/law/wsr/2023/02/23-02-055.htm (#1)

* Draft Drive: https://drive.google.com/file/d/1pYmwQS3t-ZX-Vyg9yBabtIpXZ7By2G6f/view?usp=share_link ( #1)

* Final Doc Title: 

   IECC Com Update(#1)

   IECC Res Update (#2)

   IECC Res Update (#3)

* Final Source Doc: 
  https://web.archive.org/web/20230303022130/https://apps.leg.wa.gov/wac/default.aspx?cite=51-52&full=true&pdf=true (#1)
 https://web.archive.org/web/20230303022030/https://lawfilesext.leg.wa.gov/law/wsr/2023/02/23-02-055.htm (#2)

* Final Drive: https://web.archive.org/web/20230303022130/https://apps.leg.wa.gov/wac/default.aspx?cite=51-52&full=true&pdf=true (#1)

https://web.archive.org/web/2023030302fdfdfg2130/https://apps.legfdg.gov/wac/default.aspx?cite=51-52&fdsfullfdsf=true&pfdsfdf=true  (#2)

* Effective Date: January 4, 2023

I want to extract the information corresponding to the tag ‘Reference:’ but the code below only gives me one line. I want to scan all text until it encounters the asterisk symbol.

//Extract Reference    
var reference = description.search("Reference:");
if(reference != -1){
  reference = description.match(/(?<=^* References*:)[s]*[n]*[^nr]*/m);  
  reference  = reference?.[0].trim();   
}else{
  reference = '';
}
console.log('Reference: ' + reference);

Como puedo incluir una imagen desde la carpeta public con alpine.js y Laravel? [closed]

Estoy elaborando un sistema de reservas con Laravel y alpine.js. Necesito mostrar al usuario la información de los psicólogos que están disponibles para reservar la cita de acuerdo al tipo de terapia que los usuarios seleccionaron. Para eso estoy usando el evento @click para llamar a una función que vaya a consultar la tabla de psicologos en la base de datos de acuerdo al valor de la propiedad “tipo_terapia_id”.
Para consultar utilizo la función fetch que en mi caso envía un parámetro a la función controladora para buscar al terapeuta de acuerdo al parámetro seleccionado. La consulta se hace correctamente. La respuesta del controlador es retornada a la instancia de alpine, donde la coloco en un array llamado especialistas (que ahora contendrá los datos del especialista), y luego desde mi vista recorro dicho array con la etiqueta El problema es que entre los datos que necesito mostrar del especialista está una imagen que debo mostrar. Estoy intentando usar la etiqueta img de la siguiente forma pero de esa manera no me ubica la imagen en la carpeta public. Hay alguna forma de utilizar el helper asset de laravel o algo equivalente para buscar la imagen en la carpeta correcta? Les voy a dejar la función de alpine y mi parte de blade donde estoy intentando mostrar la imagen

/*Funcion de alpine.js, es llamada por el evento @click del boton "seleccionar tipo de terapia".*/

            seleccionarespecialista(){
                var especialistaEnTerapia= this.tipo_terapia_id;

                fetch(`seleccionar_especialista/${especialistaEnTerapia}`).
                then(r => r.json()).
                then((data) => {
                    this.especialistas= data
                    console.log(this.especialistas[0])
                }).catch()
            },

/*Así intento recorrer el array para mostrar los datos del especialista incluyendo su foto*/

 <template x-for="especialista in especialistas" :key="especialista.id">
     <tr>
        <td>
           <a href="#" @click="formData.especialista='especialista.personal_info.name'">
              <img :src="especialista.photo" alt=""> <!-- No localiza la imagen en la carpeta public-->
           </a>
           <i><h4 x-text="especialista.personal_info.name"></h4></i>
        </td>
     </tr>
</template>

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?