Mongoose best way to store a set of ids in a document? Map? Array?

I have a table Entries where each document represents a list entry. Among other info, I want to store a set of id‘s in each document. These id‘s will be strings. The relevant id‘s needed will vary between different documents. When these documents are retrieved, the goal is to be able to efficiently display the entries in a React table and filter by the id‘s each document has, which seems like would make the most sense as a javascript Set.

Example of what I’m thinking of:

{
  name: "Bob",
  ids: {
    "1234a",
    "9999b"
  }
},
{
  name: "Paul",
  ids: {
    "9999b",
    "0000z"
  }
}

From reading around, it looks like I could potentially store ids as an Array, and convert them to a Set when retrieved.

Another options seems to be to store ids as a Map, where the key is the id and the value is something arbitrary (like true or something). Example:

{
  name: "Paul",
  ids: {
    "9999b": true,
    "0000z": true
  }
}

What would be the most performant way to do this?

json_encode() Data Being Automatically Converted Into A Javascript Object Without JSON.parse() Being Used

I have some PHP and JavaScript that works by PHP updating a MySQL database, and then outputting the updated code back onto the page without a hard refersh using the JavaScript fetch() method. This code works, but there is a part I don’t understand — why is it when the json_encode() PHP method is used, which converts the data to a JSON string, when it is then used in the JavaScript it is automatically being converted into a JavaScript object without JSON.parse() being used?

In the Javascript when I use JSON.parse() it understandly throws an error, because the data isn’t a string (which initially caused some confusion), when I console log the json variable being used in the JavaScript it does indeed return a JavaScript object where I can access its properties and methods etc.

There is no other JSON or json_encode() being used on the page (or indeed the site).

Also in the PHP script it echoes the JSON with echo json_encode($board_row); when the data is fetched from the database, before any HTML content is outputted. When I try and echo this in the HTML to see the value of json_encode($board_row); it just outputs the word false. I don’t understand what is going on there either?

If I manually add a simply array into the HTML such as $arr = array('a' => 1, 'b' => "hello", 'c' => null); and then echo that in the HTML with echo json_encode($arr); as excepted it outputs a JSON string.

If someone could kindly explain why this is happening, that would be wonderful.

PHP

if (isset($_POST['submit-board-name'])) {

    $create_board_name = $_POST['create-board-name'];
    
    try {
        // insert into database
        $createBoardSQL = "
            INSERT INTO boards (board_name, user_id) 
            VALUES (:board_name, :user_id )
        ";
    
        $bstmt = $connection->prepare($createBoardSQL);
        $bstmt->execute([
            ':board_name' => $create_board_name,
            ':user_id' => $db_id
        ]);

        // ----- fetch as JSON
        if(isset($_POST['json_response'])) {
            $board_stmt = $connection->prepare("
                SELECT * FROM `boards` WHERE `user_id` = :user_id 
                AND `board_name` = :board_name 
                ORDER BY `board_id` DESC");

            $board_stmt -> execute([
                ':user_id' => $db_id,
                ':board_name' => $create_board_name
            ]); 

            $board_row = $board_stmt->fetch();

            header('Content-type: application/json');
            echo json_encode($board_row);
            exit;
        }

    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

JavaScript

let boardModuleForm = document.querySelector('.board-module-form');

// URL details
let myURL = new URL(window.location.href),
pagePath = myURL.pathname;

if (boardModuleForm) {
    boardModuleForm.addEventListener('submit', function (e) {
    if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
            e.preventDefault();

            var formData = new FormData(this);

            formData.set(e.submitter.name, e.submitter.value);
            formData.set('json_response', 'yes');

            fetch (pagePath, {
                method: 'post',
                body: formData
            })
            .then(function(response) {

                if (response.status === 200) {
                    response.json().then(function(json){
                        
                        const newBoardName = json.board_name,
                        boardId = json.board_id;
                            
                        const newButton = `
                        <button name="board-name" type="submit">
                            <span>${newBoardName}</span>
                            <span style="margin:0" class="add-icon flex">+</span>
                        </button>
                        <input class="board-id-value" type="hidden" value="${boardId}">
                        `
                        // add new button from above onto page
                        document.querySelector('.board-list').insertAdjacentHTML('afterbegin', newButton);
                    
                    });

                }

            })
            .catch(function(error) {
                console.error(error);
            })

        }

    })
}

Show all the paragraphs

I’m creating a simple chat in go. But I’m struggling with the CSS.

It should show all the messages. But when it reaches the bottom of the message screen. It doesn’t show all the messages

Like this

enter image description here

I put the html, css and javascript together because I just need a simple screen for testing. But it should bring all the messages.

This is the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>CodeChallenge</title>
    <style>
        .form {
            position: fixed;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: #f9f9f9;
            border-top: 1px solid #78b8ef;
            padding: 5px 10px;
        }
        .form .placeholder,
        .form .input-message,
        .form button {
            display: block;
            margin-bottom: 5px;
        }
        .form .input-message {
            padding: 7px;
            border: 1px solid #ecebeb;
            border-radius: 4px;
            width: -webkit-fill-available;
        }
        .form button {
            width: 100%;
            color: white;
            padding: 7px 10px;
            border-radius: 4px;
            background-color: #78b8ef;
            border: 1px solid #5a9ed8;
        }
        .container {
            margin-bottom: 50px;
        }
        .container p {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container"></div>
    <div class="form">
        <form onsubmit="app.doSendMessage(); return false;">
            <div class="placeholder">
                <label>Hello <b class="username"></b>. Say something:</label>
            </div>
            <input class="input-message" type="text" placeholder="Enter message">
            <button type="submit">Send</button>
        </form>
    </div>

    <script type="application/javascript">
        var app = {}
        app.ws = undefined
        app.container = undefined

        app.print = function (message) {
            let el = document.createElement("p")
            el.innerHTML = message
            app.container.append(el)
        }

        app.doSendMessage = function () {
            var messageRaw = document.querySelector('.input-message').value
            app.ws.send(JSON.stringify({
                Message: messageRaw
            }));

            var message = '<b>me</b>: ' + messageRaw
            app.print(message)
        }

        // app.init = function () {
        //     if (!(window.WebSocket)) {
        //         alert('Your browser does not support WebSocket')
        //         return
        //     }
        //
        //     const Http = new XMLHttpRequest();
        //     const url='http://localhost:8081/message?limit=50';
        //     Http.open("GET", url);
        //     Http.send(null);
        //
        //     if (Http.status === 200) {
        //         allFifty = JSON.parse(Http.responseText)
        //         console.log(allFifty)
        //         allFifty.forEach(obj => {
        //             console.log(obj.From)
        //             console.log(obj.Message)
        //             let message = '<b>' + obj.From + '</b>: ' + obj.Message
        //             app.print(message)
        //         })
        //     }
        //
        //         app.init2()
        //     }

        app.init = function () {
            if (!(window.WebSocket)) {
                alert('Your browser does not support WebSocket')
                return
            }


            var name = getCookie("username");


            document.querySelector('.username').innerText = name

            app.container = document.querySelector('.container')

            // fetch('http://localhost:8081/message?limit=50')
            //     .then(response=>response.json())
            //     .then(data=>{
            //         console.log(data)
            //         data.forEach(obj => {
            //             console.log(obj.From)
            //             console.log(obj.Message)
            //             let message = '<b>' + obj.From + '</b>: ' + obj.Message
            //             app.print(message)
            //     })})

            app.ws = new WebSocket("ws://localhost:8081/socket/ws?username=" + name)
            app.ws.onopen = function () {
                fetch('http://localhost:8081/message?limit=50')
                    .then(response=>response.json())
                    .then(data=>{
                        console.log(data)
                        data.sort(function(a,b){
                            // Turn your strings into dates, and then subtract them
                            // to get a value that is either negative, positive, or zero.
                            return new Date(a.RegisterDate) - new Date(b.RegisterDate);
                        });
                        console.log(data)
                        data.forEach(obj => {
                            // console.log(obj.From)
                            // console.log(obj.Message)
                            let message = '<b>' + obj.From + '</b>: ' + obj.Message + ' ' + obj.RegisterDate
                            app.print(message)
                    })})
                .then(() => {
                    var message = '<b>me</b>: connected'
                    app.print(message)
                }
                )

            }

            app.ws.onmessage = function (event) {
                var res = JSON.parse(event.data)

                var message = ''
                if (res.Type === 'New User') {
                    message = 'User <b>' + res.From + '</b>: connected'
                } else if (res.Type === 'Leave') {
                    message = 'User <b>' + res.From + '</b>: disconnected'
                } else {
                    message = '<b>' + res.From + '</b>: ' + res.Message
                }

                app.print(message)
            }
        }

        window.onload = app.init

        function getCookie(cName) {
            const name = cName + "=";
            const cDecoded = decodeURIComponent(document.cookie); //to be careful
            console.log(cDecoded)
            const cArr = cDecoded.split('; ');
            console.log(cDecoded)
            let res;
            cArr.forEach(val => {
                if (val.indexOf(name) === 0) res = val.substring(name.length);
            })
            return res
        }
    </script>
</body>
</html>

Gorgias Livechat rule based on language

This code is from Gorgias livechat app,
I want to figure out if there’s a way to build a rule based on Shopify store language (shop.locale or url string(fr,en)).

The applicationID determine the language of the helpdesk. So that’s the only part affected that needs to change based on the rule. Here’s the code for english livechat only only.
French applicationID is 17741.

Can you help me build this rule?

 <!--Gorgias Chat Widget Start-->
<script id="gorgias-chat-widget-install-v2" src="https://config.gorgias.chat/gorgias-chat-bundle-loader.js?applicationId=17634"></script>
<script id="gorgias-chat-shopify-install">!function(_){_.SHOPIFY_PERMANENT_DOMAIN="{{shop.permanent_domain}}",_.SHOPIFY_CUSTOMER_ID="{{customer.id}}",_.SHOPIFY_CUSTOMER_EMAIL="{{customer.email}}"}(window||{});</script>
<!--Gorgias Chat Widget End--> 

How to escape apostrophe successfully in jQuery on iPhone that has Smart Punctuation

I haven’t been able to successfully escape Apostrophe on iPhone. After some research, it seems the Smart Punctation feature is causing some issues here. I’ve tried everything I can find and nothing has worked.

A user is entering text into a field and I verify if this text is correct. Here is my jQuery code. The valid Text is EMPORER’S EYE or Emporer’s Eye, but neither ever comes up as valid on iPhone.

$("#actionButton").click(function() {
var seats = $("#number2").val();
var apostrophe = 'u0027';
var error = null;


if ((seats === "EMPORER'S EYE") || (seats === 'Emporer's Eye')) {
 $("#message").fadeIn();
   $("#draggable").fadeOut();
  $("#draggable2").fadeOut();
} else {
  $("#messageWrong").fadeIn().delay(2500).fadeOut();
     $("#draggable").fadeOut().delay(2500).fadeIn();
  $("#draggable2").fadeOut().delay(2500).fadeIn();
}


// If you really need setflag:
var setflag = error != null;
});

Here is a codepen I have of the entire function and process I’m trying to put together.
https://codepen.io/MaxwellR/pen/BaYGPJL

TypeError: Object.method is not a function when using jest

I am trying to put together a basic implementation of an observable class in a js file

export class Observable {
constructor(emitter){
    return this._emitter = emitter
}

foo(){
    return'bar'
}

subscribe(next, error = {}, complete = {}){
    if (typeof next === "function") {
        return this._emitter({
            next, 
            error: error,
            complete: complete
        })
    }
    else {
        return this._emitter(next)
    }
}
}

with a corresponding jest file

import { Observable } from "./observable";

describe("Observable", () => {
    test('foo', () => {
        let fakeAsyncData$ = new Observable();
        expect(fakeAsyncData$.foo()).toBe('bar')
    })

    test('Observable subscriptions next returns value in pipe', () => {
        let test_value = "testing"

        let fakeAsyncData$ = new Observable(observer => {
            observer.next(test_value);
        });

        fakeAsyncData$.subscribe({
            next(val) { expect(val).toBe(test_value) }
        });
    });
});

For some reason the second test is failing due to subscribe not being a function. Which seems to be incorrect. Here is the entire jest output

 FAIL  ./observable.test.js
  Observable
    ✓ foo (21 ms)
    ✕ Observable subscriptions next returns value in pipe (2 ms)

  ● Observable › Observable subscriptions next returns value in pipe

    TypeError: fakeAsyncData$.subscribe is not a function

      14 |         });
      15 |
    > 16 |         fakeAsyncData$.subscribe({
         |                        ^
      17 |             next(val) { expect(val).toBe(test_value) }
      18 |         });
      19 |     });

      at Object.subscribe (observable.test.js:16:24)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.592 s, estimated 1 s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

What have I managed to screw up here?

Pushing QR to client

Trying to make login screen as WhatsApp, where the QR is pushed to the client for scanning, so I wrote the below server code:

package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"

    _ "github.com/mattn/go-sqlite3"
    "github.com/skip2/go-qrcode"
    "google.golang.org/protobuf/proto"

    "go.mau.fi/whatsmeow"
    "go.mau.fi/whatsmeow/store"
    "go.mau.fi/whatsmeow/store/sqlstore"
    "go.mau.fi/whatsmeow/types/events"
    waLog "go.mau.fi/whatsmeow/util/log"
)

func eventHandler(evt interface{}) {
    switch v := evt.(type) {
    case *events.Message:
        fmt.Println("Received a message!", v.Message.GetConversation())
    }
}

func main() {
    passer := &DataPasser{logs: make(chan string)}

    http.HandleFunc("/", passer.handleHello)
    go http.ListenAndServe(":9999", nil)

    store.DeviceProps.Os = proto.String("WhatsApp GO")
    dbLog := waLog.Stdout("Database", "DEBUG", true)
    // Make sure you add appropriate DB connector imports, e.g. github.com/mattn/go-sqlite3 for SQLite
    container, err := sqlstore.New("sqlite3", "file:datastore.db?_foreign_keys=on", dbLog)
    if err != nil {
        panic(err)
    }
    // If you want multiple sessions, remember their JIDs and use .GetDevice(jid) or .GetAllDevices() instead.
    deviceStore, err := container.GetFirstDevice()
    if err != nil {
        panic(err)
    }
    clientLog := waLog.Stdout("Client", "DEBUG", true)
    client := whatsmeow.NewClient(deviceStore, clientLog)
    client.AddEventHandler(eventHandler)

    if client.Store.ID == nil {
        // No ID stored, new login
        qrChan, _ := client.GetQRChannel(context.Background())
        err = client.Connect()
        if err != nil {
            panic(err)
        }

        for evt := range qrChan {
            switch evt.Event {
            case "success":
                {
                    passer.logs <- "success"
                    fmt.Println("Login event: success")
                }
            case "timeout":
                {
                    passer.logs <- "timeout"
                    fmt.Println("Login event: timeout")
                }
            case "code":
                {
                    passer.logs <- "new code"
                    fmt.Println("new code recieved")
                    img, err := qrcode.Encode(evt.Code, qrcode.Medium, 200) // evt.Code
                    if err != nil {
                        fmt.Println("error when write qrImage", err.Error())
                    }
                    passer.logs <- string(img)
                }
            }
        }
    } else {
        // Already logged in, just connect
        passer.logs <- "Already logged"
        fmt.Println("Already logged")
        err = client.Connect()
        if err != nil {
            panic(err)
        }
    }

    // Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    <-c

    client.Disconnect()
}

With the below api:

package main

import (
    "bytes"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "sync"
)

var (
    mux sync.Mutex
)

type Result struct {
    ResultType, Result string
}

type DataPasser struct {
    logs chan string
}

func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {
    setupCORS(&w, r)
    w.Header().Set("Content-Type", "text/event-stream")
    flusher, ok := w.(http.Flusher)
    if !ok {
        http.Error(w, "Internal error", 500)
        return
    }
    flusher.Flush()
    done := r.Context().Done()
    defer fmt.Println("EXIT")
    for {
        select {
        case <-done:
            // the client disconnected
            return
        case m := <-p.logs:
            fmt.Println(m)
            if m == "new code" || m == "We are logging in" || m == "Already logged" || m == "timeout" || m == "success" {
                if _, err := fmt.Fprintf(w, "data: %snn", m); err != nil {
                    // Write to connection failed. Subsequent writes will probably fail.
                    return
                }
                flusher.Flush()
            } else {
                mux.Lock()

                buffer := bytes.NewBuffer([]byte(m))

                /*  img, _, err := image.Decode(buffer)
                    if err != nil {
                        fmt.Println("err: ", err)
                    }

                    if err := jpeg.Encode(buffer, img, nil); err != nil {
                        log.Println("unable to encode image.")
                    } */

                w.Header().Set("Content-Type", "image/jpeg")
                w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
                if _, err := w.Write(buffer.Bytes()); err != nil {
                    log.Println("unable to write image.")
                }
                mux.Unlock()
                flusher.Flush()
            }
        }
    }
}

func setupCORS(w *http.ResponseWriter, req *http.Request) {
    (*w).Header().Set("Cache-Control", "no-cache")
    (*w).Header().Set("Connection", "keep-alive")
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

But stuck to read it in the client, I tried something as below, but got lost:

<html>
<head></head>
<body>
    note: <span id="content"></span><br>
    <img id="photo" style="display: block;-webkit-user-select: none;">
</body>
    <script>
      /*  (function(){
                document.getElementById("content").innerHTML='<object type="text/html" data="http://localhost:9999/" ></object>';
        })(); 
*/
        const myRequest = new Request('http://127.0.0.1:9999/', {
        method: 'GET',
        headers: new Headers(),
        type: "arraybuffer",
        mode: 'cors',
        cache: 'default',
        });  

        var source = new EventSource("http://127.0.0.1:9999/");
        source.onmessage = function (event) {
            console.log(event)
            var counter = event.data; // JSON.parse(event.data);
            document.getElementById("content").innerHTML = counter;
        }

    fetch(myRequest).then(response => {
        console.log(response)
        console.log(response.headers)
    const contentType = response.headers.get("content-type");
        if (contentType && contentType.indexOf("application/json") !== -1) {
            return response.json().then(data => {
            var obj = JSON.parse(str);
            console.log(obj)
            // Process your data as a JavaScript object
            });
        }  if (contentType && contentType.indexOf("image/jpeg") !== -1) {
            console.log("Image received")
            return response.blob().then(data => {
                var reader = new FileReader();
                reader.readAsDataURL(blob); 
                reader.onloadend = function() {
                    var imageUrl = reader.result;                
                    var img = document.querySelector("#photo");
                    img.src = imageUrl;
                }
            });
        } else if (contentType && contentType.indexOf("text/event-stream") !== -1) {
            return response.text().then(text => {
            console.log(text)
            var source = new EventSource("http://localhost:9999/");
            source.onmessage = function (event) {
                var response = event.data // JSON.parse(event.data);
                document.getElementById("content").innerHTML = counter;
            } 
            // Process your text as a String
            });
        } else if (contentType && contentType.indexOf("text/html") !== -1) {
            return response.text().then(text => {
            console.log(text)
            var source = new EventSource("http://localhost:9999/");
            source.onmessage = function (event) {
                var response = event.data // JSON.parse(event.data);
                document.getElementById("content").innerHTML = counter;
            } 
            // Process your text as a String
            });
        } 
    });

    </script>
</html>

If I run and see the displayed page, I see:

enter image description here

Any help?

Iframe src pointing to wrong URL

My document gives the user a choice of what program (effectively URL) to load in an iframe.
The user may select another program later and the browser puts the prior choice in history.
This allows the user to go back to a prior program that was loaded.
No problem and the onload JAVASCRIPT lets the program know when this happens.
Problem is the onload functions looks up the src attribute of the iframe, but instead of getting the URL of what is now (re)loaded in the iframe it lists what was the last change in the src.
I tried accessing the href of the iframe, but that is protected since it is from another site.
Is there a way to retrieve this. I suspect that using replacestate and popstate might be able do the trick. Any ideas?

axios download video from url to variable

I have a nodejs app that I want to use to download a video from a url to keep in a variable as binary.
I’m starting off by sending a get request to the url with the response type being stream.

            const videoResponse = await axios({
                method: 'GET',
                url: url,
                responseType: 'stream',
              });

const video = await videoResponse.data;

I am then trying to store the result of that call in a variable but the response isn’t a string of binary but rather an entire object.
I’ve tried calling “pipe” on the data as I’ve seen from other examples though the object does not contain anything with that name.
What do I need to do to store the video I’m downloading as binary in this variable?

Can’t show a picture in javascript

I have a quiz page and at the end when you get the results, I would like to redirect the user to another page via link. This is the sample code in js. I tried to insert the <a> tag like so : desc: "Bold, beautiful and brilliant - <a href='../../LINK'> your best match is Marlene!</a> <br>

but obviously that did not work. Also the methods from the internet of declaring a picture do not work. Does anybody have any ideas? Thank you in advance! 🙂

var possible_results = [
    {
        
        name: "Marlene",
        //THE ANIMALS CHARACTERISTICS BY WHICH ITS MEASURED:
        colourfulness: 10,
        hairiness: 10,
        landiness: 55,
        size: 80,
        carnivore: 0,
        scariness: 40,
        sociability: 70, 
        //THE SCORE IT GETS COMPARED TO THE QUIZ TAKER:
        similarity: 0,
        //BITS FOR THE RESULTS PANEL:
        desc: "Bold, beautiful and brilliant - your best match is Marlene!<br> You're intelligent and powerful. Your friends love you and whilst no-one wants to mess with you,  everyone agrees - you are great! <br> In the wild there are only 600,000 African elephants and it is officially classed as vulnerable.",

        img: "https://images.unsplash.com/photo-1588269864631-ced7dff8da0d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80"}]

Material-ui component Checkbox handler does not set the state – V.5.0

s, I made a component “Checkbox” to be used in others forms of my app, but the state does not update after click. It works and get checked at the DOM, but the state doesn’t change, it remains ‘false’. I’m using Material-ui v.5.0 and React 18.0.1, all helps will be very appreciated. Thanks in advance. I don’t know what mistake I’m doing. I’m a newbie in React. Below follows my codes. It should be a component, where I will use in another form. After checked, I want it to become disabled. Thanks folks.

// CardNotes Component
import React, {useState} from "react";
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import IconButton from '@mui/material/IconButton';
import {  DeleteOutlined } from "@mui/icons-material";
import { Typography } from "@mui/material";
import { makeStyles } from "@mui/styles";
import Checkbox  from './Checkbox';
import { Box } from '@mui/material';

const useStyles = makeStyles({
    test: {
        border: (note) => {
            if (note.status == 'Urgente'){
                return '1px solid red'
            }
            return '1px solid blue'
        }
    }
})


export default function CardNotes({ note, handleDelete }){
    
    const [checked, setChecked] = useState(false);
    console.log('checkbox', checked)
    

    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setChecked(event.target.checked);
      };

     
    const classes = useStyles(note)

    return( // receiving props from Notes
        <div>
            <Card elevation={3} className={classes.test}>
                <CardHeader 
                titleTypographyProps={{
                    fontSize: 16,
                  }}
                 action={
                    <IconButton onClick={()=> handleDelete(note.id) }>
                    <DeleteOutlined />
                  </IconButton>
                  
                 }
        
                 title={note.title}
                 subheader={note.status}

                />
                
                <CardContent>
                    <Typography variant="display2" color="textSecondary">
                        {note.details}
                    </Typography>
                </CardContent>
                 <Box ml={2}>
                <Checkbox 
                 label="Resolvido"
                  checked={checked}
                  onChange={ (e) => setChecked(e.target.checked)}>
                 </Checkbox>
                 </Box>

            </Card>
        </div>
    )
}
// checkbox component
import React from 'react'
import {FormControl , FormControlLabel} from '@mui/material';
import Checkbox from '@mui/material/Checkbox';



export default function Chekbox (props) {

const { resolved, handleChange } = props;


  return (
    <FormControl>
        <FormControlLabel
        control={<Checkbox
            checked={resolved}
            color="primary"
            onChange={handleChange}
        />}
        label='Resolvido'
        />

    </FormControl>

  )
}

how to stop one function inside another function [closed]

I have a function that is running automatically & fetching data from API. I have another function where I want to stop my first function execution

first function

LoadingAPI(): void {
    Wails.Events.On("fetching Data", (percent: number) => {
      this.uploading = percent;
      if (this.cdr && !(this.cdr as ViewRef).destroyed) {
        this.cdr.detectChanges();
      }
    });
  }

second function –

cancelTransferring(): void {
    break this.LoadingAPI();
  }

Seeking tools to housekeep organize image resources in HTML CSS JS projects

I am using Visual Studio Code to develope some pages, for my own businesses, in HTML CSS with bits of Javascript. I’ve been doing it in a bit of a hurry while retaining bits of the sites that I put together over the years using NOFusion. So I was not really able to start with a clean sheet. So now my image assets are in various folders and I also have a lot of redundant images that I would like to clear out. Is there a VSCode extension or app that would help me identify the assets that are in use and identify the ones I can clear out?

I see that VSCode will do a global search and list all the lines of code, in all the files, that contain, for example, “.jpg”. I can copy the list but then I have to parse out all the extraneous stuff (line #, src=, alt=, etc.) to leave just the path and filename. It should not be too difficult but I’m sure there are smarter ways to do it.

Thanks in advance. Please use simple language. 🙂

Detecting the collision of 2 divs with JavaScript

I’m making a simple Space Invaders Clone in Web and ran into an issue. The code works well so far with the exception of the collision system. I need to destroy an enemy every time that the player’s bullet hits it. In order to make it, I’m grabbing the x and y coordinates of both the enemies’ div and the bullet’s div. The issue appears on the values comparison: apparently getBoundingClientRect() grabs the x and y coordinates from within the element excluding its real size. Hence, according to my code, only when the bullet is perfectly inside the enemy that things would trigger. Is there a better way of doing it? How so?

Thanks in advance.

const shoot = (x) => {
  //Creates bullet
  const main = document.getElementById("main");
  const div_bullet = document.createElement("div");

  //Appends child
  main.appendChild(div_bullet);

  //Sets position
  div_bullet.style.top = "340px";
  div_bullet.style.left = x + "px";

  //Gives it a class
  div_bullet.classList.add("div_bullet");
  div_bullet.setAttribute("id", "bullet");

  //Deletes bullet
  setTimeout(() => {
    div_bullet.remove();
  }, 1000);
};

const load_game = () => {
  //Adding movement to the spaceship
  const space_ship = document.getElementById("space_ship");
  let x = 375;
  window.addEventListener("keydown", (e) => {
    switch (e.key) {
      case "ArrowLeft":
        if (x <= 15) break;
        x = x - 10;
        space_ship.style.left = x + "px";
        break;
      case "ArrowRight":
        if (x >= 725) break;
        x = x + 10;
        space_ship.style.left = x + "px";
        break;
      case "ArrowUp":
        if (document.getElementsByClassName("div_bullet").length === 0)
          shoot(x + 20);
        break;
      default:
        break;
    }
  });
};

const collision_system = () => {
  setInterval(() => {
    //Checks if any enemy was hit
    const e1 = document.getElementById("e1");
    const e2 = document.getElementById("e2");
    const e3 = document.getElementById("e3");
    const e4 = document.getElementById("e4");
    const e5 = document.getElementById("e5");

    const enemies_position = [{
        x: e1.getBoundingClientRect().x,
        y: e1.getBoundingClientRect().y
      },
      {
        x: e2.getBoundingClientRect().x,
        y: e2.getBoundingClientRect().y
      },
      {
        x: e3.getBoundingClientRect().x,
        y: e3.getBoundingClientRect().y
      },
      {
        x: e4.getBoundingClientRect().x,
        y: e4.getBoundingClientRect().y
      },
      {
        x: e5.getBoundingClientRect().x,
        y: e5.getBoundingClientRect().y
      },
    ];

    if (document.getElementById("bullet")) {
      const x_bullet = document
        .getElementById("bullet")
        .getBoundingClientRect().x;
      const y_bullet = document
        .getElementById("bullet")
        .getBoundingClientRect().y;

      console.log(
        "X: " + enemies_position[0].x + "Y: " + enemies_position[0].y
      );
      console.log("X bullet: " + x_bullet + "Y bullet : " + y_bullet);
      for (let i = 0; i < 5; i++) {
        if (
          enemies_position[i].x === x_bullet &&
          enemies_position[i].y === y_bullet
        )
          alert("Shoot!");
      }
    }
  }, 10);
};

document.addEventListener("DOMContentLoaded", () => {
  load_game();
  collision_system();
});
* {
  padding: 0px;
  margin: 0px;
}

body {
  background-color: black;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main {
  width: 800px;
  height: 500px;
  border: 2px white solid;
  border-radius: 10px;
}

@keyframes enemies_move {
  from {
    left: 80px;
  }
  to {
    left: -80px;
  }
}

.enemies {
  margin-top: 20px;
  position: fixed;
  width: 800px;
  height: 50px;
  display: flex;
  justify-content: space-evenly;
}

.enemies div {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: orange;
  animation: enemies_move 4s alternate infinite;
}

.barriers {
  width: 800px;
  height: 20px;
  position: fixed;
  top: 460px;
  display: flex;
  justify-content: space-evenly;
}

.barriers div {
  width: 100px;
  height: 20px;
  background-color: white;
}

.space_ship {
  width: 50px;
  height: 50px;
  border: 2px white solid;
  position: relative;
  top: 440px;
  left: 375px;
}

@keyframes shoot_bullet {
  from {
    top: 340px;
  }
  to {
    top: -50px;
  }
}

.div_bullet {
  left: 17px;
  width: 15px;
  height: 40px;
  background-color: white;
  position: relative;
  animation: shoot_bullet 1s;
}
<div id="main" class="main">
  <div class="enemies">
    <div id="e1"></div>
    <div id="e2"></div>
    <div id="e3"></div>
    <div id="e4"></div>
    <div id="e5"></div>
  </div>
  <div class="barriers">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div id="space_ship" class="space_ship"></div>
</div>