Change constructor function’s ‘prototype’ property and two reference differences

//1)
function Rabbit() {}
Rabbit.prototype = {
  eats: true
};

let rabbit = new Rabbit();

Rabbit.prototype = {};

alert( rabbit.eats ); // true

//2)
function Rabbit() {}
Rabbit.prototype = {
  eats: true
};

let rabbit = new Rabbit();

Rabbit.prototype.eats = false;

alert( rabbit.eats ); // false

I expected ‘false’ in the 1) case..and contemplated about this mechanism and conclude something on my own. please see if I am right 🙂

Here’s what happens:

1)
I define a Rabbit constructor function and set its prototype to an object with an eats property set to true.
I create a new instance of Rabbit using the new keyword and store it in the rabbit variable.
After that, I change the Rabbit.prototype to an empty object. However, this change does not affect the already created rabbit object.
When I try to access rabbit.eats, JavaScript first looks for the eats property directly on the rabbit object. Since the eats property is not found on the rabbit object, it goes up the prototype chain and finds it on the old prototype object { eats: true }. As a result, the alert shows true.

2)
the alert shows false.
In this case, I am modifying the eats property directly on the same object that the rabbit object points to through its [[Prototype]] link. So, the change is visible when accessing rabbit.eats.

Q)
I learned that objects assignning give varibles the address which is called object reference.
case 2) was easy to understand according to this. but I expected ‘false’ in the case 1).

My conclusion)
when I created ‘Rabbit’ function, the ‘Rabbit.prototype’ object is assigned to a memory. and in the case 2) ‘Rabbit’ and ‘rabbit functions share the same memory address however, in the case 1), when I assign ‘{}’ to the ‘Rabbit.prototype’property. they find new memory address and assign this to it so the first object and second object that assigned to ‘Rabbit.prototype’ have diffrent memory address so that Rabbit.prototype refer to new memory address and rabbit.eats refere to old one.

Am I right?

Rotating a PIXI.Graphics element around its center

I have a grid of white squares and trying to apply a mouseover event on each of them which will rotate only the hovered over square a certain degree. I have tried a lot of approaches (setting pivot points, position etc.) but I can’t get those little circles to rotate right on their position, they have a messed up rotation center which I just can’t seem to fix.

The code is below and the link to the pixi playground is:
https://www.pixiplayground.com/#/edit/2yYbsCe-rMay-VsRBiihC

// Define Variables
let width = window.innerWidth;
let height = window.innerHeight;


// Initialise application
let app = new PIXI.Application({ 
    width: width,         // default: 800
    height: height,        // default: 600
    antialias: true,    // default: false
    transparent: false, // default: false
    resolution: 1,       // default: 1
    resizeTo: window
  }
);


document.body.appendChild(app.view);

// Variables
let loader = new PIXI.Loader();
let sprite = new PIXI.Sprite();
let render = app.renderer;
let rWidth = render.width;
let rHeight = render.height;
let stage = app.stage;
let angle = 0.01;


let container = new PIXI.Container();
let count = 10;

let rows = Math.floor(render.height / count);
let cols = Math.floor(render.width / count);

let size = 50;
let margin = 2;

let rects = [];

for (let i = size; i < render.width - size + margin; i += size) {
    
    for (let j = size; j < render.height - size + margin; j += size) {            
        
    
        let rect = new PIXI.Graphics();
        rect.beginFill( 0xffffff )
        .drawRect( i, j, size - margin, size - margin);
        //rect.position.set( render.width/2, render.height/2 );
        rect.pivot.x = size/2;
        rect.pivot.y = size/2;
        rect.interactive = true;
        rect.mouseover = function() {
            rect.rotation += 1;
        }
        rects.push(rect);
        container.addChild(rect);
        
    };

};

stage.addChild(container);

app.ticker.add(function(delta) {
    
  rects.rotation -= delta;
});

I am getting” Invalid hook call. Hooks can only be called inside of the body of a function component. when i am trying to add an object to a scene”

I am using threejs in react and i am trying to add an object inot my scene to have some specific functions that update regularly Here is my code for the object :

import React, { useRef, useEffect } from "react";
import { useFrame, useThree } from "react-three-fiber";
import * as THREE from "three";

const Actor = () => {
  const meshRef = useRef();
  const { scene } = useThree();

  useEffect(() => {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const mesh = new THREE.Mesh(geometry, material);
    mesh.rotateY(Math.PI);

    // Set initial properties and functions
    mesh.instructions = [];
    mesh.target = new THREE.Object3D().copy(mesh, false);
    mesh.targetRadiansOnY = 0;
    mesh.currentRadiansOnY = 0;
    mesh.mass = 0.1;
    mesh.velocity = new THREE.Vector3();
    mesh.angularVelocity = 0.015;
    mesh.topSpeed = 0.05;
    mesh.topAccelleration = 0.0015;
    mesh.accelleration = new THREE.Vector3();
    mesh.currentInstruction = null;
    mesh.gravityForce = new THREE.Vector3(0.0, -0.01, 0.0);

    // Add mesh to the scene
    scene.add(mesh);
    meshRef.current = mesh;

    return () => {
      // Clean up the mesh when the component unmounts
      scene.remove(mesh);
    };
  }, [scene]);

  useEffect(() => {
    // Update function to consume commands
    const consumeCommands = () => {
      const mesh = meshRef.current;
      if (mesh.currentInstruction) {
        let instruction = mesh.currentInstruction;
        let movementType = instruction["type"];
        let movementValue = instruction["value"];
        let dir = null;
        switch (movementType) {
          case "move_forward":
            dir = new THREE.Vector3().subVectors(mesh.target.position, mesh.position);
            dir.setLength(mesh.topAccelleration);
            mesh.applyForce(dir);
            mesh.applyForce(mesh.gravityForce);
            mesh.velocity.add(mesh.accelleration);
            mesh._limitVelocity(mesh.topSpeed);
            mesh.position.add(mesh.velocity);
            mesh._limitGravity();
            mesh.accelleration.multiplyScalar(0.0);
            break;
          case "jump_forward":
            dir = new THREE.Vector3().subVectors(mesh.target.position, mesh.position);
            let upForce = new THREE.Vector3(0, (0.012 * (dir.length() / movementValue)), 0);
            dir.setLength(mesh.topAccelleration);
            mesh.applyForce(dir);
            mesh.applyForce(upForce);
            mesh.applyForce(mesh.gravityForce);
            mesh.velocity.add(mesh.accelleration);
            mesh._limitVelocity(mesh.topSpeed);
            mesh.position.add(mesh.velocity);
            mesh._limitGravity();
            mesh.accelleration.multiplyScalar(0.0);
            break;
          case "turn":
            if (movementValue === "turnLeft") {
              mesh.rotateY(mesh.angularVelocity);
              mesh.currentRadiansOnY += mesh.angularVelocity;
            } else {
              mesh.rotateY(-mesh.angularVelocity);
              mesh.currentRadiansOnY += mesh.angularVelocity;
            }
            break;
          default:
            console.log("command not implemented");
            break;
        }
        if (mesh._targetReached(movementType)) {
          mesh._nextAnimation();
        }
      }
    };

    // Set the consumeCommands function as an update function
    useFrame(() => {
      consumeCommands();
    });
  }, []);

  return null; // We don't render anything for this component
};

export default Actor;

When i run this code i get the error Invalid hook call. Hooks can only be called inside of the body of a function component.i dont know what i am doing wrong.This is my first time using threejs in react

How do I turn my current page displaying profiles into one that uses infinite scrolling?

Hi I’ve got a firestore database with a heap of profile documents and I’m displaying them on the webpage through v-for and I’ve been trying for a while now to get just 4 documents at a time and then on scrolling getting another four to increase user experience.
I originally tried getting just four documents but then I had no idea how to get the next four instead of just getting the same for over and over again, I’ve also tried many different examples online but none of them work either.
Heres what I have so far on the javascript page which gets the profiles from firestore.

const getPremium = () => {
    const Premium = ref([])
    const error = ref(null)

    
const load = async () => {
    try{
        const res = await projectFirestore.collection('Premium').limit(4).get()
        

        Premium.value = res.docs.map(doc => {
           console.log(doc.data())
           return {...doc.data(), id: doc.id}
        })
    }
    catch (err){
        error.value = err.message
        console.log(error.value)
    }
    }

    return { Premium, error, load}
}

export default getPremium

And here is the vue page which I want to show all the profiles with infinite scrolling.

<script setup>


import getPremium from "../Composables/getPremium.js";
const {Premium, error, load} = getPremium();
load();





</script>

<template>


<br> 
 <div class="grid gap-x-5 gap-y-5 grid-cols-2 grid-rows-fit mx-5 md:grid md:gap-2 md:grid-cols-4 md:grid-rows-fit md:mx-20 lg:grid lg:gap-4 lg:grid-cols-4 lg:grid-rows-fit lg:mx-20 xl:grid xl:gap-4 xl:grid-cols-4 xl:grid-rows-fit xl:mx-20 2xl:grid 2xl:gap-4 2xl:grid-cols-4 2xl:grid-rows-fit 2xl:mx-20">

 <div v-for =" Premiums in Premium" :key="Premiums.id" >
 <router-link :to="{ name: 'Samplepremium', params: { id: Premiums.id }}">
 <div class= "hover:scale-105 transition ease-in-out duration-300 bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-900 text-neutral-400 font-bold rounded-xl">
  <br>
     <p class="text-xl">{{ Premiums.name }}</p>
     <div class="relative">
     <img :src= "Premiums.Pic1"  class="object-contain px-1 inline-block w-96 h-44 md:w-60 md:h-80 lg:w-60 lg:h-80 xl:w-60 xl:h-80 2xl:w-60 2xl:h-80 transition ease-in-out duration-300">
     <p class="bg-red-700 text-slate-300 text-xl absolute top-0 w-full">{{ Premiums.det1 }}</p>
     <p class="bg-red-700 text-slate-300 text-xl absolute bottom-0 w-full"> {{ Premiums.det2 }} </p>
    </div>
     <div class="grid grid-cols-2 grid-rows-fit text-left ml-6">
     <p>Age:</p>
     <p>{{ Premiums.det3 }}</p>
     <p>Location:</p>
     <p>{{ Premiums.det4 }}</p>
     <p>Rates:</p>
     <p>{{ Premiums.det5 }} /hr</p>
     <p>Phone:</p>
     <p>{{ Premiums.det6 }}</p>
   
    </div><br>
  </div>
  </router-link>
  </div>
</template>

I’ve taken out any attempts I’ve made to fetch another 4 as they just continually get the same 4 and don’t put any others on the page, if anyone can show me how to do this with this code it would be greatly appreciated.

change auto traffic light to manual

I want when I click to a button traffic light switch to manual from auto


let auto = () => {
    setTimeout(handleRed, 1000);
    setTimeout(handleGreen, 7000);
    setTimeout(handleYellow, 13000);
    setTimeout(auto, 14000);
}

auto();

what should I do here?

Positioning Cursor in a Text Editor

I am building a simple text editor, and I want to implement the functionality where the user can click on any written text and start editing it.

I have created a caret div, which represents the cursor, and I position it based on the clicked position. However, I’m facing an issue where if I click in the middle of a letter, the caret is being positioned there, but I want it to be shown after the letter.

To illustrate the problem, I have attached two screenshots:

what is happining
enter image description here

what i want
enter image description here

Red caret is basically a div whose top and left I am setting based on mouse click position.

In the desired behavior, the red caret div is positioned after the clicked letter.

I have tried to understand the logic used in existing text editors like Visual Studio Code, but the code is quite complex.

I would greatly appreciate any help or guidance on how to achieve the desired behavior.

I tried to understand how other code editors like vscode is generating caret position but there code is complex to understand

Stripe payment redirection issue

We have payment button in our website and we are using stripe invoice creation method for the stripe payment and it should be mandatory go with stripe invoice method. When users are clicking the payment button, we are creating the stripe invoice URL and users are redirecting to that invoice URL for the payment. But as of now we don’t have option to set success URL in the stripe. So how can we close the or how can we redirect the users back to our website after user redirected to stripe invoice URL. Any alternate solution to solve the redirection issue after completed the payment?
Currently when the user done the payment, user are still in the stripe invoice page.

Thanks in Advance
Roshil

Send email using Nodemailer and Gmail with display name (e.i. company name)

The problem I’m having is when I send an email using Gmail and Nodemailer, it only displays the email and not the display name (e.g., Spotify).

Here’s an example of what I want to achieve:

Display name example image

My code for sending the email:

const smtpTransport = nodemailer.createTransport({
       host: 'smtp.gmail.com',
       service: 'Gmail',
       port: 587,
       secure: true,
       auth: {
           user: '[email protected]',
           pass: 'xxxxxxxxx',
       },
})
const mailOptions = {
    to: user.email,
    from: {
        name: 'Company Name',
        address: '[email protected]'
    },
    subject: 'Password Reset Link',
    html: `<h1>Password Reset Link</h1>
           <a href="http://${req.header.host}/reset/${token}"></a>`
    }
smtpTransport.sendMail(mailOptions, (err) => {
    req.flash('success', 'Reset link was sent to ' + user.email)
    done(err, 'done')
})

I tried changing “Send mail as” in my Gmail account settings, but it still doesn’t display my company name and instead only displays my email.

Link to what I tried:

https://support.google.com/mail/answer/8158?hl=en#:~:text=See%20all%20settings.,show%20when%20you%20send%20messages.

Thank you! 😉

How can i trigger the function based on the value of the dropdown in React?

I have a problem with a code, I’m coding a drawing tool for soccer drills like on soccerddrive.com/draw and my problem is that I dont know how I can trigger different functions based on what value is selected on the dropdown. Just for information i use React with UseState and UseEffect.

      <div>
      <label>Players: </label>
      <select value={selectedPlayer} onChange={handlePlayerChange}>
        <option value="Player 1">Player 1</option>
        <option value="Player 2">Player 2</option>
        <option value="Player 3">Player 3</option>
      </select>
    </div>

so every option should draw a player on the field like this:

    if (addingPlayer) {
      const rect = canvasRef.current.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const newPlayer = { x, y, id: players.length + 1, playerType: props.selectedPlayer }; // Add playerType to the player object
      handleAddPlayer(event);
      setPlayers((players) => [...players, newPlayer]);
    }

Adding access controls to users in KeystoneJS

everyone!

I’m learning about KeystoneJS referring its manual. In this manual, I’ve stuck at an area of how to add access controls from the back-end to users which has labeled as admin. So, I’m referring the given examples in the KeystoneJS Manual

The given example in the following code is unclear how to figure out this with my code

const isAdmin = ({ session }: { session: Session }) => session?.data.isAdmin;

as

const isAdmin = ({ session }) => session?.data.isAdmin;

But when I try to add access controls to Post list, it won’t work for the users that I’ve already created in the database as admin.

The problem is, when I start the server, it is loading normally the admin route. I don’t see any error message in the console if I’ve made something wrong with the code

So, if someone could have any idea about how could I resolve this issue, please guide me. I’ll provide all the code down below how I’ve configured my application.

This is my keystone.js file

// Requiring configuration modules
const { config } = require("@keystone-6/core");
const { withAuth, session} = require("./auth");

// Requiring models
const User = require("./models/User");
const Post = require("./models/Post");

// Initializing configuration and settings up
export default config(
    withAuth({
        db: {
            provider: 'mysql',
            url: 'mysql://root:Kist%40Ride%23007@localhost:3306/keystone',
        },
        lists: {
            User,
            Post
        },
        session,
        ui: {
            isAccessAllowed: (context) => !!context.session?.data,
        },
    })  
);

This is my auth.js file

const { createAuth } = require("@keystone-6/auth");
const { statelessSessions  } = require("@keystone-6/core/session");

const { withAuth } = createAuth({
    listKey: 'User',
    identityField: 'email',
    sessionData: 'isAdmin',
    secretField: 'password',
    initFirstItem: {
        fields: ['name', 'email', 'password']
    }
});

let sessionSecret = '-- DEV COOKIE SECRET; CHANGE ME --';
let sessionMaxAge = 60 * 3;

const session = statelessSessions({
    maxAge: sessionMaxAge,
    secret: sessionSecret
});

module.exports = {
    withAuth,
    session
};

This is my post.js file for Post list

const { list } = require("@keystone-6/core");
const { allowAll } = require("@keystone-6/core/access");
const { password, text, relationship, checkbox } = require("@keystone-6/core/fields");

module.exports = list({
    access: allowAll,
    fields: {
        name: text({
            validation: {
                isRequired: true
            }
        }),
        email: text({
            validation: {
                isRequired: true
            },
            isIndexed: 'unique'
        }),
        password: password({
            validation: {
                isRequired: true
            }
        }),
        isAdmin: checkbox(),
        posts: relationship({
            ref: 'Post',
            many: true
        }),
    }
});

This is my user.js file for User list

const { list } = require("@keystone-6/core");
const { allowAll } = require("@keystone-6/core/access");
const { document } = require("@keystone-6/fields-document");
const { text, timestamp, relationship, select, checkbox } = require("@keystone-6/core/fields");

const isAdmin = ({ session }) => session?.data.isAdmin;

module.exports = list({
    access: {
        operation: {
            create: isAdmin
        }
    },
    fields: {
        title: text(),
        isPublished: checkbox(),
        publishedAt: timestamp(),
        author: relationship({
            ref: 'User',
            many: false,
        }),
        content: document({
            formatting: true,
            links: true,
            dividers: true,
            layouts: [
                [1, 1],
                [1, 1, 1],
                [2, 1],
                [1, 2],
                [1, 2, 1],
            ],
        }),
        status: select({
            options: [{
                label: 'Published',
                value: 'published'
            }, {
                label: 'Draft',
                value: 'draft'
            }],
            defaultValue: 'draft',
            ui:{
                displayMode: 'segmented-control'
            }
        }),
    }
});

Note that, I’m using JavaScript instead of TypeScript for KeystoneJS

I hope someone could help me to resolve this problem.

Thank you!

How can i get string values from inputs rather than objects?

I have a div and, inside that div, I’m generating dynamically input tags depending on a number wrote by the user. When the user clicks on the submit button, i have to get all the values of the inputs in an array and store it in the database. I’m using the firestore database. My problem is that whenever I tried to save the values of the inputs in the db, I have an error saying that the values of the inputs are UNDEFINED. I think the problem is in the values i’m getting from the inputs. They are not strings but objects.

Here’s my htlm code :

<div>
        <div id='dates' ref={myRef} className='fields_container'>
            {
                array.map(index => 
                  <input key={index} type="date"/>
                )
            }
        </div>
        <div className="btn">
            <Button 
            variant="contained" 
            size="large" 
            onClick={handleClick}
            sx={
                {
                    fontSize: 25,
                    color: "black",
                    backgroundColor: "#d19c97",
                    fontFamily: "'Caveat', cursive",
                    boxShadow: "2px 2px 52px black",
                    '&:hover': {
                        backgroundColor: "black",
                        color: "white",
                        boxShadow: "2px 2px 52px black"
                    }
                }
            }
            >
                Suivant
            </Button>
        </div>
    </div>

and here is my handleClick function that is responsible of saving in the db:

const handleClick = async () => {
    // initialize array for the input values
    let values = []

    // save input values in array
    array.map(index => values.push(myRef.current.children[index].value))
    
    try {
        const clientRef = await doc(db, "SEANCES_COLLECTIONS", clientName)
        await setDoc(clientRef, {seances: values}, {merge: true})

        console.log('réussie !')
        setLoading(false)
    } catch (error) {
        //displaying all the input values on the console
        console.log(values)
        //displaying error saying that all my values are undefined
        console.log(error)
    }
}

and here is the values and the error the console is displaying:

enter image description here

How to fetch data using App Routes from NextJS and Prismic? I’m currently only being able to render uid fields

I’m using Prismic and NextJS. After reading their documentation on how to fetch data using the new App folder, I created this src/[uid]/page.jsx file

import { createClient } from "@/prismicio";

export default async function Page({ params }) {
  const client = createClient();

  const page = await client.getByUID("post", params.uid);

  return <main>{page.uid}</main>;
}

Which is returning the uid just fine.

The problem arises when I try to fetch whatever other data. In my schema (custom type) a few fields like title and content. But whenever I try to make {page.title} it doesn’t work. I get no error from it, it simply doesn’t render anything.

I tried a few things to fix this. First, I tried this snippet from the Prismic documentation itself

import { createClient } from "@/prismicio";

export default async function Page({ params }) {
  const client = createClient();

  const page = await client.getByUID("page", params.uid);

  return <main>{page.data.title}</main>;
}

But I get the following error. And by the way, titulo1 is the value passed to the uid field in my documents within Prismic.

Error: [function at(..)] unexpected field ‘my.page.uid’ on line:1
col:6 in query ‘[[at(my.page.uid, “titulo1”)]]’ [[at(my.page.uid,
“titulo1”)]]

I also tried removing the params.uid. That gets me an error as well.

Then, I tried doing something like this: const page = await client.getByUID("post", params.uid, params.title);

But this simply have no effect and changes nothing.

Finally, tried to simply use params as some of their examples. In that case I’d get the following error

Error: ‘]’ expected but ‘[‘ found on line:1 col:2 in query
‘[[at(my.post.uid, [object Object])]]’ [[at(my.post.uid, [object
Object])]]

I don’t know if this is relevant or not but my prismicio.js route configuration is this

const routes = [{
    type: "post",
    path: "/:uid",
  },
];

Also, as it could be related, when I try to query all documents of type post using the snippet they have in their documentation I get an error as well.

import { createClient } from "@/prismicio";

export default async function Page() {
  const client = createClient();

  const pages = await client.getAllByType("post");

  return (
    <ul>
      {pages.map((page) => (
        <li>{page.data.title}</li>
      ))}
    </ul>
  );
}

And the error is

Error: Objects are not valid as a React child (found: object with keys
{type, text, spans}). If you meant to render a collection of children,
use an array instead.

So, I’m confused on how to move forward as I tried to replicate what they have in their documentation but I’m failing to do so. Any ideas on how to fix this?

How is the arrow function syntax different from the function syntax [duplicate]

i have tried to reference an arrow function b

can one reference an arrow function,i mean call it and then initialize it later?
I ask this because when I use the function(){} syntax it works perfectly fine but with the arrow function i throws an error.in javascript

form.addEventListener(‘submit’,getItems)

function getItems(){} works fine
but
const getItems = () =>{} doesn’t work

functionality google chrome

I have a small question for all who use Google Chrome browser what functionality you lack in this popular browser?

#JS #CHROME #GOOGLECHROME #Google #programing #extensions

#JS #CHROME #GOOGLECHROME #Google #programing #extensions

ExpiryMap is getting set but doesn’t remember when the function is called again?

what is the right way to use expiry-map in javascript/typescript

It seems to be getting set properly but seems like it forgets with end of the function.

This is my code.

import ExpiryMap from 'expiry-map'
const KEY_ACCESS_TOKEN = 'accessToken'
const cache = new ExpiryMap(10 * 1000)

export async function getChatGPTAccessToken(): Promise<string> {
  if (cache.get(KEY_ACCESS_TOKEN)) {
    return cache.get(KEY_ACCESS_TOKEN)
  }
  console.log("Couldnt find accessToken in cache", cache)
  const resp = await fetch('https://example.com/api/auth/session')
  const data = await resp.json().catch(() => ({}))
  if (!data.accessToken) {
    throw new Error('UNAUTHORIZED')
  }
  cache.set(KEY_ACCESS_TOKEN, data.accessToken)
  console.log("accessToken set to: ", data.accessToken);
  console.log("accessToken get from:", cache.get(KEY_ACCESS_TOKEN));// <-- it has the new value set, so it is getting set properly
  return data.accessToken
}

getChatGPTAccessToken() is being called from another file and it isn’t part of any class.