Typescript: how to change object to Class object with cast

In angular 18 I have usual TypeScript (“module”: “ES2022”)

I have basic class:

class Item {
  id: number = 0;
  title: string = '';
  active: boolean = false;
  date: Date = new Date();

  getTitle() {
    return this.title;
  }
}

And some object (from Json for example):

const someObj = {
  id: 1,
  title: 'some title',
  active: 1 // notice that type here in number, not boolean
}

I want to create new object with class Item,
with all methods available, and with all properties from someObj casted to types from class.

I tried:

const realItem = new Item();
const myItem = <Item> someObj;
const myItem2 = someObj as Item;
const myItem3 = <Item> someObj as Item;
console.log(realItem)
console.log(myItem);
console.log(myItem2);
console.log(myItem3);

None of this ways gives the real Class object, like realItem.

enter image description here

And of course, the method getTitle is not available this way.

The only way I see, to make huge constructor, with checking types:

  constructor(res: any = {}) {
    Object.keys(res).forEach(key => {
      if (this.hasOwnProperty(key)) {
        const type = typeof this[key as keyof typeof this];
        if (type === 'boolean') {
          // @ts-ignore
          this[key as keyof typeof this] = !!res[key];
        } else if (type === 'number') {
          // @ts-ignore
          this[key as keyof typeof this] = +res[key];
        } else if (type === 'string') {
          // @ts-ignore
          this[key as keyof typeof this] = String(res[key]);
        } else if (type === 'object' && this[key as keyof typeof this] instanceof Date) {
          // @ts-ignore
          this[key as keyof typeof this] = new Date(res[key]);
        } else {
          this[key as keyof typeof this] = res[key];
        }
      }
    })
  }

But I can’t believe , that there is no simple and right way to do this.

I am writing a .sh script to automate the creating the docusaurus and hosting to github

here when I execute the creation of docusaurus command it halts and never comes out of loop post executing

here is the command: when I try to execute in git bash
npx create-docusaurus@latest my-website classic

[enter image description here] (https://i.sstatic.net/3KwSEKpl.png)

Please help to fix this, not sure why its halting and not coming out of this command post executing.

I tried executing the same command in command prompt and PowerShell it is working fine as expected. But not use why in git bash?

How to hide cut | copy | Paste menu on double tap or long press in input box on chromium

I had an integrated Chromium application where I needed to hide the menu that appeared on double-tap or long press on a POS device or touch laptop, as shown in the image below.

I tried the code below, which works only on div elements. However, we need it to be disabled for text boxes as well.

 {
  -webkit-user-select: none; /* Safari */
  -ms-user-select: none; /* IE 10 and IE 11 */
  user-select: none; /* Standard syntax */
 }

Screen shot showing copy menu on long press / double tap

How to stop server refresh event from logging event multiple times?

I am trying to learn Node.js. While combining events with server during self-practicing, I am facing a weird problem.

const {v4:uuid} = require('uuid');
const {format} = require('date-fns');
const Eventemit = require('events');      //Eventemit is a class
const os = require('os');
const path = require('path');
const fs = require('fs');
const http = require('http');


const user = os.userInfo().username;

const eventemitter = new Eventemit();    //eventemitter is an object of the class Eventemit

const server = http.createServer((req, res)=>{

    const date_time = `${format(new Date, 'dd.MM.yyyy  HH:mm:ss')}`
    eventemitter.on('log', ()=>{
        const req_string = `Log event: '${uuid()}' emitted by ${user} at time:    ${date_time} hrs.n`;
    
        if(!fs.existsSync(path.join(__dirname, 'server_folder'))){
            fs.mkdir(path.join(__dirname, 'server_folder'), (err)=>{
                if(err){
                    console.error(err);
                }
            });
        }
    
        fs.appendFileSync(path.join(__dirname, 'server_folder', 'server_log.txt'), req_string, 'utf-8');

        res.write(req_string);
        res.end();
    })
    eventemitter.emit('log');
})

server.listen(5000);

When I am refreshing localhost:5000 on browser, the log text file is registering it multiple times in one time instance (please refer to the attached screenshot).

enter image description here

Please help me with this issue, thanks in advance!

Why ++ operator didn’t work in prod mode?

I have a problem with this reducer. There is button with onClick function which triggers NextBox action to change a state of React UseContext.
Application is created with Vite, and when I’m running npm run dev it works correctly (button changes the state), but when I run npm run build && npm run preview button does nothing.

export function Reducer(state: State, action: Action) {
  switch (action) {
    case Action.NextBox:
      return { ...state, currentBox: state.currentBox ++ };
    case Action.PreviousBox:
      return { ...state, currentBox: state.currentBox -- };
    default:
      return state;
  }
}

I found a solution to change currentBox ++ into currentBox +1 and it works now on built app, but I have no idea still why previous solution worked in dev mode but didn’t in prod mode.
Any ideas?

Email,name and image not updating after logging in from different account

so like, when i login the first time, it works perfectly, but when i login again with different gmail, the name email and image displayed at dashboard page is not updated,
i asked gpt,gemini etc, but they werent helpful at all, cookies is getting updating properly when logging out, i checked it multiple times

here is the video of the problem:

here are some useful codes and debugging that i tried myself

this is the output of api/users/dashboard
debuggin output:

userId: 66d027dc93164109b87574cb
user: {
  _id: new ObjectId('66cf366a27efefd2c067d5fc'),
  name: 'aman_5909',
  email: '[email protected]',
  image: 'https://www.shutterstock.com/image-vector/default-avatar-profile-vector-user-260nw-1705357234.jpg',
  isVerified: true,
  createdAt: 2024-08-28T14:38:34.491Z,
  updatedAt: 2024-08-28T14:38:58.223Z,
  __v: 0
}

userId is the right one
but user is the wrong one


import { dbconnect } from "@/utils/dbconnect";
import { NextResponse } from "next/server";

dbconnect();

export async function POST(req) {
    try {
        // Create the response indicating successful logout
        const response = NextResponse.json({ message: "User logged out successfully" }, { status: 200 });
        
        // Set the access_token cookie to an empty string and expire it immediately
        response.cookies.set("access_token", "", {
            httpOnly: true,
            path: "/",  // Ensure this path matches where the cookie was originally set
            sameSite: "strict",
            expires: new Date(0)  // Expire the cookie immediately
        });
        
        console.log("User logged out successfully");
        return response;
    } catch (error) {
        console.error("Error in logout/route.js: ", error);
        return NextResponse.json({ error: "Something went wrong in logout/route.js" }, { status: 500 });
    }
}

import { getDataFromToken } from "@/helpers/getDataFromToken";
import User from "@/models/User";
import { dbconnect } from "@/utils/dbconnect";
import { NextResponse } from "next/server";

dbconnect();
export async function POST(req) {
    try {
        const userId = await getDataFromToken(req);
        console.log("userId:", userId);
        const user = await User.findOne({userId}).select("-password");
        console.log("user:", user);
        return NextResponse.json({ message: "User fetched successfully" , user });
    } catch (error) {
        return NextResponse.json({ error: "Something went wrong in dashboard/route.js" }, { status: 500 });
    }
}

import { dbconnect } from "@/utils/dbconnect";
import { NextResponse } from "next/server";
import User from "@/models/User";
import bcryptjs from "bcryptjs";
import jwt from "jsonwebtoken";

dbconnect();

export async function POST(req) {
    try {
        const body = await req.json();  // <-- Properly await the json() method
        const { email, password } = body;
        console.log("email:", email, "password:", password);

        const existingUser =  await User.findOne({ email });
        if (!existingUser) {
            console.log("User does not exist");
            return NextResponse.json({ error: "Invalid email or password" }, { status: 400 });
        }

        const isPasswordCorrect = await bcryptjs.compare(password, existingUser.password);
        if (!isPasswordCorrect) {
            console.log("isPasswordCorrect:", isPasswordCorrect);
            return NextResponse.json({ error: "Invalid email or password" }, { status: 400 });
        }

        const token = jwt.sign({ email: existingUser.email, id: existingUser._id, name: existingUser.name }, "test", { expiresIn: "1h" });
        console.log("token:", token);

        const response = NextResponse.json({ result: { email: existingUser.email } }, { status: 200 });
        console.log("email:", existingUser.email);
        response.cookies.set("access_token", token, {
            httpOnly: true,
            sameSite: "strict",
            path: "/"
        });
        return response;
    } catch (error) {
        console.log("error in login/route.js: ", error);
        return NextResponse.json({ error: "Something went wrong in login/route.js" }, { status: 500 });
    }
}

import jwt from "jsonwebtoken";

export const getDataFromToken = (req) => {
    try {
        const token = req.cookies.get("access_token")?.value || "";
        console.log("token:", token);
        if (!token) {
            throw new Error("Token not found");
        }
        
        const decodedToken = jwt.verify(token, "test");
        console.log("decodedToken:", decodedToken.id);
        return decodedToken.id;
    } catch (error) {
        console.error("An error occurred in getDataFromToken:", error.message);
        return null; // Or throw an error, depending on how you want to handle it
    }
}

I have mentioned what i tried and what i was expecting above

How to Properly Center Two Groups of PCBs with Test and Impedance Coupons in HTML Canvas?

I’m working on a PCB panel visualization in an HTML5 canvas where I need to place two groups of PCBs for a given panel area. Each group has:

4 test coupons (2 vertical, 2 horizontal) surrounding the PCBs.
A dynamic number of impedance coupons, placed based on a given number (e.g., numImpedance = 1 should place 1 on the left; numImpedance = 3 should place 1 on the left, 1 on the top, and 1 on the right).

What I’m Looking For:
I need help to:

Correctly place the vertically aligned test coupons so they don’t overlap the midline.
Ensure there’s adequate space for the impedance coupons and they are placed without overlapping.
Ensure both groups are centered and properly aligned within the panel area.
Any suggestions or improvements on the logic or approach would be greatly appreciated!

Here’s my approach:
Calculate the number of PCBs to draw after subtracting space for test coupons and impedance coupons.
Center the PCB area within the available space.
Surround it with test coupons.
Surround it with the given number of impedance coupons.

const canvas = document.getElementById('pcbCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 406;
canvas.height = 533;

const x_border = 406;
const y_border = 533;

const top_mn = 17;
const bot_mn = 17;
const left_mn = 17;
const right_mn = 17;

const routerGap = 1.6;

// Test coupon dimensions
const couponWidth = 35.0; // Width in mm
const couponHeight = 195.0; // Height in mm

function drawPCBs2withImpedance(orientation) {
  if (orientation === "horizontal") {
    pcbWidth = 93;
    pcbHeight = 100;
  } else {
    pcbWidth = 100;
    pcbHeight = 85;
  }

  // Clear the canvas and set the background
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#505050";
  ctx.fillRect(0, 0, x_border, y_border);

  // Calculate active area dimensions
  const activeWidth = x_border - left_mn - right_mn;
  const activeHeight = y_border - top_mn - bot_mn; // Split height into two halves

  ctx.fillStyle = "Gold";
  ctx.fillRect(left_mn, top_mn, activeWidth, activeHeight);

  var mid_active_panel_len = activeHeight / 2.0;

  var mid_line_len = y_border / 2.0;
  mid_active_panel_len = mid_active_panel_len;
  console.log(activeHeight, y_border, mid_active_panel_len, mid_line_len)

  var mid_active_panel_bre = activeWidth / 2.0;
  var half_mid = mid_active_panel_bre / 2.0
  mid_active_panel_bre = mid_active_panel_bre + left_mn + routerGap;

  horz_end = x_border - right_mn;
  ctx.beginPath();
  ctx.moveTo(left_mn, mid_line_len);
  ctx.lineTo(horz_end, mid_line_len);
  ctx.strokeStyle = "Crimson";
  ctx.stroke();
  var numImpCoupons = 2;
  var impCouponWidth = 25;
  var impCouponHeight = 200;

  var impCoupns = calculateImpedanceCoupons(numImpCoupons);
  console.log(impCoupns)
  // Assuming impCoupns contains the number of coupons on each side
  const impCouponSpaceLeft = impCoupns.left * (impCouponWidth + routerGap);
  const impCouponSpaceRight = impCoupns.right * (impCouponWidth + routerGap);
  const impCouponSpaceTop = impCoupns.top * (impCouponWidth + routerGap);
  const impCouponSpaceBottom = impCoupns.bottom * (impCouponWidth + routerGap);

  console.log("sss", impCouponSpaceTop + impCouponSpaceBottom)

  // Total available width and height after placing impedance coupons
  const availableWidth = x_border - impCouponSpaceLeft - impCouponSpaceRight - left_mn - right_mn - 2 * (couponWidth + routerGap);
  // const availableHeight1 = mid_line_len - impCouponSpaceTop - impCouponSpaceBottom - 2 * (couponWidth + routerGap);
  const availableHeight1 = (mid_line_len - top_mn) - impCouponSpaceTop - impCouponSpaceBottom - 2 * (couponWidth + routerGap);

  console.log("availableHeight", mid_line_len, availableHeight1)

  // Calculate number of PCBs that can fit in the remaining area
  const numPcbsX1 = Math.floor(availableWidth / (pcbWidth + routerGap));
  const numPcbsY1 = Math.floor(availableHeight1 / (pcbHeight + routerGap));

  // Calculate the PCB area dimensions
  const pcbAreaWidth1 = numPcbsX1 * (pcbWidth + routerGap) - routerGap;
  const pcbAreaHeight1 = numPcbsY1 * (pcbHeight + routerGap) - routerGap;

  // Center the PCB area within the available space
  const pcbAreaX1 = (availableWidth - pcbAreaWidth1) / 2 + impCouponSpaceLeft + couponWidth + routerGap + left_mn;
  const pcbAreaY1 = (availableHeight1 - pcbAreaHeight1) / 2 + impCouponSpaceTop + impCouponSpaceBottom + couponWidth;
  // const pcbAreaY2 = mid_line_len + (availableHeight1 - pcbAreaHeight1) / 2 + impCouponSpaceTop + impCouponSpaceBottom + couponWidth + routerGap ;
  const pcbAreaY2 = mid_line_len + (availableHeight1 - pcbAreaHeight1) / 2 + impCouponSpaceTop + impCouponSpaceBottom + couponWidth + routerGap;
  ctx.fillStyle = "#00a2ed";

  console.log(numPcbsX1, numPcbsY1)
  for (let y = 0; y < numPcbsY1; y++) {
    for (let x = 0; x < numPcbsX1; x++) {
      const xPos = pcbAreaX1 + x * (pcbWidth + routerGap);
      const yPos = pcbAreaY1 + y * (pcbHeight + routerGap);
      ctx.fillRect(xPos, yPos, pcbWidth, pcbHeight);
    }
  }

  for (let y = 0; y < numPcbsY1; y++) {
    for (let x = 0; x < numPcbsX1; x++) {
      const xPos = pcbAreaX1 + x * (pcbWidth + routerGap);
      const yPos = pcbAreaY2 + y * (pcbHeight + routerGap);
      ctx.fillRect(xPos, yPos, pcbWidth, pcbHeight);
    }
  }
  ctx.fillStyle = "DarkOrange";
  // top coupon
  const topCouponX1 = pcbAreaX1;
  const topCouponY1 = pcbAreaY1 - couponWidth - routerGap;
  ctx.fillRect(topCouponX1, topCouponY1, couponHeight, couponWidth);

  //bottom coupon
  const bottomCouponX1 = pcbAreaX1 + pcbAreaWidth1 - couponHeight
  const bottomCouponY1 = pcbAreaY1 + pcbAreaHeight1 + routerGap
  ctx.fillRect(bottomCouponX1, bottomCouponY1, couponHeight, couponWidth);
  ctx.fillStyle = "Green";
  //Right Coupon
  const rightCouponX1 = pcbAreaX1 + pcbAreaWidth1 + routerGap;
  const rightCouponY1 = pcbAreaY1 - couponWidth - routerGap;



  //left coupon
  const leftCouponX1 = pcbAreaX1 - couponWidth - routerGap;
  const leftCouponY1 = pcbAreaY1 - couponWidth - routerGap


  ctx.fillStyle = "DarkOrange";
  // top coupon
  const topCouponX2 = pcbAreaX1;
  const topCouponY2 = pcbAreaY2 - couponWidth - routerGap;
  ctx.fillRect(topCouponX2, topCouponY2, couponHeight, couponWidth);

  //bottom coupon
  const bottomCouponX2 = pcbAreaX1 + pcbAreaWidth1 - couponHeight
  const bottomCouponY2 = pcbAreaY2 + pcbAreaHeight1 + routerGap
  ctx.fillRect(bottomCouponX2, bottomCouponY2, couponHeight, couponWidth);
  ctx.fillStyle = "Green";
  //left coupon
  const leftCouponX2 = pcbAreaX1 - couponWidth - routerGap;
  const leftCouponY2 = pcbAreaY2 - couponWidth - routerGap


  //Right Coupon
  const rightCouponX2 = pcbAreaX1 + pcbAreaWidth1 + routerGap;
  const rightCouponY2 = pcbAreaY2 - couponWidth - routerGap;


  if (pcbAreaWidth1 > couponHeight) {
    //Right Coupon
    ctx.fillRect(rightCouponX1, rightCouponY1, couponWidth, couponHeight);
    ctx.fillRect(rightCouponX2, rightCouponY2, couponWidth, couponHeight);

    ctx.fillRect(leftCouponX1, leftCouponY1, couponWidth, couponHeight);
    ctx.fillRect(leftCouponX2, leftCouponY2, couponWidth, couponHeight);

  } else {

    var adjustSpace = couponHeight - pcbAreaWidth1;
    console.log(pcbAreaWidth1, couponHeight, leftCouponX1, adjustSpace)
    ctx.fillRect(rightCouponX1 + adjustSpace, rightCouponY1, couponWidth, couponHeight);
    ctx.fillRect(rightCouponX2 + adjustSpace, rightCouponY2, couponWidth, couponHeight);

    ctx.fillRect(leftCouponX1 - adjustSpace, leftCouponY1, couponWidth, couponHeight);
    ctx.fillRect(leftCouponX2 - adjustSpace, leftCouponY2, couponWidth, couponHeight);
  }

  // Update active and non-utilized dimensions
  document.getElementById("act-length").innerHTML = "Active Breadth X Length : " + parseInt(activeWidth) + " X " + parseInt(activeHeight * 2);
  document.getElementById("non-act-length").innerHTML = "Non Utilized Breadth X Length : " + parseInt(x_border - activeWidth) + " X " + parseInt(y_border - (activeHeight * 2));
}



document.querySelectorAll('input[name="orientation"]').forEach(radio => {
  radio.addEventListener('change', (event) => {
    drawPCBs2withImpedance(event.target.value);
  });
});

drawPCBs2withImpedance('horizontal');



function calculateImpedanceCoupons(n) {
  if (n < 1) {
    console.log("The number of coupons must be at least 1.");
    var abc2 = {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
      xAxis: 0,
      yAxis: 0
    }
    return abc2;
  }

  let left = 0,
    top = 0,
    right = 0,
    bottom = 0,
    xAxis = 0,
    yAxis = 0;

  if (n === 1) {
    left = 1;
  } else if (n === 2) {
    left = 1;
    top = 1;
  } else if (n === 3) {
    left = 1;
    top = 1;
    right = 1;
  } else {
    left = 1;
    top = 1;
    right = 1;
    bottom = 1;

    // Distribute the remaining coupons
    let remainingCoupons = n - 4;
    if (remainingCoupons > 0) {
      let additionalCouponsPerSide = Math.floor(remainingCoupons / 4);
      let extraCoupons = remainingCoupons % 4;

      left += additionalCouponsPerSide + (extraCoupons > 0 ? 1 : 0);
      top += additionalCouponsPerSide + (extraCoupons > 1 ? 1 : 0);
      right += additionalCouponsPerSide + (extraCoupons > 2 ? 1 : 0);
      bottom += additionalCouponsPerSide;
    }
  }

  var abc = {
    left: left,
    top: top,
    right: right,
    bottom: bottom,
    xAxis: left + right,
    yAxis: top + bottom
  }

  return abc;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PCB Panel Visualization</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }
    
    canvas {
      border: 1px solid #000;
    }
    
    .controls {
      margin-bottom: 10px;
    }
  </style>
</head>

<body>
  <div class="controls">
    <label><input type="radio" name="orientation" value="horizontal" checked> Horizontal</label>
    <label><input type="radio" name="orientation" value="vertical"> Vertical</label>

    <div id="act-length"></div>
    <div id="non-act-length"></div>
  </div>
  <canvas id="pcbCanvas"></canvas>
</body>

</html>

Problem:
The vertically placed coupons are overlapping on the midline, which shouldn’t happen.
There is often no space for the impedance coupons due to the placement of other elements.
I want both groups to be centered and non-overlapping, but my current logic isn’t achieving this.

does nextjs render the child components on client if parent component is rendered on client

When I’m creating a custom authentication using firebase. I added the auth flow in one component(AuthComp) and had to use “use client” to make it work. Now if I add any component/page render as a child of this AuthComp will it be rendered server side or client side?

I tried finding answers but everywhere it says the answer is “client side” but if I look at the network tab the page seems to have generated server side.enter image description here

How to Add a Profile Image Upload Field in Auth0Lock SignUp Form?

I’m using Auth0Lock to handle user signups in my application. The default additionalSignUpFields option allows me to add fields like full_name and phone_number, but I need to add an image upload field for the user’s profile picture during signup.

I attempted to add a custom outside the Lock widget, but this field does not appear in the signup form, and it doesn’t seem to integrate well with Auth0’s internal handling of user metadata.

Is there any way to extend the Auth0Lock widget to include a file input field for image uploads? If not, what would be the best approach to handle image uploads during signup while using Auth0Lock?

Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Sign In with Auth0</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
</head>
<body>
  <script src="https://cdn.auth0.com/js/lock/12.5/lock.min.js"></script>
  <script>
    var config = JSON.parse(decodeURIComponent(escape(window.atob('@@config@@'))));
    var lock = new Auth0Lock(config.clientID, config.auth0Domain, {
      auth: {
        redirectUrl: config.callbackURL,
        responseType: (config.internalOptions || {}).response_type ||
          (config.callbackOnLocationHash ? 'token' : 'code'),
        params: config.internalOptions
      },
      theme: {
        primaryColor: 'green'
      },
      additionalSignUpFields: [
        {
          name: "full_name",
          placeholder: "Enter your full name",
          validator: function(name) {
            return {
              valid: name.length >= 2,
              hint: "Must be at least 2 characters"
            };
          }
        },
        {
          name: "phone_number",
          placeholder: "Enter your phone number",
          validator: function(phone) {
            var phone_number_pattern = /^[0-9]{10}$/;
            return {
              valid: phone_number_pattern.test(phone),
              hint: "Must be a valid 10-digit phone number"
            };
          }
        }
      ]
    });

    lock.show();
  </script>
</body>
</html>

how to learn javascript [closed]

I want to learn JavaScript. What can I do to get started? Please help me by giving a step-by-step explanation on how to learn JavaScript effectively.

please help me in that what can I do. I am beginner I want to learn JavaScript and jQuery please give me detail explanation step by step

how do view id datas in firebase

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.13.0/firebase-app.js";
import { addDoc, collection, getFirestore, getDocs, deleteDoc, doc} from "https://www.gstatic.com/firebasejs/10.13.0/firebase-firestore.js";

function editResume(index){    
    getDocs(collection(db,"users_resume_data")).then(edit_resume =>{
            
            let edit_resumes = edit_resume.data();
           
            const searchParams = new URLSearchParams(window.location.search); 
            const indexParam = searchParams.get('index'); 
            // const ls_data = JSON.parse(localStorage.getItem('allUserResumes'));

            document.getElementById("resName").innerHTML = edit_resumes[indexParam].resName;
            document.getElementById("resMobile").innerHTML= edit_resumes[indexParam].resMobile;
            document.getElementById("resMail").innerHTML = edit_resumes[indexParam].resMail;
            document.getElementById("resLinkedIn").innerHTML = edit_resumes[indexParam].resLinkedIn;
            document.getElementById("view_father_name").innerHTML = edit_resumes[indexParam].personal_details.father_name;
            document.getElementById("view_mother_name").innerHTML = edit_resumes[indexParam].personal_details.mother_name;
            document.getElementById("view_dob").innerHTML = edit_resumes[indexParam].personal_details.dob;
            document.getElementById("view_gender").innerHTML = edit_resumes[indexParam].personal_details.gender;
            document.getElementById("view_material_status").innerHTML = edit_resumes[indexParam].personal_details.material_status;
            document.getElementById("view_address").innerHTML = edit_resumes[indexParam].personal_details.address;
            document.getElementById("view_state").innerHTML = edit_resumes[indexParam].personal_details.state;
            document.getElementById("view_pin").innerHTML = edit_resumes[indexParam].personal_details.pincode;


            let view_skill_detail="";

            for(let each of ls_data[indexParam].personal_details.skills_details){
                view_skill_detail += `<li>${each}</li>`

            };
            document.getElementById("view_skills").innerHTML = view_skill_detail;

            let view_language_detail="";

            for(let each of ls_data[indexParam].personal_details.languages_details){
                view_language_detail += `<li>${each}</li>`
            }
            document.getElementById("view_languages").innerHTML = view_language_detail;

            let view_work_exp =""

            for(let each in ls_data[indexParam].work_experience){
                view_work_exp += `  <div>
                                        <div> <lable> Company Name : </lable> <span> ${ls_data[indexParam].work_experience[each].c_name} </span></div>
                                        <div> <lable> Designation : </lable> <span> ${ls_data[indexParam].work_experience[each].c_designation}</span></div>
                                        <div> <lable> Experience years: </lable> <span> ${ls_data[indexParam].work_experience[each].c_experience}</span></div>
                                        <div> <lable> Learned Skills  : </lable> <span> ${ls_data[indexParam].work_experience[each].c_learnSkill}</span></div>
                                        <div> <lable> About  : </lable> <span> ${ls_data[indexParam].work_experience[each].c_about}</span></div>
                                        <hr class="right-section-hr">
                                    </div>`
            }
            document.getElementById("view_work_experience").innerHTML = view_work_exp; 

            let view_education =""

            for(let each in ls_data[indexParam].education_qualification ){
                view_education += `<div>
                                        <div> <lable> Course Name : </lable> <span> ${ls_data[indexParam].education_qualification[each].course_name}</span></div>
                                        <div> <lable> PassOut Year : </lable> <span> ${ls_data[indexParam].education_qualification[each].passOut_year}</span></div>
                                        <div> <lable> Scored Percentage : </lable> <span> ${ls_data[indexParam].education_qualification[each].scored_percentage}</span></div>
                                        <div> <lable> Institute  : </lable> <span> ${ls_data[indexParam].education_qualification[each].institute}</span></div>
                                        <div> <lable> University or Board Name  : </lable> <span> ${ls_data[indexParam].education_qualification[each].university_or_board_name}</span></div>
                                        <hr class="right-section-hr">
                                    </div>`
            };

            document.getElementById("view_education").innerHTML= view_education;

            let view_project = ""

            for(let each in ls_data[indexParam].projects){
                view_project +=`<div>
                                    <div> <lable> Project Name : </lable> <span> ${ls_data[indexParam].projects[each].project_name}</span></div>
                                    <div> <lable> Description : </lable> <span> ${ls_data[indexParam].projects[each].p_description}</span></div>
                                    <div> <lable> Project link : </lable> <span> ${ls_data[indexParam].projects[each].p_link}</span></div>
                                    <div> <lable> Develope Tools  : </lable> <span> ${ls_data[indexParam].projects[each].develope_at}</span></div>
                                    <div> <lable> Institude or Company  : </lable> <span> ${ls_data[indexParam].projects[each].institude_or_company}</span></div>
                                    <div> <lable> My Contribution  : </lable> <span> ${ls_data[indexParam].projects[each].contribution}</span></div>
                                    <hr class="right-section-hr">
                                </div>`
            }

            document.getElementById("view_projects").innerHTML = view_project
        
        }
    )
}
window.editResume = editResume

We need the clarification

How to use Javascript’s drag and drop Api to sort rows and colums displayed as grid

I have the following grid:

    <html>
<head>
  <style>
      .grid {
          display: grid;
          grid-template-columns: 100px 100px 100px 100px 100px;
          grid-template-rows: 50px 50px 50px 50px;
          grid-gap: 10px;

          & > * {
              padding: 10px;
              border: 1px solid black;
          }

          & > div:first-child {
              border: none;
          }

          & .column-header {
              background-color: lightgray;
          }

          & .row-header {
              background-color: lightgray;
          }
      }
  </style>
</head>
<body>
<div class="grid">
  <div></div>
  <div class="column-header">Col 1</div>
  <div class="column-header">Col 2</div>
  <div class="column-header">Col 3</div>
  <div class="column-header">Col 4</div>

  <div class="row-header">Row 1</div>
  <div>Cell 1.1</div>
  <div>Cell 2.1</div>
  <div>Cell 3.1</div>
  <div>Cell 4.1</div>

  <div class="row-header">Row 2</div>
  <div>Cell 1.2</div>
  <div>Cell 2.2</div>
  <div>Cell 3.2</div>
  <div>Cell 4.2</div>

  <div class="row-header">Row 3</div>
  <div>Cell 1.3</div>
  <div>Cell 2.3</div>
  <div>Cell 3.3</div>
  <div>Cell 4.3</div>

  <div class="row-header">Row 4</div>
  <div>Cell 1.4</div>
  <div>Cell 2.4</div>
  <div>Cell 3.4</div>
  <div>Cell 4.4</div>
</div>
</body>
</head>

How to use Javascript drag and drop api to:

  1. drag any of the “Column headers” cells and rearrange the columns horizontally
  2. drag any of the “Row headers” cells and rearrange the rows vertically

?

Buildable libraries cannot import or export from non-buildable librarieseslint@nx/enforce-module-boundaries

I am working with an Angular monorepo using Nx, and I’ve run into an issue while trying to build a component library that’s set up to be publishable to npm. My project structure is as follows:

nx-monorepo-root
│
├── /apps
│  ├── /app1
│  └── /app2
│
├── /libs
│  ├── /shared-ui-lib
│  ├── /app1Lib
│  ├── /app2Lib
│  ├── /prime-ng-lib
│
├── /package
│  └── /component-lib
│
├── /tools
│
├── /node_modules
│
├── /dist
│
├── nx.json
├── workspace.json
├── tsconfig.base.json

I’ve created a buildable component library (component-lib) that I want to publish to npm. This library also depends on another library (prime-ng-lib) that wraps PrimeNG components.

Here’s the relevant code for component-lib:

// Import statements
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Button1Component } from './button1/button1.component';
import { PrimeNgLibModule } from '@monorepov2/prime-ng-lib'; // Importing the PrimeNG wrapper module

@NgModule({
  imports: [CommonModule, PrimeNgLibModule],
  declarations: [Button1Component],
  exports: [Button1Component]
})
export class G99UiLibModule {}

But when I try to import primeNgLibrary module in component lib I am getting below error which is fixed if I add eslint disable rule
Buildable libraries cannot import or export from non-buildable libraries eslint@nx/enforce-module-boundaries

When I try to build component-lib, I encounter the following error:


PS C:UsersDesktopWorkspaceLearningAngularg99monorepov2> npx nx build g99-ui-lib

> nx run g99-ui-lib:build:production

Building Angular Package

------------------------------------------------------------------------------
Building entry point 'g99-ui-lib'
------------------------------------------------------------------------------
- Compiling with Angular sources in Ivy partial compilation mode.
✖ Compiling with Angular sources in Ivy partial compilation mode.
 NX   Cannot destructure property 'pos' of 'file.referencedFiles[index]' as it is undefined.
Pass --verbose to see the stacktrace.

Additionally, when I remove the dependency on prime-ng-lib, the build process works fine. The code also works as expected when running locally.

Questions:

  • How can I resolve the issue of building a buildable library (component-lib) that depends on a non-buildable library (prime-ng-lib) in an Nx workspace?

  • Are there any recommended solutions or best practices for handling dependencies between buildable and non-buildable libraries in Nx?

**Additional Information:

I’ve tried using the –verbose flag but didn’t find much detail in the stack trace.
My Nx and Angular versions are up-to-date.

Login Not happening Correctly in Codeignitor php 7.4

When I click on Login button, 1) then login successfully message appears. 2) I also checked session is created successfully as I put response line $resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url); inside condition if ($this->session->has_userdata('email')), it shows session is also created. 3) I also checked overall code and debug the code in browser also. I cannot find out any reason why it comes back to the login page. That’s why I am here for your assistance. I attached relevent View file code, Controller code as well as js file code so that anyone can test it. Looking forward to your guideance

In view Login.php

<form class="form" method="post" action="<?php echo base_url().'front_ajax/login'; ?>" data-redirect="yes">
    <div class="edu_field_holder">
        <input type="text" class="edu_form_field require" name="email" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_p_email'));?>" autocomplete="off" value="<?php echo(isset($_COOKIE['UML'])) ? base64_decode(urldecode(base64_decode($_COOKIE['UML']))) : ''; ?>">
    </div>
    <div class="edu_field_holder">
        <input type="password" name="password" class="require edu_form_field" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_password'));?>" value="<?php echo(isset($_COOKIE['SSD'])) ? base64_decode(urldecode(base64_decode($_COOKIE['SSD']))) : ''; ?>">
    </div>
    
    <div class="col-lg-6 col-md-6 col-sm-12 col-12 text-md-right">
        <button class="edu_btn edu_btn_black" id="auth_login" type="button" data-action="submitThisForm"><?php echo html_escape($this->common->languageTranslator('ltr_login'));?></button>
    </div>      
</form>

In Controller Front_ajax.php

function login(){
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')){
        if(!empty($this->input->post('email',false)) && !empty($this->input->post('password',false))){          
            $email = trim($this->input->post('email',TRUE));
            $pass = md5(trim($this->input->post('password',TRUE)));     
            if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
                $stud_cond = array('enrollment_id'=>$email,'password'=>$pass);
            }else{
                $stud_cond = array('email'=>$email,'password'=>$pass);
            }
            $userDetails = $this->db_model->select_data('id,name,role,status,parent_id,teach_image,email,teach_batch,teach_subject,super_admin','users use index (id)',array('email'=>$email,'password'=>$pass),1);
            $studentDetails = $this->db_model->select_data('id,name,contact_no,batch_id,admin_id,enrollment_id,image,email,status,login_status','students use index (id)',$stud_cond,1);          
            $this->session->sess_destroy();
            if(!empty($userDetails)){
                  if($userDetails[0]['status']=='1'){
                    $brewers_strings = $this->random_strings(10);
                    $sess_arr = array(
                                'uid'=> $userDetails[0]['id'],
                                'name'=> $userDetails[0]['name'],
                                'role'=> $userDetails[0]['role'],
                                'status'=> $userDetails[0]['status'],
                                'admin_id' => $userDetails[0]['parent_id'],
                                'profile_img' => $userDetails[0]['teach_image'],
                                'email' => $userDetails[0]['email'],
                                'mobile' => $userDetails[0]['contact_no'],
                                'brewers_check' => $brewers_strings,
                                'super_admin' => $userDetails[0]['super_admin'],
                               
                            );
                        
                    $url = '';
                        $url = base_url().'admin/dashboard';
                                            
                    $this->session->set_userdata($sess_arr);
                        
                    $resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url);//
                    
                    $this->db_model->update_data_limit('users use index (id)',$this->security->xss_clean(array('token'=>1,'brewers_check'=>$brewers_strings)),array('id'=>$userDetails[0]['id']),1);
                  }else{
                    $resp = array('status' => '0','msg' =>$this->lang->line('ltr_contact_to_admin_msg'));//
                }
            }
            else{
                $resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
            }
        }
        else{
            $resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
        }
        echo json_encode($resp,JSON_UNESCAPED_SLASHES);
    }
    else{
        echo $this->lang->line('ltr_not_allowed_msg');
    } 
}

In login.js

$(document).ready(function(){
$('[data-action="submitThisForm"]').on('click' , function(){
    var targetForm = $(this).closest('form');
    if(!myCustom.checkFormFields(targetForm)){
        myCustom.callFormAjax(targetForm).done(function(res){
            var resp = $.parseJSON(res);
            if(resp.status == 1){
                if(typeof targetForm.attr('data-reset') != 'undefined' && targetForm.attr('data-reset') == 1){ //check reset form data
                    targetForm[0].reset();
                }
                if(typeof targetForm.attr('data-redirect') != 'undefined'){ //check reset form data
                    if(resp.msg != '')
                        toastr.success(resp.msg)
                    setTimeout(function(){
                        location.href = resp.url;   
                    },1500)
                }else if(resp.msg){
                    toastr.success(resp.msg);
                }
            }else if(resp.status == 2){
                $.magnificPopup.open({
                    items: {
                        src: '#studentLogin',
                    },
                    type: 'inline'
                });
                $('#studentLogin .changeStudentLogin').attr('data-id',resp.student_id);
            }
            else if(resp.status == 0){
                toastr.error((resp.msg)?resp.msg:resp.error);
            }
        });
    }
});