How to hide the output of a javascript if queryselector returns empty values?

My code is given below. I just want to hide the out put of “”acceptedAnswer”: {}” section if no accepteted answer found in the post… url: https://edulimit.com/answer/questions-title-12/

function extractQAPageSchema() {
 //Question 
    const questionElement = document.querySelector("h2.wp-block-heading.qtitle");
    const answerCountElement = document.querySelector("p.answercount");
    const upvoteCountElement = document.querySelector("div.gb-container.gb-container-a89cbad3");
    const questionTextElement = document.querySelector("p.question-text");
    const qDatePubElement = document.querySelector("time.entry-date.published");
    //for converting date to ISO format
    const qDatePub = qDatePubElement.textContent.trim();
    const parsedDate = new Date(qDatePub);
    // end of ISO convert
    
//End Question 
  
  // Accepted Answer
  
  const answerElement = document.querySelector("div.gb-container.gb-container-aa37b5a0");
  const ansUpvoteCountElement = document.querySelector("div.gb-container.gb-container-f5b832ff");
  const aDatePubElement = document.querySelector("time.entry-date.published.text");
  //for converting date to ISO format
    const aDatePub = qDatePubElement.textContent.trim();
    const aparsedDate = new Date(aDatePub);
    // end of ISO convert
  const currentUrl = window.location.href;
const urlWithTest = currentUrl + "#acceptedAnswer";
  //Suggested Answer
  
  const schema = {
    "@context": "https://schema.org",
    "@type": "QAPage",
    "mainEntity": {
      "@type": "Question",
      "name": questionElement.textContent.trim(),
      "text": questionTextElement.textContent.trim(),
      "answerCount": parseInt(answerCountText = answerCountElement.textContent.trim()),
      "upvoteCount": parseInt(upvoteCountText = upvoteCountElement.textContent.trim()),
      "datePublished": isoFormattedDate = parsedDate.toISOString(),
      "author": {
          "@type": "Organization",
          "name": "Edulimit Team",
          "url": "https://edulimit.com/answer/author/wptest/"
      },
        
      "acceptedAnswer": {
        "@type": "Answer",
        "text": answerText = answerElement.textContent.replace(/n/g, ''),
        "upvoteCount": parseInt(ansUpvoteCount = ansUpvoteCountElement.textContent.trim()),
        "datePublished": aisoFormattedDate = aparsedDate.toISOString(),
        "url": urlWithTest,
        "author": {
            "@type": "Organization",
            "name": "Edulimit Varified Teacher",
            "url": "https://edulimit.com/answer/author/wptest/"
          }
    },
      "suggestedAnswer": []
    }
  };

  return schema;
}

// Example usage
//const qaPageSchema = extractQAPageSchema();
const schema = extractQAPageSchema();

if (schema) {
  // Do something with the extracted schema, such as:
  
  // 1. Print the schema to the console

  console.log(JSON.stringify(schema, null, 2));

  // 2. Embed the schema into the HTML of the page
  const scriptElement = document.createElement('script');
  scriptElement.type = 'application/ld+json';
 // scriptElement.textContent = JSON.stringify(qaPageSchema);
  scriptElement.textContent = JSON.stringify(schema);
 document.head.appendChild(scriptElement);

  // ... other actions based on your use case 
} else {
  // Handle the case where the schema extraction failed
  console.error("Failed to extract QAPage schema.");

}

Similary I want to hide the “suggestedAnswer”: [] section if no “suggestedAnswer” found in the post.. Althout “suggestedAnswer”: [] section is not defined in the post.

I want to filter the salary data according to the radio button text

In the code I want filter the data of salary Array when i clicked on the radio button. The render data should be filtered accordingly to the text on the radio button. The check box Array filtering is working fine after applying the same concept the radio type is not working.

code is:

import {Component} from 'react'
    import Cookies from '[Jobby App](https://i.sstatic.net/ZLavA3Qm.png)js-cookie'
    import {FcSearch} from 'react-icons/fc'
    import {IoMdStar} from 'react-icons/io'
    import {BsFillBagFill} from 'react-icons/bs'
    import {ImLocation2} from 'react-icons/im'
- import './index.css'

const employmentTypesList = [
  {
    label: 'Full Time',
    employmentTypeId: 'FULLTIME',
  },
  {
    label: 'Part Time',
    employmentTypeId: 'PARTTIME',
  },
  {
    label: 'Freelance',
    employmentTypeId: 'FREELANCE',
  },
  {
    label: 'Internship',
    employmentTypeId: 'INTERNSHIP',
  },
]

const salaryRangesList = [
  {
    salaryRangeId: '1000000',
    label: '10 LPA and above',
  },
  {
    salaryRangeId: '2000000',
    label: '20 LPA and above',
  },
  {
    salaryRangeId: '3000000',
    label: '30 LPA and above',
  },
  {
    salaryRangeId: '4000000',
    label: '40 LPA and above',
  },
]

class JobsRoute extends Component {
  state = {
    profileList: [],
    jobsList: [],`your text`
    searchInput: '',
    EmployList: [],
    SalaryList: [],
  }

  componentDidMount() {
    this.renderProfile()
    this.renderJobsApi()
  }

  searchBox = event => {
    this.setState({searchInput: event.target.value})
  }

  renderProfile = async () => {
    const url = 'https://apis.ccbp.in/profile'
    const jwtToken = Cookies.get('jwt_token')

    const options = {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${jwtToken}`,
      },
    }
    const response = await fetch(url, options)
    if (response.ok === true) {
      const data = await response.json()
      const updatedData = {
        name: data.profile_details.name,
        profileImageUrl: data.profile_details.profile_image_url,
        shortBio: data.profile_details.short_bio,
      }

      this.setState({profileList: updatedData})
    }
  }

  renderProfileList = () => {
    const {profileList} = this.state
    const {name, profileImageUrl, shortBio} = profileList

    return (
      <div className="profile-container">
        <div className="profile">
          <img src={profileImageUrl} alt="profileImage" />
          <h1 style={{color: 'blue+  '}}>{name}</h1>
          <p style={{color: 'black'}}>{shortBio}</p>
        </div>
      </div>
    )
  }

  renderJobsApi = async () => {
    const {EmployList, SalaryList, searchInput} = this.state
    const JobsUrl = `https://apis.ccbp.in/jobs?employment_type=${EmployList}&package_per_annum=${SalaryList}&search=${searchInput}`
    const jwtJobsToken = Cookies.get('jwt_token')

    const JobOptions = {
      method: 'GET',

      headers: {
        Authorization: `Bearer ${jwtJobsToken} `,
      },
    }
    const response = await fetch(JobsUrl, JobOptions)
    if (response.ok === true) {
      const jobData = await response.json()
      const updatedJobsData = jobData.jobs.map(jobItem => ({
        companyLogoUrl: jobItem.company_logo_url,
        employmentType: jobItem.employment_type,
        id: jobItem.id,
        jobDescription: jobItem.job_description,
        location: jobItem.location,
        packagePerAnnum: jobItem.package_per_annum,
        rating: jobItem.rating,
        title: jobItem.title,
      }))

      this.setState({jobsList: updatedJobsData})
    }
  }

  EmployLists = event => {
    const {EmployList} = this.state
    const CheckboxNotInLists = EmployList.filter(
      each => each === event.target.id,
    )
    if (CheckboxNotInLists.length === 0) {
      this.setState(
        prevState => ({
          EmployList: [...prevState.EmployList, event.target.id],
        }),
        this.renderJobsApi,
      )
    } else {
      const filterData = EmployList.filter(each => each !== event.target.id)
      this.setState(
        {
          EmployList: filterData,
        },
        this.renderJobsApi,
      )
    }
  }

  SalaryLists = event => {
    const {SalaryList} = this.state
    const salaryRangeId = event.target.id
    const isChecked = event.target.checked

    if (isChecked) {
      this.setState(prevState => ({
        SalaryList: [...prevState.SalaryList, salaryRangeId],
      }))
    } else {
      const filteredList = SalaryList.filter(id => id !== salaryRangeId)
      this.setState({
        SalaryList: filteredList,
      })
    }
  }

  buttonSearch = () => {
    this.renderJobsApi()
  }

  searchInputDown = event => {
    if (event.key === 'Enter') {
      this.renderJobsApi()
    }
  }

  render() {
    const {jobsList, searchInput} = this.state
    return (
      <div className="job-container">
        <div className="profile-container">
          <div style={{marginLeft: '38px'}}>{this.renderProfileList()}</div>
          <hr style={{marginTop: '25px', marginLeft: '38px'}} />
          <p style={{color: 'white', marginTop: '10px', marginLeft: '38px'}}>
            Type of Employment
          </p>
          <ul className="unordered">
            {employmentTypesList.map(each => (
              <li key={each.employmentTypeId} className="listed">
                <input
                  onChange={this.EmployLists}
                  value={each.label}
                  type="checkbox"
                  className="checkbox"
                  id={each.employmentTypeId}
                />
                <label className="label-name" htmlFor={each.employmentTypeId}>
                  {each.label}
                </label>{' '}
              </li>
            ))}
          </ul>
          <hr style={{marginTop: '25px', marginLeft: '38px'}} />
          <p style={{color: 'white', marginTop: '10px', marginLeft: '38px'}}>
            Salary Range
          </p>
          <ul className="unordered">
            {salaryRangesList.map(each => (
              <li key={each.salaryRangeId} className="listed">
                <input
                  type="radio"
                  value={each.label}
                  onChange={this.SalaryLists}
                  id={each.salaryRangeId}
                />
                <label className="label-name" htmlFor={each.salaryRangeId}>
                  {each.label}
                </label>
              </li>
            ))}
          </ul>
        </div>
        <div className="search-container">
          <div className="search-box">
            <input
              type="search"
              className="search-bar"
              placeholder="Search"
              value={searchInput}
              onChange={this.searchBox}
              onKeyDown={this.searchInputDown}
            />
            <button
              className="search"
              onClick={this.buttonSearch}
              type="button"
              data-testid="searchButton"
              aria-label="Search"
            >
              <FcSearch className="search-icon" />
            </button>
          </div>
          <ul>
            {jobsList.map(jobItem => (
              <li value={this.SalaryList} className="list-jobdetails">
                <div className="container">
                  <img
                    src={jobItem.companyLogoUrl}
                    alt="job details company logo"
                    className="job-image"
                  />
                  <div className="title-rating">
                    <h1>{jobItem.title}</h1>
                    <div className="star-rating">
                      <IoMdStar className="star" />
                      <p>{jobItem.rating}</p>
                    </div>
                  </div>
                </div>

                <div className="location-employment">
                  <div className="loc-emp">
                    <ImLocation2 />
                    <p style={{marginLeft: '8px'}}>{jobItem.location}</p>

                    <BsFillBagFill style={{marginLeft: '13px'}} />
                    <p style={{marginLeft: '8px'}}>{jobItem.employmentType}</p>
                  </div>
                  <p>{jobItem.packagePerAnnum}</p>
                </div>
                <hr />
                <h2 style={{marginTop: '10px'}}>Description</h2>
                <p style={{marginTop: '10px'}}>{jobItem.jobDescription}</p>
              </li>
            ))}
          </ul>
        </div>
      </div>
    )
  }
}
export default JobsRoute

 


**salary details should be ``

filtered after clicking the radio button (salary Range)**

How to build a confirm() like function for NodeJS?

In the browser we have confirm() function which allows to provide a prompt string, and it returns either true/false.

I am trying to create a similar function for a NodeJS cli app. Below I am using readline module. Here is my code:

const readline = require('node:readline');

const rl = readline.createInterface({input: process.stdin, output: process.stdout});

let q = "Do you agree?";

function confirm(question) {
    let options = ["yes", "y", "YES", "Y"];
    let response;

    rl.question(question, ans => {
      response = ans;
      console.log(`You responded with: ${ans}!`);
      rl.close();
    });

    return options.includes(response);
    
}

let ans1 = confirm(q);
console.log(`ans1=${ans1}`);

let ans2 = confirm(q);
console.log(`ans2=${ans2}`);

For some reason it doesn’t work and the output generated is out of order also.

Do you agree?ans1=false
Do you agree?ans2=false
yes
You responded with: yes!

I suspect there is some async behaviour happening as we can see both prompt appear before readline callback is actually called.

How can I fix this?

Unraveling the Mystery: Understanding API Calls and Async Processing with Vercel.com

How Vercel.com handles api calles? It seems that some 3rd party call is responded more than 1 minutes later, or it is not even responded.

3rd party claims with timestams, that they responded in 1 second.

Who is right who is wrong? Can it be that queues are used in Vercel and they postpone the handling of an async process?

It is possible that some variable will loose value meantime?

async function sendInvoice(
    db: Db,
    payment: Payment,
    vegszamla: boolean,
    xml: string,
    paymentAndInvoiceRecipientId?: string
): Promise<void> {
    await db.collection('logs').insertOne({
        service: 'sendInvoice',
        createdAt: new Date(),
        severity: 'log',
        message: 'Sending invoice starting',
        xml,
    })
    const timestamp = new Date()
    let d = {
        createdAt: timestamp,
    }
    if (paymentAndInvoiceRecipientId) {
        d['paymentAndInvoiceRecipientId'] = paymentAndInvoiceRecipientId
    }
    if (vegszamla) {
        db.collection('payments').updateOne(
            { _id: payment._id },
            {
                $push: {
                    finalInvoices: d,
                },
            }
        )
    } else {
        db.collection('payments').updateOne(
            { _id: payment._id },
            {
                $push: {
                    invoices: d,
                },
            }
        )
    }
    const blob = new Blob([xml], { type: 'text/plain' })
    const formData = new FormData()
    formData.append('action-xmlagentxmlfile', blob, 'xmlfile.xml')
    const response = await fetch(`https://www.szamlazz.hu/szamla/`, {
        method: 'POST',
        body: formData,
    })
    const text = await response.text()
    await db.collection('logs').insertOne({
        service: 'prepareAndSendInvoice',
        createdAt: new Date(),
        severity: 'log',
        message: 'Sending invoice response received',
        status: response.status,
    })
    if (response.status === 200 && !response.headers.has('szlahu_error')) {
        const invoiceId = response.headers.get('szlahu_szamlaszam')
        await db.collection('logs').insertOne({
            service: 'prepareAndSendInvoice',
            createdAt: new Date(),
            severity: 'log',
            message: 'Invoice ID read',
            invoiceId,
            paymentId: payment._id,
            timestamp,
        })
        if (!invoiceId) {
            await db.collection('logs').insertOne({
                service: 'sendInvoice',
                createdAt: new Date(),
                severity: 'error',
                message: 'No tetelek created',
            })
            return Promise.reject(new Error('No invoiceId returned by provider'))
        }
        if (vegszamla) {
            db.collection('payments').updateOne(
                { _id: payment._id, 'finalInvoices.createdAt': timestamp },
                { $set: { 'finalInvoices.$.id': invoiceId } }
            )
        } else {
            db.collection('payments').updateOne(
                { _id: payment._id, 'invoices.createdAt': timestamp },
                { $set: { 'invoices.$.id': invoiceId } }
            )
        }
        await db.collection('logs').insertOne({
            service: 'prepareAndSendInvoice',
            createdAt: new Date(),
            severity: 'log',
            message: 'Sending invoice finished',
        })
    } else {
        await db.collection('logs').insertOne({
            service: 'sendInvoice',
            createdAt: new Date(),
            severity: 'error',
            responseText: text,
            responseStatus: response.status,
            responseHeaders: response.headers,
            xml,
        })
    }
}

Create a Java program that can generate a 14-character unique personal password [closed]

Create a Java program that can generate a 14-character unique personal password. The password combines the first two characters of the user’s nickname, the last four digits of their identification numbers, and their birthdate.

This program should include all these requirements:
i. This program should implement proper multiple inheritance with a minimum of THREE (4) classes
including Interface and main method class.
ii. A class constructor is used to accept all the inputs from the users.
iii. Abstract class which contains abstract methods and normal methods need to be used to process
all String manipulation to extract the password element from the user’s input data.
iv. An interface is used to display the final password combination.
v. Your program should apply a good programming style and documentation.

I tried but couldnt get anything

Displaying the Result of Your Nested Color Code

My project code is quite large and tedious, so I’ve written a shorter code to better explain my problem.

First, please review the following code:

  function chgrad() {
    // Get the selected radio button
    var selectedRadio = document.querySelector('input[name="radioGroup"]:checked');
  
    // Get colors and rotation values
    var red1 = document.getElementById('red1').value;
    var green1 = document.getElementById('green1').value;
    var blue1 = document.getElementById('blue1').value;
  
    var red2 = document.getElementById('red2').value;
    var green2 = document.getElementById('green2').value;
    var blue2 = document.getElementById('blue2').value;
  
    var rot = document.getElementById('rot').value;
  
    // Set background-size to cover before setting background-image
    document.getElementById('wrapper').style.backgroundSize = 'cover';
  
    // Create gradient string based on selected radio button
    var gradientString;
    if (selectedRadio.value === 'option1') {
      gradientString = "-webkit-linear-gradient(" + rot + "deg, rgb(" + red1 + "," + green1 + "," + blue1 + "))";
    } else if (selectedRadio.value === 'option2') {
      gradientString = "-webkit-linear-gradient(" + rot + "deg, rgb(" + red1 + "," + green1 + "," + blue1 + "), rgb(" + red2 + "," + green2 + "," + blue2 + "))";
    }
  
    // Apply the gradient
    document.getElementById('wrapper').style.backgroundImage = gradientString;
  }
 .wrapper {
    width: 100%;
    height: 50px;
    background-color: #000;
    background-image: transparent;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="wrapper" class="wrapper"></div>

    <div class="btn-radio">
        <input type="radio" id="radio1" name="radioGroup" value="option1" checked>
        <label for="radio1">One colors</label>
    </div>

    <div class="btn-radio">
        <input type="radio" id="radio2" name="radioGroup" value="option2">
        <label for="radio2">Two colors</label>
    </div>

    <div class="rotate-change-main">
        <label for="rot">Rotate</label>
        <input type="range" min="0" max="360" oninput="chgrad()" value="0" id="rot">
    </div>

    <br>

    <div id="range_color1" class="range-color">
        <label for="red1">Red</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="red1" value="0" /><br />
        <label for="green1">Green</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="green1" value="0" /><br />
        <label for="blue1">Blue</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="blue1" value="0" /><br />
    </div>

    <br>

    <div id="range_color2" class="range-color">
        <label for="red2">Red</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="red2" value="0" /><br />
        <label for="green2">Green</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="green2" value="0" /><br />
        <label for="blue2">Blue</label>
        <input type="range" min="0" max="255" oninput="chgrad();" id="blue2" value="0" /><br />
    </div>

Problem:

As you can see in the code above, when the first button (One colors) with the ID #radio1 is active, changing the values in the #range_color1 box does not cause any changes in the black box. However, as soon as the second button (Two colors) with the ID #radio2 is activated, a combined color is correctly created.

My question:

My problem is exactly here!

I want the changes to be reflected in the black box in full width (so that there is only one color) when the first button (One colors) with the ID #radio1 is active, and the color to be combined (gradient) when the second button (Two colors) with the ID #radio2 is activated In the black box, a color should be displayed as a combination (gradient).

Additional Information:

I have already tried setting the background-image property to none in the CSS for the .wrapper class. I have also tried creating a separate gradient string for each option, but this does not work either.

I would appreciate it if you could help me solve this problem.

Thank you for your time and assistance.

“Is each frontend index uniquely mapped to a payroll ID, and is PaySlipPDF processing data for every index?”please ready my description give solution

import AppSelect from '@/components/form-fields/AppSelect';
import {
  Box,
  Button,
  CircularProgress,
  Divider,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Stack,
  Typography,
  useTheme,
} from '@mui/material';
import React, { useEffect } from 'react';
import { BlobProvider, PDFDownloadLink } from '@react-pdf/renderer';
import Iconify from '@/components/iconify';
import PaySlipPDF from './paySlipPDF';
import useGet from '@/hooks/useGet';
import { useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';
import { PAYSTRUCTURE_PAYROLL_LIST_ENDPOINT } from '@/constants/my-company/employee-directory';
import useUserStore from '@/store/user.store';

type PayRoll = {
  year: string;
  month: string;
  monthText: string;
  payrollId: string;
};

const Payslips = () => {
  const theme = useTheme();
  const [selectedIndex, setSelectedIndex] = React.useState(1);
  const [payrollId, setPayrollId] = React.useState('');
  const [list, setlist] = React.useState<PayRoll[] | undefined>([]);
  const { control, watch } = useForm();
  const user = useUserStore((state) => state.user);
  // const {id} = useParams();
  const { data } = useGet<any>(
    PAYSTRUCTURE_PAYROLL_LIST_ENDPOINT (user?.Employee?.id), ['getPayrunListForEmp']
  );

  
  // const options = [...new Set(data?.map((each: { year: any; }) => each.year))].map((each) => ({
  //   label: each,
  //   value: each,
  // }));


  // const year = watch('year');
  // useEffect(() => {
  //   if (data) {
  //     setlist(data?.filter((each: { year: any; }) => each.year === year));
  //   }
  // }, [year, data]);
  
  const options = [...new Set(data?.map((each:any) => each.year))].map((each) => ({
    label: each,
    value: each,
  }));

  const year = watch('year');
  useEffect(() => {
    setlist(data?.filter((each:any) => each.year == year));
  }, [year, data, payrollId]);
  const handleListItemClick = (index: number, id: string) => {
    setSelectedIndex(index);
    if (payrollId !== id) {
      setPayrollId(id);
    } else {
      // Reset payrollId if the same month is selected again
      setPayrollId('');
    }
  };
  
  // Add your custom styles for the header box
  const headerStyles = {
    display: 'flex',
    flexDirection: 'row',
    width: '70%',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: theme.spacing(2),
    backgroundColor: '#4A5363',
    color: theme.palette.primary.contrastText,
  };
  // console.log('Data:', data);
  // console.log('Options:', options);
  // console.log('List:', list);
  // console.log('Mapped Years:', data?.map((each: { year: any; }) => each.year));
  return (
    <Stack
      sx={{
        display: 'flex',
        flexDirection: 'row',
        margin: 2,
        gap: 2,
        flexWrap: 'wrap',
        height: '100%',

        [theme.breakpoints.down('sm')]: {
          flexDirection: 'column',
        },
      }}
    >
      <Stack
        direction='column'
        sx={{
          width: '250px',
          [theme.breakpoints.down('sm')]: {
            width: '100%',
          },
        }}
        gap={2}
      >
        <AppSelect control={control} name='year' options={options} />
        <Box component='span' sx={{ bgcolor: 'background.paper', flex: 1 }}>
          <List component='nav' aria-label='main mailbox folders'>
            {list?.map((each, idx) => (
              <ListItemButton
                selected={selectedIndex === idx}
                onClick={(event) => handleListItemClick(idx, each.payrollId)}
              >
                <ListItemText primary={each.monthText} />
              </ListItemButton>
            ))}
          </List>
        </Box>
      </Stack>
      <Box sx={{ flex: 1 }}>
        {payrollId ? (
          <PaySlipPDF id={payrollId} />
        ) : (
          <Typography variant='body2'>Select Year and Month </Typography>
        )}
      </Box>
    </Stack>
  );
};

export default Payslips;

in this provided code if i select month which is in listitembutton it fetch data and gives payslipdf, but after selecting next month for three time then only it shows next payslip pdf for that month for example if i select jan it shows payslip pdf and same time if i press feb for three times then only it shows the payslip pdf

 useEffect(() => {
    setlist(data?.filter((each:any) => each.year == year));
  }, [year, data, payrollId]);
  const handleListItemClick = (index: number, id: string) => {
    setSelectedIndex(index);
    if (payrollId !== id) {
      setPayrollId(id);
    } else {
      // Reset payrollId if the same month is selected again
      setPayrollId('');
    }
  };
type here
import { PAYSTRUCTURE_PAYSLIP_ENDPOINT } from "@/constants/my-company/employee-directory"
import useGet from "@/hooks/useGet"
import { LinearProgress } from "@mui/material"
import { useEffect, useRef } from "react"

export default function PaySlipPDF({id}:{id:string}) {
    const { data,isLoading } = useGet<any>(PAYSTRUCTURE_PAYSLIP_ENDPOINT + `/${id}`, ["payslip"],false,true)
    const ref = useRef<any>()
    useEffect(() => {
        console.log(data)
        const file = new Blob([data], 
            { type: 'application/pdf' });
        //Build a URL from the file
        const fileURL = URL.createObjectURL(file);
        console.log(fileURL)
        ref.current.src = fileURL
//Open the URL on new Window
// window.open(fileURL);
    }, [data])
    
    return (
        <div style={{ width: "100%", height: "700px" }}>
            {isLoading && <LinearProgress />}
             <iframe style={{display:isLoading?"none":"block"}} width="100%" height="100%" ref={ref} />
      </div>
   
  )
}

i modify the logic but it won’t works please give some solution it in react tyepscript

I’m facing an error while loading a script in my React app’s public HTML file, but the script works fine in the background. How can I resolve this?

How to specify the column and data property in jspreadsheet ce when a property is another object

The outer object has properties name, id, age, and company. The company property is another object with properties name and location.

var table = jexcel(document.getElementById('spreadsheet'), {        
data:[
    { name:'Jorge', id:'3', age:'40',company:{name:'nokia',location:'us'} },
    { name:'Robert', id:'4', age:'48',company:{name:'nokia',location:'us'} },
    { name:'Santos', id:'5', age:'32',company:{name:'nokia',location:'us'} },
],
columns: [
    { type:'text', width:300, name:'id', title:'id' },
    { type:'text', width:100, name:'name', title:'name' },
    { type:'text', width:100, name:'age', title:'age' },
    { type:'text', width:100, data:'company.name', title:'company name' },
    { type:'text', width:100, data:'company.location', title:'company location' },
 ]
});

and the result table looks like this:
enter image description here

An example of this issue here: https://jsfiddle.net/sridharnetha/vf0tknxb/2/

my question is that i will added a polyline in D3 pie chart

My problem is that my polylines in my chart are not correct positioning on the exact data on my slices which are given in my code

This is my code of slices and polylines when yu convert this code into html this will run and place on W3 school or place this code on a function and call on html on click

for reference the whole code
https://observablehq.com/@mast4461/d3-donut-chart-labels
this is a donut but exact polylines will place on their correct positioning and my chart is pie chart in 3D-view i will attach my UI in image

    var slices = vis
      .append("svg:g")
      .attr("transform", "translate(" + x + "," + y + ")")
      .attr("class", "slice");

    slices
      .selectAll(".innerSlice")
      .data(_data)
      .enter()
      .append("path")
      .attr("class", "innerSlice")
      .style("fill", function (d) {
        return d3.hsl(d.data.color).darker(0.7);
      })
      .attr("d", function (d) {
        return pieInner(d, rx + 0.5, ry + 0.5, h, ir);
      })
      .each(function (d) {
        this._current = d;
      });

    slices
      .selectAll(".topSlice")
      .data(_data)
      .enter()
      .append("path")
      .attr("class", "topSlice")
      .style("fill", function (d) {
        return d.data.color;
      })
      .style("stroke", function (d) {
        return d.data.color;
      })
      .attr("d", function (d) {
        return pieTop(d, rx, ry, ir);
      })
      .each(function (d) {
        this._current = d;
      });

    slices
      .selectAll(".outerSlice")
      .data(_data)
      .enter()
      .append("path")
      .attr("class", "outerSlice")
      .style("fill", function (d) {
        return d3.hsl(d.data.color).darker(0.7);
      })
      .attr("d", function (d) {
        return pieOuter(d, rx - 0.5, ry - 0.5, 40, 5, 50, 100, 0.02);
      })
      .each(function (d) {
        this._current = d;
      });

    slices
      .selectAll(".percent")
      .data(_data)
      .enter()
      .append("text")
      .attr("class", "percent")
      .attr("x", function (d) {
        return 0.6 * rx * Math.cos(0.5 * (d.startAngle + d.endAngle));
      })
      .attr("y", function (d) {
        return 0.6 * ry * Math.sin(0.5 * (d.startAngle + d.endAngle));
      })
      .text(getPercent)
      .each(function (d) {
        this._current = d;
      });

    function pieInner(d, rx, ry, h, ir) {
      var startAngle = d.startAngle < Math.PI ? Math.PI : d.startAngle;
      var endAngle = d.endAngle < Math.PI ? Math.PI : d.endAngle;

      var sx = ir * rx * Math.cos(startAngle),
        sy = ir * ry * Math.sin(startAngle),
        ex = ir * rx * Math.cos(endAngle),
        ey = ir * ry * Math.sin(endAngle);

      var ret = [];
      ret.push(
        "M",
        sx,
        sy,
        "A",
        ir * rx,
        ir * ry,
        "0 0 1",
        ex,
        ey,
        "L",
        ex,
        h + ey,
        "A",
        ir * rx,
        ir * ry,
        "0 0 0",
        sx,
        h + sy,
        "z"
      );
      return ret.join(" ");
    }

    function pieTop(d, rx, ry, ir) {
      if (d.endAngle - d.startAngle == 0) return "M 0 0";
      var sx = rx * Math.cos(d.startAngle),
        sy = ry * Math.sin(d.startAngle),
        ex = rx * Math.cos(d.endAngle),
        ey = ry * Math.sin(d.endAngle);

      var ret = [];
      ret.push(
        "M",
        sx,
        sy,
        "A",
        rx,
        ry,
        "0",
        d.endAngle - d.startAngle > Math.PI ? 1 : 0,
        "1",
        ex,
        ey,
        "L",
        ir * ex,
        ir * ey
      );
      ret.push(
        "A",
        ir * rx,
        ir * ry,
        "0",
        d.endAngle - d.startAngle > Math.PI ? 1 : 0,
        "0",
        ir * sx,
        ir * sy,
        "z"
      );
      return ret.join(" ");
    }

    function pieOuter(d, rx, ry, h) {
      var startAngle = d.startAngle > Math.PI ? Math.PI : d.startAngle;
      var endAngle = d.endAngle > Math.PI ? Math.PI : d.endAngle;

      var sx = rx * Math.cos(startAngle),
        sy = ry * Math.sin(startAngle),
        ex = rx * Math.cos(endAngle),
        ey = ry * Math.sin(endAngle);

      var ret = [];
      ret.push(
        "M",
        sx,
        h + sy,
        "A",
        rx,
        ry,
        "0 0 1",
        ex,
        h + ey,
        "L",
        ex,
        ey,
        "A",
        rx,
        ry,
        "0 0 0",
        sx,
        sy,
        "z"
      );
      return ret.join(" ");
    }
    var radius = 200;
    var arc = d3
      .arc()
      .innerRadius(radius - 100)
      .outerRadius(radius - 50);

    var outerArc = d3
      .arc()
      .innerRadius(radius * 0.9)
      .outerRadius(radius * 0.9);
    // Add the polylines between chart and labels:
    slices
      .selectAll("allPolylines")
      .data(_data)
      .enter()
      .append("polyline")
      .attr("stroke", "black")
      .style("fill", "none")
      .attr("stroke-width", 1)
      .attr("points", function (d) {
        console.log("checkkkshdfkh", d);
      
        var posA = arc.centroid(d) // line insertion in the slice
        var posB = outerArc.centroid(d) // line break: we use the other arc generator that has been built only for that
        var posC = outerArc.centroid(d); // Label position = almost the same as posB
        let tempX= 0.6 * rx * Math.cos(0.5 * (d.startAngle + d.endAngle));
        let tempY= 0.6 * ry * Math.sin(0.5 * (d.startAngle + d.endAngle))
        var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 // we need the angle to see if the X position will be at the extreme right or extreme left
        posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1);
        console.log("checknskdnfknsdf",posA,[tempX,tempY])
        return [posA, posB, posC]

      });

My UI looks like

I try https://observablehq.com/@mast4461/d3-donut-chart-labels and i try most of the code but it didn’t work

I expect that my polylines are place on the exact slice based on the data and also

Copy of my webpage with a single statement causing an error

I am making a website with the flask module of python and facing issue in javascript of my html element and the error is in a on click event, when I click the button it shows an uncaught ReferenceError in console and it refers to copy of my webpage containing only a single onclick event statement and refering to the parameter I passed as undefined.

function add_card(id1, l_no){
                            var sec = document.getElementById(id1);


                    var inp1 = document.createElement("input");
                    inp1.setAttribute("placeholder","Enter a title");
                    inp1.setAttribute("id","inp1");
                    inp1.setAttribute("type","text");

                    var btn1 = document.createElement("button");
                    btn1.textContent = "Add card";
                    btn1.setAttribute("id","c_btn");
                    btn1.setAttribute("type","button");
                    btn1.setAttribute("onclick","card_done(l_no)");

                    sec.insertBefore(inp1,sec.lastElementChild);
                    sec.insertBefore(btn1,sec.lastElementChild);

                }```

resulting error in console:
Uncaught ReferenceError: l_no is not defined
    at HTMLButtonElement.onclick (1:1:11)

creating a copy file like this
[enter image description here](https://i.sstatic.net/KKRYg7Gy.png)


i checked the variable by printing it, there is no issue with the variable "l_no".
Please help finding the issue. 

Specific Part Not Showing in PieChart

I have a pie chart displaying various amounts and values. However, I’ve encountered an issue where a specific segment is not appearing on the chart. I’m seeking assistance to resolve this matter. I’ve ensured that I’m fetching all values correctly, and upon inspecting them through console.log, everything appears to be working fine. Could AnyOne please help me understand why this discrepancy is occurring?

I’ve attached an image where you can observe that I’ve retrieved the amount for ‘1link,’ yet the corresponding segment is not visible on the chart.

here is the code


            ////////////////////////maintenance

            var graphtotmanamontValue = '<%= graphtotmanamont.Text %>';
            var graphtotmanamont1lnkValue = '<%= graphtotmanamont1lnk.Text %>';
            var graphtotmanamontkpayValue = '<%= graphtotmanamontkpay.Text %>';
            var graphtotmanamontothrValue = '<%= graphtotmanamontothr.Text %>';

            var outstndngmanamnt = '<%= lbltotaloutstandingamountman.Text%>';
            var splitoutstndngmanamnt = outstndngmanamnt.split(',');
            var splittedoutstndngmanamnt = splitoutstndngmanamnt.join('');


            ////percentage
            var totalmainothramountpercentage = (graphtotmanamontothrValue / graphtotmanamontValue * 100).toFixed(2) + "%";
            var totalmain1linkamountpercentage = (graphtotmanamont1lnkValue / graphtotmanamontValue * 100).toFixed(2) + "%";
            var outstndngmainprcntg = (splittedoutstndngmanamnt / graphtotmanamontValue * 100).toFixed(2) + "%";


            var Mainchart = new CanvasJS.Chart("MaintenanceChart", {
                animationEnabled: true,
                backgroundColor: "transparent",
                data: [{
                    type: "pie",
                    startAngle: 240,
                    yValueFormatString: "##0""",
                    indexLabel: "{label} {y}",
                    dataPoints: [
                        { y: parseFloat(splittedoutstndngmanamnt), label: "O/S ", toolTipContent: "Outstanding Receieved : " + outstndngmainprcntg },
                        { y: parseFloat(graphtotmanamontkpayValue), label: " KPay" },
                        { y: parseFloat(graphtotmanamontothrValue), label: " Others", toolTipContent: "Others Receieved : " + totalmainothramountpercentage , color:"#FFC0CB" },
                        { y: parseFloat(graphtotmanamont1lnkValue), label: " 1LINK", toolTipContent: "1 link Receieved : " + totalmain1linkamountpercentage, color: "orange" }
                    ]
                }]
            });

            Mainchart.render();

Converting an SVG path arc to DXF

I am working on creating a custom converter from svg to dxf and need a math wizard to help me figure out where my logic is flawed.

Here is my current code:

function svgArcToLWPolyline(rx, ry, rotation, largeArcFlag, sweepFlag, x1, y1, x2, y2) {
    const scaleX = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / (2 * rx);
    const scaleY = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / (2 * ry);

    const arcInfo = svgArcToOvalArc(rx * scaleX, ry * scaleY, rotation, largeArcFlag, sweepFlag, x1, y1, x2, y2);
    const numPoints = calculateNumberOfPoints(rx * scaleX, ry * scaleY, arcInfo.startAngle, arcInfo.endAngle);

    // Calculate bulge factors
    const bulgeFactors = [];
    const angleIncrement = (arcInfo.endAngle - arcInfo.startAngle) / (numPoints - 1);
    let currentAngle = arcInfo.startAngle;
    for (let i = 0; i < numPoints - 1; i++) {
        const nextAngle = currentAngle + angleIncrement;
        const bulge = Math.tan((nextAngle - currentAngle) * Math.PI / 360);
        bulgeFactors.push(bulge);
        currentAngle = nextAngle;
    }
    bulgeFactors.push(0); // Last point has zero bulge

    // Construct LWPOLYLINE points
    const lwpolylinePoints = [];
    for (let i = 0; i < numPoints; i++) {
        const angle = arcInfo.startAngle + i * angleIncrement;
        const x = arcInfo.cx + rx * scaleX * Math.cos(angle * Math.PI / 180);
        const y = arcInfo.cy + ry * scaleY * Math.sin(angle * Math.PI / 180);
        lwpolylinePoints.push([x, y, bulgeFactors[i]]);
    }

    return lwpolylinePoints;
}

function svgArcToOvalArc(rx, ry, rotation, largeArcFlag, sweepFlag, x1, y1, x2, y2) {
    // Convert rotation angle to radians
    const angle = rotation * Math.PI / 180;

    // Calculate intermediate values
    const dx = (x1 - x2) / 2;
    const dy = (y1 - y2) / 2;
    const x1p = Math.cos(angle) * dx + Math.sin(angle) * dy;
    const y1p = -Math.sin(angle) * dx + Math.cos(angle) * dy;
    const rxSq = rx * rx;
    const rySq = ry * ry;
    const x1pSq = x1p * x1p;
    const y1pSq = y1p * y1p;
    let radicand = (rxSq * rySq - rxSq * y1pSq - rySq * x1pSq) / (rxSq * y1pSq + rySq * x1pSq);

    // Ensure non-negative radicand
    if (radicand < 0) {
        radicand = 0;
    }

    // Calculate root
    let root = Math.sqrt(radicand);
    if (largeArcFlag === sweepFlag) {
        root = -root;
    }
    const cxp = root * rx * y1p / ry;
    const cyp = -root * ry * x1p / rx;

    // Calculate center
    const cx = Math.cos(angle) * cxp - Math.sin(angle) * cyp + (x1 + x2) / 2;
    const cy = Math.sin(angle) * cxp + Math.cos(angle) * cyp + (y1 + y2) / 2;

    // Calculate start and end angles
    let startAngle = Math.atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
    let endAngle = Math.atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);

    // Convert angles to degrees
    startAngle *= 180 / Math.PI;
    endAngle *= 180 / Math.PI;

    // Adjust angles to be in the range [0, 360]
    if (startAngle < 0) {
        startAngle += 360;
    }
    if (endAngle < 0) {
        endAngle += 360;
    }

    return { cx: cx, cy: cy, startAngle: startAngle, endAngle: endAngle };
}

function calculateNumberOfPoints(rx, ry, startAngle, endAngle) {
    // Calculate arc length
    let arcLength;
    if (startAngle <= endAngle) {
        arcLength = (endAngle - startAngle) * Math.PI / 180;
    } else {
        arcLength = (360 - startAngle + endAngle) * Math.PI / 180;
    }
    arcLength *= (rx + ry) / 2;

    // Choose a fixed length for each segment
    const segmentLength = 1.0;  // Adjust as needed

    // Calculate the number of points
    const numPoints = Math.max(Math.floor(arcLength / segmentLength), 2);  // Minimum of 2 points

    return numPoints;
}

Here is what the svg looks like using d=”M10,10L20,25A1,3,0,0,0,50,50L90,90V80Z”
enter image description here
And here is my dxf (don’t worry that it’s upside down
enter image description here

As you can see, the ry and rx aren’t being taken into account. And when I change my path to add a xRotationalAxis, my dxf breaks even more: d=”M10,10L20,25A1,3,45,0,0,50,50L90,90V80Z”:
SVG:
enter image description here
DXF:
enter image description here

I’ve spent 12 hours trying to tweek this and figure out mathmatically how to make it work (with a lot of help from ChatGPT) So any help I can get on this would be really nice!

‘http://localhost:3000’ has been blocked by CORS

I’ve been trying to connect my react .js file to the back end. I have a API in API Gateway and I created a method and enabled CORS and gave it access

method.response.header.Access-Control-Allow-Headers 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
method.response.header.Access-Control-Allow-Methods 'OPTIONS'
method.response.header.Access-Control-Allow-Origin  '*'

I even tried the http://localhost:3000 for the Access-Control-Allow-Origin

but every-time I run this code and check the console I’m getting the error

Access to fetch at https://mdksmdk.execute-api.us-east-5.amazonaws.com/blehxajkhnd from origin http://localhost:3000 has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

I’ve enabled the CORS multiple times. Idk what could be the issue

I can paste the code if that helps