Discord js Using guild. but this error happens Cannot read properties of undefined (reading ‘members’)

So I was writing tje code as a test to implement some functionality.

when a user sends a user ID with a command, the bot have to check if the id is on the server or not, but this error occurs Cannot read properties of undefined (reading 'members')

    if (command === "give") {
        message.channel.send('test');
        if (guild.members.cache.find(m => m.id === args)?.id) {
    // true
    message.channel.send('FOUND');
} else {
    // false
    message.channel.send('who is that');
}}

Is there a way to solve the problem or is there another way?

In simple functions is ‘const’ or ‘let’ or ‘var’ even necessary

This is a Postman global function, but it’s what I have for an example. I have many of these types of examples in my code.

endpointUtils = {
    validateResponse: pm => {
        const responseData = pm.response.json();

        pm.test("Response field 'status' equals 'S'", () => {
            pm.expect(responseData.status).to.eql('S')
        })
    }
}

As matter of habit I define variables like ‘responseData’ with ‘const’. I’m wondering in this circumstance if any modifier is necessary, be it ‘const’, ‘let’, or ‘var’. Would nothing do just as well? It would greatly simplify the clutter in these few line functions. Am curious if this is violating some best practices at some level. Within the scope of the function ‘validateResponse’, does it really matter?

React rendering issue- object as props and props getting manipulated using deepclone

I have a React component <Grid /> which renders <SubGrid />
Now <grid /> is receiving props data and config.
My Grid Component is has a useEffect-

useEffect(() => {
        prepareAdaptableOptions();
    }, [data, config]);

this useEffect has some code to deepclone data and config and then pass it down to <SubGrid />

Now my issue is – whenever <Grid /> is rendererd my subgrid updates on DOM ie., DOM is manipulated. even tho data and config that I passed are same.

And If I remove data, config from array of dependency then this useEffect does not even trigger when data and config is changed?

How do I resolve this issue ?

what has gone wrong in my html and js source code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gym Management System</title>
    
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="app"
    </div>
    <script type="module" src="scripts.js" defer ></script>
</html>



SCRIPT.JS FILE

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js';
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from 'https://www.gstatic.com/firebasejs/9.1.0/firebase-auth.js';
import { getFirestore, collection, addDoc, getDocs, serverTimestamp, query, orderBy } from 'https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js';


const firebaseConfig = {
    apiKey: "AIzaSyAqW1Sb6okV-bIp6Z_q1LjnR62fjEyEOKM",
    authDomain: "management-system-f0b2b.firebaseapp.com",
    projectId:"management-system-f0b2b",
    storageBucket: "management-system-f0b2b.appspot.com",
    messagingSenderId:"412778751231",
    appId: "1:412778751231:web:316fe137b5c980417ed8ca",
    measurementId:"G-KBG05HJ8F6"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();
const analytics = getAnalytics(app);

document.addEventListener('DOMContentLoaded', () => {
    const app = document.getElementById('app');

    const renderLogin = () => {
        app.innerHTML = `
            <h2>Login</h2>
            <form id="login-form">
                <input type="email" id="login-email" placeholder="Email" required>
                <input type="password" id="login-password" placeholder="Password" required>
                <button type="submit">Login</button>
            </form>
            <p>Don't have an account? <a href="#" id="signup-link">Sign up</a></p>
        `;

        document.getElementById('login-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;

            auth.signInWithEmailAndPassword(email, password)
                .then((userCredential) => {
                    console.log('User logged in:', userCredential.user);
                    renderDashboard();
                })
                .catch((error) => {
                    console.error('Error logging in:', error);
                });
        });

        document.getElementById('signup-link').addEventListener('click', (e) => {
            e.preventDefault();
            renderSignup();
        });
    };

    const renderSignup = () => {
        app.innerHTML = `
            <h2>Sign Up</h2>
            <form id="signup-form">
                <input type="email" id="signup-email" placeholder="Email" required>
                <input type="password" id="signup-password" placeholder="Password" required>
                <button type="submit">Sign Up</button>
            </form>
            <p>Already have an account? <a href="#" id="login-link">Login</a></p>
        `;

        document.getElementById('signup-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const email = document.getElementById('signup-email').value;
            const password = document.getElementById('signup-password').value;

            auth.createUserWithEmailAndPassword(email, password)
                .then((userCredential) => {
                    console.log('User signed up:', userCredential.user);
                    renderDashboard();
                })
                .catch((error) => {
                    console.error('Error signing up:', error);
                });
        });

        document.getElementById('login-link').addEventListener('click', (e) => {
            e.preventDefault();
            renderLogin();
        });
    };

    const renderDashboard = () => {
        app.innerHTML = `
            <h2>Dashboard</h2>
            <button id="logout">Logout</button>
            <h3>Members</h3>
            <div id="members-list"></div>
            <h3>Add Member</h3>
            <form id="add-member-form">
                <input type="text" id="member-name" placeholder="Name" required>
                <input type="email" id="member-email" placeholder="Email" required>
                <button type="submit">Add Member</button>
            </form>
            </div>
            <div class="section">
                <h3>Fees</h3>
                <div id="fees-list"></div>
                <form id="add-fee-form">
                    <input type="text" id="fee-member-email" placeholder="Member Email" required>
                    <input type="number" id="fee-amount" placeholder="Amount" required>
                    <button type="submit">Add Fee</button>
                </form>
            </div>
            <div class="section">
                <h3>Working Day Notifications</h3>
                <div id="notifications-list"></div>
                <form id="add-notification-form">
                    <input type="text" id="notification-message" placeholder="Notification Message" required>
                    <button type="submit">Add Notification</button>
                </form>
            </div>
        `;

        document.getElementById('logout').addEventListener('click', () => {
            auth.signOut().then(() => {
                console.log('User logged out');
                renderLogin();
            });
        });

        const addMemberForm = document.getElementById('add-member-form');
        addMemberForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const name = document.getElementById('member-name').value;
            const email = document.getElementById('member-email').value;

            db.collection('members').add({
                name: name,
                email: email,
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            })
            .then(() => {
                console.log('Member added');
                addMemberForm.reset();
                loadMembers();
            })
            .catch((error) => {
                console.error('Error adding member:', error);
            });
        });
        const addFeeForm = document.getElementById('add-fee-form');
        addFeeForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const email = document.getElementById('fee-member-email').value;
            const amount = document.getElementById('fee-amount').value;

            db.collection('fees').add({
                email: email,
                amount: amount,
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            })
            .then(() => {
                console.log('Fee added');
                addFeeForm.reset();
                loadFees();
            })
            .catch((error) => {
                console.error('Error adding fee:', error);
            });
        });

        const addNotificationForm = document.getElementById('add-notification-form');
        addNotificationForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const message = document.getElementById('notification-message').value;

            db.collection('notifications').add({
                message: message,
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            })
            .then(() => {
                console.log('Notification added');
                addNotificationForm.reset();
                loadNotifications();
            })
            .catch((error) => {
                console.error('Error adding notification:', error);
            });
        });


        loadMembers();
        loadFees();
        loadNotifications();
    };

    const loadMembers = () => {
        const membersList = document.getElementById('members-list');
        membersList.innerHTML = '';

        db.collection('members').orderBy('createdAt', 'desc').get()
            .then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                    const member = doc.data();
                    membersList.innerHTML += `
                        <div>
                            <h4>${member.name}</h4>
                            <p>${member.email}</p>
                        </div>
                    `;
                });
            })
            .catch((error) => {
                console.error('Error loading members:', error);
            });
    };

    const loadFees = () => {
        const feesList = document.getElementById('fees-list');
        feesList.innerHTML = '';

        db.collection('fees').orderBy('createdAt', 'desc').get()
            .then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                    const fee = doc.data();
                    feesList.innerHTML += `
                        <div>
                            <h4>${fee.email}</h4>
                            <p>Amount: $${fee.amount}</p>
                        </div>
                    `;
                });
            })
            .catch((error) => {
                console.error('Error loading fees:', error);
            });
    };

    const loadNotifications = () => {
        const notificationsList = document.getElementById('notifications-list');
        notificationsList.innerHTML = '';

        db.collection('notifications').orderBy('createdAt', 'desc').get()
            .then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                    const notification = doc.data();
                    notificationsList.innerHTML += `
                        <div class="notification">
                            <p>${notification.message}</p>
                        </div>
                    `;
                });
            })
            .catch((error) => {
                console.error('Error loading notifications:', error);
            });
    };

    // Initial render
    auth.onAuthStateChanged((user) => {
        if (user) {
            renderDashboard();
        } else {
            renderLogin();
        }
    });
});


i am not able to get the output.
my html file is not able to process the link to my javascript file
why can i not import rules form firebase
now my console is only showing problem with my html code
i am new to programming so i’m just trying to incorporate codes from here and there but nothing is working out.

Change gradient Values on click / Pressed

The link will show you what I’m trying to achieve

(this is not a real outcome. this video is a concept of my goal)

https://www.youtube.com/watch?v=U_MggL4-AMc

I could really do with a helping hand on this lol

(I need to be able to do this for MULTIPULE different gradients individually)

I’ve tried using Vars with colours and using a Event listener which worked somewhat in codepen with solid colours not gradients but didn’t work on my actual site. (this didn’t previously work for me.

I have now tried using background images to somewhat success. I’m now trying to figure out how I can go back and fourth with the theme colours as well as set the scale for the background retrieved by the script. (however I’d prefer the original method of changing gradient values on click)

here’s a link to the CodePen

<!DOCTYPE html>
<html>
<head>
<style> 
#Background {
  width: 1920px;
  height: 1080px;
  background-image: url("https://previews.dropbox.com/p/thumb/ACUv6h-QQ6PskOhByDXYwHCGjtk1ar3JN5ufhLEEwKxFAJvxxqUyCHMT-DMbK318IVJ_Zn2ustYtg-CcpEPp3egLeHMJoH_teEMKWVjtmw3VSeDvSJpwcqCk89QsDdKjbL4Q9cuPviRrw--RPRXN-uIDTcQYQfkyiQyQT0VMVN5FOwsblLq222dzHRW-YL9huPTGqgmWYNVOc36wpcNva2sVah0UVRLxjeSiGEbF4RPZijO2tp0kYovzRsuybNjkvHbxK4SgO_WGPjebe2Uh9OzoLmygGI-zItBzoqLk9dzLe0Bo6jMQr7v_8fDX3VnJpHNAOMZstzdmXlhQ_INGmlqaaCoTM175t6pYfVxUy_s2qxRotclVumgogKWY2RwUyqk/p.png");
}

  .Embers-Theme-Card {
    --perspective: 1400px;
    --rotateX: 0;
    --rotateY: 0;
    --angle: 6.5deg;
  
    position: relative;
    display: grid;
    place-content: center;
    text-align: center;
    box-shadow: rgba(0, 0, 0, 0.25) -20px 20px 20px 0px;
    padding: 2rem;
    aspect-ratio: 1 / 2;
    background-image: url("http://localhost:10060/images/Embers.png");
    background-size: cover;
    transform: perspective(var(--perspective)) rotateX(var(--rotateX))
      rotateY(var(--rotateY));
    transition: transform 350ms ease;

    width: 180px;
    height: 75px;
    border-radius: 20px;
    left:800px;
    Top: 100px;
  }
  
  .Embers-Theme-Card > :where(h1, p) {
    background: rgba(221, 221, 221, 0.432);
    margin: 0;
    padding: 0.5rem;
  }
  
  .mouse-position-tracker {
    position: absolute;
    inset: 0;
  }
  
  .mouse-position-tracker > div {
    position: absolute;
    width: calc(100% / 3);
    height: calc(100% / 3);
    z-index: 2;
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(1):hover) {
    --rotateX: var(--angle);
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(2):hover) {
    --rotateX: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(3):hover) {
    --rotateX: var(--angle);
    --rotateY: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(4):hover) {
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(6):hover) {
    --rotateY: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(7):hover) {
    --rotateX: calc(var(--angle) * -1);
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(8):hover) {
    --rotateX: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(9):hover) {
    --rotateX: calc(var(--angle) * -1);
    --rotateY: var(--angle);
  }
  
  /* 1st, 4th, 7th */
  .mouse-position-tracker > div:nth-of-type(3n - 2) {
    left: 0;
  }
  /* 2nd, 5th, 8th */
  .mouse-position-tracker > div:nth-of-type(3n - 1) {
    left: calc(100% / 3);
  }
  /* 3rd, 6th, 9th */
  .mouse-position-tracker > div:nth-of-type(3n) {
    right: 0;
  }
  
  /* 1-3 */
  .mouse-position-tracker > div:nth-child(n + 1):nth-child(-n + 3) {
    top: 0;
  }
  
  /* 4-6 */
  .mouse-position-tracker > div:nth-child(n + 4):nth-child(-n + 6) {
    top: calc(100% / 3);
  }
  
  /* 7-9 */
  .mouse-position-tracker > div:nth-child(n + 7):nth-child(-n + 9) {
    bottom: 0;
  }
  
  /* general styling */
  :root {
    --shadow: 0px 1px 2.2px rgba(0, 0, 0, 0.02),
      0px 2.5px 5.3px rgba(0, 0, 0, 0.028), 0px 4.6px 10px rgba(0, 0, 0, 0.035),
      0px 8.3px 17.9px rgba(0, 0, 0, 0.042), 0px 15.5px 33.4px rgba(0, 0, 0, 0.05),
      0px 37px 80px rgba(0, 0, 0, 0.07);
  }

  .Embers-Theme-Card
  {
    cursor:pointer;
  }
</style>
</head>
<body>


<div id="Background">
        <div class="Embers-Theme-Card"<button onclick="myFunction()"></button>
  <h1>Embers</h1>


  <div class="mouse-position-tracker">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>
</div>


<script>
function myFunction() {
   document.getElementById("Background").style.backgroundImage = "url(https://previews.dropbox.com/p/thumb/ACX0qlkI5_4X1wx38BE5OYUXzWxSZf1IDvUqHhiRXEWE8XbQf6t-OTWScbY8iUOJi1Zw-v0B89055hqh7J87eIpVkC3gfh4ceH5AATuzh95VVChO9wD1TDCYsgQN9Qc6XDWT2p9x3_BG8zhGu6tuaCxreeS_NJDzAa-W3VU38f7L0Ik2lrn-1KI19pu8caW2DkBL1aY7-QePYnjLvaYmGvCrk4ZUYu27ITHJMQYtJd_VsEwCyp3-CLABikGcO0gtaeo1GrhtAjKjC6QRxnmCz3A-uCbb-aF9aJyxkOs3Mues2Pi8H8PNhZ3sZ7pQqbqhChdgg4BvXJPUfeK5RZhWa6jxsXVgYnbTaqEjLWWO7ONvOw/p.png)";
}

</script>

</body>
</html>

How can I connect a like counter to my firebase database

I have a post view counter (Blogger) which is connected to a Firebase database and is working fine. But I would like to add the like counter to the same database and structure for each post id.

Postviews js

<script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("My-Project-URL/pages/id/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); }); </script> 

Show the views value

<i class='fa fa-eye'/> <a expr:name='data:post.id'/><span id='postviews'/> Views

Like counter js

<script>
// store the main Firebase URL
var firebaseURL = 'My-Project-URL/pages/id/';

// update the likeCounts shown in a <span> beside each blogpost
var postDivs = document.querySelectorAll('.post');

for (var i = 0; i < postDivs.length; i++) {

    var postID = postDivs[i].id;

    var numLikes = getLikeCount(postID);

}

// this function grabs the likeCount for a particular post from the Firebase
function getLikeCount(postID) {
 
    console.log('running getLikeCount for post ID:', postID);
    
    var thisPostRef = new Firebase(firebaseURL + postID + '/like-count/');
    
    thisPostRef.once('value', function(snapshot) {
        
        console.log( postID + ' value:', snapshot.val() );
        
        if ( snapshot.val() ) {
            
            console.log( postID + ' contains:', snapshot.val() );

            document.querySelector('#' + postID + ' .like-count').innerHTML = snapshot.val() + ' likes';
            
        } else {
            
            console.log( postID + '- no data in Firebase' );
            
            return 0;
        
        }
    
    });
    
}

function likePost(id) {

    console.log('running likePost() for post ID:', id);
    
    var postRef = new Firebase(firebaseURL + id);
    
    // get current number of likes here, so we can increment if any exist
    postRef.child('like-count').once('value', function(snapshot){
        
        console.log( 'snapshot.val():', snapshot.val() );
        
        var currentLikes = snapshot.val() ? snapshot.val() : 0;
        
        console.log( 'currentLikes:', currentLikes );
    
        postRef.update({
            
            'postID': id,
            'like-count': currentLikes + 1
            
            }, function(error) {
                
              if (error) {
                  
                console.log('Data could not be saved:' + error);
              
              } else {
              
                console.log('Data saved successfully');
              
              }
            
            });
            
        getLikeCount(id);
    
    });
    
}
</script>

Show the likes value:

<a expr:name='data:post.id'/> <button onclick='likePost()'> <i class='fa fa-thumbs-up' style='font-size:36px'/></button> <span id='likes'/>

I tried to get the post id but always have to put it manually on the onlick=’likePost()’ function to get something stored in the database.

I don’t know how to integrate the like counter code to the viewpost code (which is working) and have same database structure.

Three JS loop through materials

I want to search for the material called COIN and assign a new texture to it. I know it’s material number 0, but what I want is to search through the materials and if it finds a name match, assign the texture.

object.traverse( function( node ) {
  if (node.isMesh) {
    if ( node.material[0].name == 'COIN' ) {
      node.material = textura
    } 
  }
})
// Works perfect

Looking something like:

if ( node.material[].name == 'COIN' )
// Error

How can I loop through the object’s textures to find the one I’m interested in without knowing the material index?

Just in case it matters, the object format is FBX.

Thanks!!!

FileDownload Open in a new tab

I implemented TelerikUpload in my project. Upload is working fine.
My following code is downloading the file to download folder then I have to click it to open the folder. But I want the file to open in a new tab or in a popup window without the download.
I tried all options, Any option I try it is always downloading to download folder.
Is it because my Blazor application is a single page app?

    //JRazor file
<a href="" @onclick="() => AttachmentOpen(item)" @onclick:preventDefault target="_blank">fileName</a>

function openFile(filename, content, mimeType) {
    var blob = new Blob([content], { type: mimeType });
    var url = window.URL.createObjectURL(blob);
    var anchorElement = document.createElement('a');
    document.body.appendChild(anchorElement);    
    anchorElement.setAttribute("type", "hidden");
    anchorElement.href = url;
    anchorElement.target = "_blank";
    anchorElement.click();

    anchorElement.remove();
    window.URL.revokeObjectURL(url);
}
//Razor.cs file
private async Task AttachmentOpen(Attachment attachment)
{
    var extension = Path.GetExtension(attachment.fileName);
    var mimeType = MimeTypeHelper.GetMimeType(extension);
    byte[] DownloadFileBytes = ReadFile(attachment.Path);
    await JSRuntime.InvokeVoidAsync("openFile", attachment.fileName, FileBytes, mimeType);
}

Convert objects into array

A = [{"name":"John","age":30,"city":"New York"},{"name":"Jimmy","age":40,"city":"Toronto"}]

B = [["John", 30, "New York"], ["Jimmy", 40, "Toronto"]]

How to convert A into B in JavaScript?

Thanks in advance for your help!

Use ajax to call php, to call python, and get the result

I have built a website with a fairly complex structure and lots of javascript and php functions. I avoided jquery to make it lighter.

I now want to add a python function that should return a value to it. Most people recommend Flask for this, but all the examples I have found seem to require re-arranging the index page etc, which I don’t want to do (but please correct me if I am misunderstanding that).

So, the simple solution I thought about is to use ajax to call a php script, which in turn executes a python file. The problem, is that ajax isn’t waiting for the python script to complete and return the result.

I am mostly self-taught, so maybe what I did is all wrong, and any suggestion for a simple fix is much appreciated. Again, I’d like to avoid jquery and any major re-arrangement of pages etc.

Here is my code.

The ajax function that I use for lots of things on the site:

 var ajaxResponseText = "";//a global variable that I use to get back the results of PHP functions
function ajaxRequestReturn(phpRequest, vars, isAsync=false, setHeader=false, jsonParsed=true){
  ajaxResponseText = "";
  var req = new XMLHttpRequest();
  req.open("POST", phpRequest, isAsync);//not asynchronous
  if(setHeader){
    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  }
  req.onProgress = function(){
    console.log("READYSTATE: ", req.readyState );
  }
  req.onload = function(){
    if(this.status==200){
      console.log("READYSTATE: ", this.readyState);
      console.log("responseText: ", this.responseText);
      if(jsonParsed){
        ajaxResponseText = JSON.parse(this.responseText);
      }else{
        ajaxResponseText = this.responseText;//php functions will echo a json array
      }
      // console.log(ajaxResponseText);
    }else if(this.status==404){
      ajaxResponseText = "Not found";
    }
  }
  req.onerror = function(){
    throw new Error("Bad request.");//this will stop the script and report the error
  }
  req.send(vars);
}

An event handler on the page calls:

ajaxRequestReturn("myPhpPythonCaller.php", vars="", isAsync=false, setHeader=false, jsonParsed=false)

myPhpPythonCaller.php simply has:

echo exec("pathToMyPythonEnv .venv/bin/python3 pathToMyPythonScript.py");

And the python script would produce and then print the result, say

from library import functionx

res = functionx()

print(res)

This set-up works for simple functions (e.g. print(“hello”) from MyPythonScript.py sends “hello” to ajaxResponseText, as expected ). However, if I call a function that takes time (I want to run an LLM, which would take dozens of seconds to produce an output), ajax doesn’t wait for the result, gets to status==200 and console.logs an empty ajaxResponseText.

What is the simplest, lightest way to do what I am trying to do?

Thank you so much for any tips!

How to check both mouse click down while dragging mouse over an element?

I am working on a basic sketching application using React JS. The intended functionality is that when a user clicks the mouse while hovering over an element, the element should change color.

One approach I considered involves using a variable (e.g., shouldDraw). This variable would be set to true on onMouseDown and set back to false on onMouseUp.

When shouldDraw is true, any element the mouse hovers over should change to the new color.

Is there a more idiomatic way to implement this in React JS?

How to change Radar Chart size? Chart JS

I’m trying to make a Radar Chart using react and ChatJs. It works just fine on bigger screens, but on mobile phone the chart is too small. How could I remove the blank spaces(Example on image) and make the chart bigger(As example the line red)?
Code:

// RadarChart.js
import React from 'react';
import { Radar } from 'react-chartjs-2';
import {
    Chart,
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend,
} from 'chart.js';



Chart.register(
    RadialLinearScale,
    PointElement,
    Legend,
    Filler,
    LineElement,
    Tooltip,
);
Chart.defaults.font.size = '16';
Chart.defaults.color = 'black';

const RadarChart = () => {
    const data = {
        labels: ['Running', 'Swimming', 'Cycling', 'Reading'],
        datasets: [
            {
                data: [80, 30, 100, 65],
                borderWidth: 1,
            },
        ],
    };

    // Chart options

    return (
        <Radar
            data={data}
            options={{
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function (tooltipItems) {
                                return 'Result: ' + tooltipItems.raw + '%';
                            },
                        },
                    },
                    legend: {
                        display: false,
                    },
                    title: {
                        text: 'Title Here',
                        display: true,
                        font: { size: 24 },
                    },
                },

                responsive: true,
            }}
            className='rounded-md bg-zinc-300'
        />
    );
};

export default RadarChart;

How I want to make the chart looks like

Content Security Policy Blocked JS file from live reload

Essentially i have tried loading my site multiple times and cannot get the JS to work.

tester.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple HTML Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        header, footer {
            background-color: #f8f8f8;
            padding: 10px;
            text-align: center;
        }
        nav {
            margin-bottom: 20px;
        }
        nav a {
            margin: 0 10px;
            text-decoration: none;
            color: #333;
        }
        main {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<h1>Choose a country</h1><br>
<button function="onClick()">Grab my location</button>   
<script type="text/javascript" src="tester.js"></script>
</body>
</html>

the js file.


    function onClick(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(successCallback, errorCallBack)
        } else {
            alert("Geolocation is not supported by this browser")
        }
    }

    function    successCallback(){
        console.log(position)
        console.log(position.coords.latitude)
        console.log(position.coords.longitude)

        alert("Latitude is "+ position.coords.latitude +" and "+ position.coords.longitude )

        function errorCallBack() {
            switch(error.code) {
                case error.PERMISSION_DENIED:
                alert("Geolocation is not supported by this browser")
                break;
                case error.POSITION_UNAVAILABLE:
                alert("Geolocation is not supported by this browser")
                break;
                case error.TIMEOUT:
                alert("Geolocation is not supported by this browser")
                break;
                case error.UNKNOWN_ERROR:
                alert("Geolocation is not supported by this browser")
                break;
            }
        }
    }

It should be loading the button and asking for the location through the alert but it is not working. Nothing is showing up in the console either.

And then here is the output with the inspect showing me CSP has blocked my JS.

enter image description here

Trying to mock all the functions of a JavaScript class with Jest

I am trying to mock a JavaScript service class (AppInsightsService) that I pass in to a tool class (OrderHistoryTool) to use. I don’t want to return any data from the mock – I just want to ignore all calls to the service functions, and also allow me to pass in the mock when I create my tool that uses that service.

I have tried various and sundry examples that I have seen when searching online, but they are not working for me. I’m sure I’m doing something wrong, but I’m not sure what it is.

Here is a nutshell of the service class that I want to mock:

@Injectable()
export class AppInsightsService {
  constructor(private readonly config: ConfigService) {
...
  }

  async postEvent(appInsightsEventDTO: AppInsightsEventDTO) {
...
  }
...

Here is the tool class that uses the service:

export class OrderHistoryTool extends DynamicStructuredTool {
  constructor(
    ...
    appInsightsService: AppInsightsService,
  ) {
    super({
...
      }),
      func: async (payload: OrderHistoryInput): Promise<string> => {
        appInsightsService.postEvent(
          {
            name: 'OrderHistoryRequested',
            properties: {
              conversationId: conversationId,
              athleteId: athleteId,
            },
          });
...

Here is my test:

const appInsightsServiceMock = jest.mock('../../app-insights/app-insights.service', jest.fn());
import { AppInsightsService } from '../../app-insights/app-insights.service';

enableFetchMocks();

// NOTE: TRIED USING THIS TOO BUT SAME ERROR
// jest.mock('../../app-insights/app-insights.service', () => {
//   return {
//     AppInsightsService: jest.fn().mockImplementation(() => {
//       return jest.fn().mockImplementation(() => {
//         return undefined;
//       });
//     }),
//   };
// });

describe('orderHistory - unit tests', () => {

  it('verify correct output', async () => {

    // NOTE: TRIED USING THIS TOO BUT SAME ERROR
    // const appInsightsServiceMock = jest.fn();

    const orderHistoryTool = new OrderHistoryTool(
      ...
      appInsightsServiceMock as unknown as AppInsightsService,
    );

    const result = await orderHistoryTool.invoke(
      {
        orderNumber: '123456',
      },
    );

I am getting an error when I try to run the test. It is failing when it tries to execute the postEvent() function from the service:

    [tool/error] [1:tool:order_history] [37ms] Tool run errored with error: "appInsightsService.postEvent is not a function
    TypeError: appInsightsService.postEvent is not a functionn    at OrderHistoryTool.func (orderHistory.ts:63:28)n    at OrderHistoryTool._call 

How do I create a mock of the class that will mock all the functions, and allow the user to call those functions as if they are real?

Dynamically creating a reusable, editable, and savable clipping path with bezierCurveTo() for image masking in canvas

I want to dynamically create, with mouse, savable, reusable and editable bezier curve paths comprising moveable points and handles just like the pen tool allows in Photoshop. I would use these for masking parts of an image for composite layering. I’m looking for a lightweight vanilla javascript solution that I can work with, expand, and learn from.

Because of my current very little knowledge of HTML5 canvas applications, I could only programmatically supply clipping path values via bezierCurveTo() for masking an image through an irregular shape, but I am looking for a solution that allows me to dynamically draw, edit, reuse, and save clipping paths for image mask creation just like the pen tool in Photoshop provides. Here is the programmatical version I tried so far in this fiddle:

Note: Using img.onload for example only.

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {

// Save the state, so we can undo the clipping
ctx.save();

var xoff = 10; //  pixel x-offset of handle (when moved dynamically)
var yoff = 10; //  pixel y-offset of handle (when moved dynamically)
    
// This is the irregular shape
ctx.beginPath();
ctx.moveTo(29 + xoff, 55 + yoff);
ctx.bezierCurveTo(18 + xoff, 37 + yoff, 39 + xoff, 16 + yoff, 48 + xoff, 28 + yoff);
ctx.bezierCurveTo(82 + xoff, 75 + yoff, 162 + xoff, 5 + yoff, 155 + xoff, 18 + yoff);
ctx.bezierCurveTo(128 + xoff, 73 + yoff, 154 + xoff, 123 + yoff, 167 + xoff, 131 + yoff);
ctx.bezierCurveTo(186 + xoff, 143 + yoff, 111 + xoff, 145 + yoff, 96 + xoff, 148 + yoff);
ctx.bezierCurveTo(81 + xoff, 151 + yoff, 24 + xoff, 154 + yoff, 34 + xoff, 135 + yoff);
  
ctx.closePath();

// Clip to the current path
ctx.clip();
    
ctx.drawImage(img, 0, 0);
    
// Undo the clipping
ctx.restore();
}

// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";

In attempting to solve my problem, I analyzed pertinent code made freely available in this post, but I can’t quite grasp how to conjugate only what is strictly needed for implementing the dynamic aspect of drawing clipping paths with bezierCurveTo().

Lastly, I want to implement the clipping path functionality into this freely available javascript-canvas-image-mask application. I would add a pen tool option right over the paint brush tool option that is already implemented in that code. Therefore, the javascript-canvas-image-mask application will be the UI/UX template used to provide both pen and paint brush tools for image masking.

So any working samples, hints or suggestions you want to offer me should be applicable to the javascript-canvas-image-mask application mentioned in the above link. Lean and simple is best – I’m not interested in adopting existing frameworks because they usually provide many more functionality than I actually need.

Thank you for your guidance, can’t wait to get my hands more dirty on this one.