how to convert html webpage to PDF and download it In Javascript/Vuejs from client-side? That PDF should be editable and not just an image

I am using Vue.js (Vue2) Project and i need to give a functionality of export PDF for the webPage/Html content which is displayed already for the user. there are lots of libraries like jsPDF, html2pdf, etc etc but none of them allows me to select the text or edit the PDF in Online PDF editor.
And 1 more thing that the html content is already rendered in the browser and that html I want to export as a PDF so basically it should be operated totaly from client Side and not from the server Side.
I have heard about pspdfKit but the documentation is not clear.

h1 element not be updated correctly by setInterval

i want to create a simple React app that upadates a h1 element every second with setInterval function. I have an array with strings and every second i want randomly pick a string from that array and uses that string inside h1. But my code doesnt work properly. h1 not be updated every second but every millisecond.

import PersonalInfo from './PersonalInfo.js'
import { useState } from 'react';

function App() {
  const myPersonalInfo = ['books', 'music', 'code']; 
  const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);

  setInterval(() => {
    changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
  }, 2000);

  return (
    <div className="App">
      <PersonalInfo title={state} />
    </div>
  );
}

export default App;
function PersonalInfo({ title}) {
    return <div>
        <h1>I Love {title} </h1>
    </div>
}

export default PersonalInfo

TypeScript – Distributive conditional types

Talk is cheap,show the code!


type ITypeA = ((args: { A: any }) => any) | ((args: { B: any }) => any);

type Test<T> = T extends (args: infer A) => any ? A : never;

// type Result1 = {
//     A: any;
// } | {
//     B: any;
// }
type Result1 = Test<ITypeA>;

// type Result2 = {
//     A: any;
// } & {
//     B: any;
// }
type Result2 = ITypeA extends (args: infer A) => any ? A : never;

Result1 may use ‘distributive conditional types’ rule in ts, so type Result1 = { A: any;} | { B: any;}. My question is why does Result2 not apply this rule? Is there any difference between them?

How to create dynamic object using javascript?

I have one array variable and object. i need to map the object value with array variable’s key value. i couldn’t map the value when have nested object. kindly refer the data below.

the condition array variable is

let allowedField = [
                'organization_id',
                'organization_name',
                'payload.offer',
                'id',
                'candidate_id'
            ]

full response object is

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    }
                }
            }

Below i have mentioned required output,

let ouputObj = {
organization_id: 4002400004,
organization_name: 'Velocity Global Integration Sandbox',
payload: {
offer: {
id: 4524843004,
application_id: 31948577004,
user_id: 4123647004,
version: 1,
sent_on: null,
resolved_at: '2022-05-19T06:21:25.084Z',
start_date: '2022-05-17',
notes: null,
job_id: 4298940004,
offer_status: 'Accepted'
}
}
}

quasar q-select use filter event as a common function not work

I try this @filter event example

https://quasar.dev/vue-components/select#example–basic-filtering

can work

Index.vue

<template>
  <q-select
    :options="options"
    @filter="filter"
    v-model="model"
  ></q-select>
</template>

<script>
import { defineComponent } from "vue";
import { computed, reactive, toRefs, ref } from "vue";
const selectedOptions = ["Google", "Facebook", "Twitter", "Apple", "Oracle"];

export default defineComponent({
  name: "PageIndex",
  setup() {
    let state = reactive({
      model: null,
      options: selectedOptions,
    });

    const filter = (val, update, abort) => {
      update(() => {
        const needle = val.toLowerCase()
        state.options = selectedOptions.filter(v => v.toLowerCase().indexOf(needle) > -1)
      })
    }

    return {
      filter,
      selectedOptions,
      ...toRefs(state),
    };
  },
});
</script>

I want to do common function from utils/filter.js but not work

Index.vue

<template>
  <q-select
    :options="options"
    @filter="
      (val, update, abort) =>
        filter(val, update, abort, selectedOptions, options)
    "
    v-model="model"
  >  </q-select>
</template>

<script>
import { defineComponent } from "vue";
import { computed, reactive, toRefs, ref } from "vue";
import { filter } from "../utils/filter";
const selectedOptions = ["Google", "Facebook", "Twitter", "Apple", "Oracle1"];

export default defineComponent({
  name: "PageIndex",
  setup() {
    let state = reactive({
      model: null,
      options: selectedOptions,
    });

    return {
      filter,
      selectedOptions,
      ...toRefs(state),
    };
  },
});
</script>

utils/filter.js

export function filter(val, update, abort, from, to) {
  update(() => {
    const needle = val.toLowerCase()
    to.value = from.filter((v) => v.toLowerCase().indexOf(needle) > -1)
  })
}

What to do to get filtering to work ?

https://codesandbox.io/s/blissful-brattain-vd085n?file=/src/utils/filter.js

How can I investigate memory issues in NodsJS on kubernetes

I am looking for a way to investigate one of our nodejs services that keeps getting the error

"FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory" 

when testing our performance.

I am looking for a package or program that will give me a warning when there is a memory leak and maybe what exactly is leaking. I know there are the heapdump snapshots, but most of the packages save it to a file that when it is saved on the pod when the pod will crash, will disappear, but also it takes a lot of memory to take the snapshot.

Most of the articles I found are very old and use packages that are already deprecated or just use snapshots and use the chrome dev tools but nobody seems to explain what exactly the columns in the snapshot mean.

Long story short: Do you have any suggestions for how to or which program/package to us for investigating memory issues in a nodejs service that runs on kubernetes and most of its info is received via message queue and not just RestAPI?

How to store video url in usestate and pass it to video popup modal react js

I get a response from API and pass it to the react js.

API response

    Array(80)
    0:
    Camera_Number: "Camera_1"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/0"
    [[Prototype]]: Object
    
    1:
    Camera_Number: "Camera_2"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/1"
    [[Prototype]]: Object

After getting a response populated API data to the react-ag grid.

App.js

    import video from "./video_2.mp4";
   ....... 
    export default function App(data, handleFormSubmit) {
      const { id } = data;
      const actionButton = (params) => {
        setOpen(true);
      };
      const [open, setOpen] = React.useState(false);
      const [setFormData] = useState(initialValue);
      const handleClose = () => {
        setOpen(false);
        setFormData(initialValue);
      };
      const columnDefs = [
        { headerName: "Name", field: "Company_Name", filter: "agSetColumnFilter" },
        { headerName: "Floor", field: "Floor Number" },
        { headerName: "Group", field: "Group_Name" },
        { headerName: "Camera", field: "Camera_Number" },
        { headerName: "Videos", field: "Video_Name" },
        {
          headerName: "Actions",
          field: "Video_Name",
          cellRendererFramework: (params) => (
            <div>
              <Button
                variant="contained"
                size="medium"
                color="primary"
                onClick={() => actionButton(params)}
              >
                Play
              </Button>
            </div>
          ),
        },
      ];
      const onGridReady = (params) => {
        console.log("grid is ready");
        fetch("http://localhost:8000/get_all")
          .then((resp) => resp.json())
          .then((resp) => {
            console.log(resp.results);
            params.api.applyTransaction({ add: resp.results });
          });
      };
      return (
        <div className="App">
          <div>
            <Dialog
              open={open}
              onClose={handleClose}
            >

          {/* Issue is Here */}
          <DialogContent>
            <iframe width="420" height="315" title="videos" src={video} />
          </DialogContent>
          {/* Issue is Here */}

        </Dialog>
      </div>
    </div>
  );
}

I used this code to call API and populate external API data to react js. Now the problem is to assign only one video to the source located in the project directory.

      <DialogContent>
       
       <iframe width="420" 
        height="315" 
        title="videos" 
        src={video} />
    
     </DialogContent>

Video_Name:"http://localhost:4000/video/0" , Video_Name:"http://localhost:4000/video/1"

How to assign the above multiple video URLs to the source(src) which I got from API.

Thanks

Why image and username not saved in firebase?

I have a react and firebase app wherein after successful login signup I need to display the username and the profile picture of the user.Its working until I refresh the page.After refreshing the username turns null and the profile picture is reduced to default profile Picture.Here’s the code for the same:

const Homepage = ({user,username,setusername}) => {
    const [photourl,setPhotourl]=useState(profile)
    const [photo,setPhoto]=useState(null);
    const handleImageChange=(e)=>{
       if(e.target.files[0]);
       setPhoto(e.target.files[0]);
    }
     function handleImageClick(e){
        if(photo)
        {
        const photoRef=ref(storage,photourl);
        console.log(photoRef);
         uploadBytes(photoRef,photo).then(()=>{
             getDownloadURL(photoRef).then((url)=>{
                 setPhotourl(url);
             }).catch((err)=>{
                 console.log(err);
             })
         }).catch((err)=>{
            console.log(err);
        });
        alert("Profile Image has been changed successfully. Click OK and Wait for a second to view the changes.");
        }
        else
        alert("Please upload a file")
    }
    // useEffect(()=>{
    //     if(user && user.photoURL)
    //     setphotourl(user.photoURL)
    // })
    return (
        <>
            <header>
                <nav>
                    <div className="logo"><h1 className=""><a href="#">SOLRUF</a></h1></div>
                    <div className="menu">
                            <h3>Welcome {username}</h3>   
                            <img className="avatar" src={photourl}/> 
                            <button >Change Username</button>                    
                    </div>
                </nav>
                <main>
                    <section>
                        <h3>Welcome To India</h3>
                        <h1>Do come and Visit<span className="change_content"> </span></h1>
                        <p>"India once is not enough"</p>
                        
                        <input  type="file" onChange={(e)=>{handleImageChange(e)}}/>
                        <button onClick={(e)=>{handleImageClick(e)}}>Change Profile Pic</button>   
                    </section>
                </main>
            </header>
        </>
    )
}

export default Homepage

How to manipulate date using Javascript

How can I achieve this output if user input 04-29-2022 and the
output is like this

Output:
05-14-2022
05-29-2022
06-14-2022
06-29-2022
07-14-2022
07-29-2022
08-14-2022
08-29-2022

var dateRelease = new Date("04-29-2022")

const terms = 8
for (let i = 0; i < terms; i++) {
  console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))

}

JS – Can I get the next open div element – Not the sibling

Is it possible using just JS (or possibly with jQuery) to get the next open html element?

In the snippet below, if I click on any div it’ll give me the id of that div. I want it to get the next open element id, so e.g.

if I click on page123 it should give me 123efter
if I click on 123efter it should give me 13

I don’t want the next sibling within the encapsulating div, which is all I’ve managed to do so far!

document.addEventListener("click", function(event) {
console.log(event.target.id);
}
);
.efter{
min-height:20px;
}
.efter:hover{
background-color:beige;
}
<div>
  <div id="1">
    home
    <div id="1efter" class="efter"></div>
    <div id="11">
      page11
      <div id="11efter" class="efter"></div>
    </div>
    <div id="12">
      page12
      <div id="12efter" class="efter"></div>
      <div id="121">
        page121
        <div id="121efter" class="efter"></div>
      </div>
      <div id="122">
        page122
        <div id="122efter" class="efter"></div>
      </div>
      <div id="123">
        page123
        <div id="123efter" class="efter"></div>
      </div>
    </div>
    <div id="13">
      page13
      <div id="13efter" class="efter"></div>
    </div>
  </div>
</div>

How can I create button by using FTD? FTD is created by FifthTry – https://ftd.dev

While using FTD a new front-end language created by Fifthtry(https://www.fifthtry.com). Its easy to use for its non-technical users. Even if you don’t have any prior knowledge of html, css1 OR JavaScript you can write magical code.

Even they have collection of icons, which can be used inside button and you can create button with icons. Octicons in FTD

Package Name: https://fifthtry.github.io/button/

e.g.

  1. Primary Button
-- button: PRIMARY
role: primary
large: true
  1. Secondary Button
-- button: SECONDARY
role: secondary
large: true
  1. Button with icon
-- button: BUTTON
role: primary
large: true
icon-left: true
icon: icon.info:

Buttons created by using FTD language

FTD buttons with icon

Can’t get the result of an NPM library (not library specific) [duplicate]

For hours I have been trying to get this piece of code to work.

— I tried not async as well btw.

getSentenceNouns(){
    wordpos.getNouns(this.sentence, async (result) => {
        let nouns = await result;
        return nouns;
    })};

However the return value is undefinied, but if I console log inside the getNouns method I get the desired output… I tried it all, nausea kicked in, plz help.

How to define overlayMode for easyMDE?

I’ve tried to define custom mode for highlight custom markdown syntax with easyMDE like this:

CodeMirror.defineMode("mymode", function () {
  return {
    token: function (stream, state) {
      if (stream.match("aaa")) {
        return "style1";
      } else if (stream.match("bbb")) {
        return "style2";
      } else {
        stream.next();
        return null;
      }
    },
  };
});

window.easyMDE = new EasyMDE({
  element: $('#textarea')[0],
  parsingConfig: {
    allowAtxHeaderWithoutSpace: true,
  },
  overlayMode: {
    mode: CodeMirror.modes.mymode(),
    combine: true,
  },
});

Actually, CodeMirror don’t return mymode by CodeMirror.getMode('mymode') so may be there mistake in declaration by CodeMirror.defineMode in my code.

How to show and hide loader while using fetch in JavaScript?

I’m using JavaScript Fetch to access an API and I want to show a loader while the fetch is in progress. I’m using the following code…

      async function fetchStates() {
            showLoader();
            await fetch('https://localhost:7123/locations/states?token=@{@HttpContext.Session.GetString("sessionToken")}')
            .then(response => response.json())
            .then(states => {
                for (let i = 0;i < states.length;i++){
                    let option = document.createElement('option');
                    option.text = states[i].name;
                    option.value = states[i].id;
                    ddlCAStates.appendChild(option)
                }
                /*hideLoader(1);
                scrollToTop(1);*/
            })
            .catch(error => {
                divErrors.style.display = "block";
                let errorName = GetHttpErrorName(error.toString());
    
                txtErrors.textContent = 'The server responded with error: ' + error + ' ' + errorName;
                /*hideLoader(2);
                scrollToTop(2);*/
            })
            .finally(() => {
                hideLoader();
                scrollToTop();
            });
        }

    function showLoader() {
        document.getElementById('loader').style.display = 'block';
    }

    function hideLoader() {
        document.getElementById('loader').style.display = 'none';
    }

    function scrollToTop() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    }

The loader displays for a split second and then hides way before the fetch is completed. The loader should be visible until either the fetch successfully loads data or it fails for any reason. What I’m doing wrong here?

Failed to traverse DOM while rendered inside iframe with section tags

I facing a situation which i can’t traverse the dom inside iframe. My code is as follows. When i am trying to accessing childNodes of body tag, console will show there are no childNodes inside the body tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <iframe id="container"
        src="./resources/c07.xhtml"
        frameborder="0"></iframe>
    <style>
        #container {
            width: 100%;
            height: 800px;
        }
    </style>
    <script src="index.js"></script>
</body>
</html>

c07.xhtml

<!DOCTYPE html>
<html>
<body>

<h1>The section element</h1>

<section>
  <h2>History</h2>
  <p>The World Wide Fund for Nature (WWF)</p>
</section>

<section>
  <h2>Symbol</h2>
  <p>The Panda has become the symbol of WWF.</p>
</section>

</body>
</html>

//index.js

const parentNode = document.querySelector("#container");
const iframeBody =  iframeRef(parentNode);
console.log(element.childNodes[0].getElementsByTagName('section')); //prints HTMLCollection[] and length is 0

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

How can i resolve this?