Header Not Appearing in Generated PDF using html2pdf in asp.net

  function convertHtmlToPdf() {
      const element = document.getElementById('incidentReport');
      const headerContent = generateHeaderContent(); // Get the header content

      var reportPageHeight = $('#incidentReport').innerHeight();
      var reportPageWidth = $('#incidentReport').innerWidth();

      var pdf = new html2pdf(element, {
          margin: [45, 10, 10, 10],
          pagebreak: { mode: 'avoid-all' },
          html2canvas: { scale: 1 },
          image: { type: 'png', quality: 1.0 },
          jsPDF: {
              unit: 'pt',
              format: [reportPageWidth, reportPageHeight],
              orientation: 'landscape',
          }
      }).set(headerContent).save('IncidentReport.pdf');
  }

  function generateHeaderContent() {
      const startDate = $('#startDateIncident').val();
      const endDate = $('#finDateIncident').val();
      const todayChecked = $('#todayIncident').is(':checked');
      const dateRange = todayChecked ? 'Today' : (startDate + ' to ' + endDate);

      const header = ` <div style="display: flex; align-items: center; margin-bottom:20px;">
  <div style="margin-left:40px;">
      <img src="/app-assets/images/logo/logo-color3.png" alt="Logo" style="max-height: 40px;">
  </div>
  <div style="font-size: 12px; margin-left:180px;">Date: ${dateRange}</div>
  </div> `;

      return header;
  }

Troubleshooting Header Absence in ASP.NET’s html2pdf Generated PDF

I attempted to include a header in a PDF generated using html2pdf in ASP.NET. I expected the header to be visible in the generated PDF document, but despite setting it up correctly, it did not appear.

How to display average ratings in the form of stars in django

I want to display the average rating on a product in the form of stars where i want to have 5 stars and then fill the stars with gold color on how much the average rating on the product is.
This is my code and my relation b/w models

class Product(models.Model):
name = models.CharField(max_length=300)
price = models.DecimalField(max_digits=7, decimal_places=2)
image_url = models.CharField(max_length=400)
digital = models.BooleanField(blank=False)
sizes =  models.ManyToManyField(Size, through='ProductSize')
quantity = models.IntegerField(default=1)

    def __str__(self):
       return self.name
    
    @property
    def get_average_rating(self):
    average = self.comment_set.aggregate(Avg('rating'))['rating__avg']
    if average is not None:
      return round(average, 1)
    else:
      return 0 



class Comment(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   product = models.ForeignKey(Product, on_delete=models.CASCADE)
   text = models.TextField()
   image = models.ImageField(upload_to='images/comment_images', null=True, blank=True)
   created_on = models.DateField(auto_now_add=True)
   rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)])

 


I tried to run a loop like this but it did not work as the average rating is in float

I do not know much javascript so if you can help me in js that will be appreciated too thank you!!

           {% for _ in product.get_average_rating %}
               &#9733;
           {% endfor %}

Swap array items and reorder them accordingly

I have this kind of data structure:

[{id: 'a', order: 9 }, {id: 'b', order: 6 }, {id: 'c', order: 4 }, {id: 'd', order: 2 }].

I want to assign to item B the order value of item D and reorder the ‘order’ value of each item accordingly:

[{id: 'a', order: 9 }, {id: 'b', order: 4 }, {id: 'c', order: 2 }, {id: 'd', order: 6 }].

Here is a visual representation (decrescent order by “order” value):

A/B/C/D -> A/D/B/C

I’m struggling to write a function in JavaScript that do this having as an input:

  • The “id” of the item I want to move
  • The desired key index position of the item in the array

In my example above the parameters would be (‘d’, 1)

I’m tried various approaches with no success, any help is appreciated

generateStaticParams() not working in NextJs/TypeScript

I have a products page in my NextJs app. Dynamic routes should get rendered statically using generateStaticParams(), however they do not. when I run “npm run build” it says “Generating static pages (3/3)”when it should be much more than 3 and also when I deploy the project on Vercel and click on a single product card. instead of it taking me to the corresponding product page, it gives me “500 internal server error”. Also, it used to work before, but now I wrote some new types, otherwise I did not touch anything else related to this page, but it stopped working.

import Image from "next/image"

export async function generateStaticParams() {
    const res = await fetch('https://dummyjson.com/products')
    const products = await res.json()

    const paths = products.products.map((product: {id: number}) => ({
        id: `${product.id}`,
    }))

    return paths
}


async function getProduct(id: number) {
    const res = await fetch(`https://dummyjson.com/products/${id}`)
    const data = await res.json()
    return data
}


export default async function Service({ params }: { params: {id: number} }) {
    
    const product = await getProduct(params.id)

    return (
        <div style={{display: "flex", flexDirection: "column"}}>
            <h1>{product.title}</h1>
            <Image src={product.thumbnail} alt="asd" width={400} height={400}/>
            <span>In stock: {product.stock}</span>
        </div>
    )
}

This is the parent:

"use client";

import '@/styles/BlogServices.css'
import ServiceSection from '@/components/ServiceSection.tsx'
import React from 'react'


export default function Services() {
    
    interface Product {
        id: number,
        title: string,
        description: string,
        price: number,
        image: string,
        category: string
    }


    const [searchedService, setSearchedService] = React.useState<Product[]>([])
    const [defaultService, setDefaultService] = React.useState<Product[]>([])

    React.useEffect(() => {
        fetch('https://dummyjson.com/products')
        .then(res => res.json())
        .then(res => {
            setSearchedService(res.products)
            setDefaultService(res.products)
        })
    },[])



    function handleSearch (value:string) {
        setSearchedService(defaultService.filter(item => item.title.toLowerCase().includes(value.toLowerCase())))
    }

    return (
        <div className="services-page-container">
            <div className="blog-service-page-title-container parent-flex-column-center dark:bg-slate-900">
                <span className="blog-service-page-short-title">SERVICES</span>
                <h1 className="blog-service-page-title font-bold">Choose and book service with us</h1>
                <p className="blog-service-page-desc text-page-subtitle text-xl dark:text-slate-400">Subscribe to learn about new product features, the latest in technology, solutions, and updates.</p>
            </div>
            <ServiceSection 
                servicePage
                descStyle='services-section-desc'
                handleSearch={handleSearch}
                searchedService={searchedService}
                defaultService={defaultService}
            />
        </div>
    )
}

And this is the card component itself:

"use client";

import servicearrow from '../public/assets/servicearrow.svg'
import '../styles/Card.css'
import Image, { StaticImageData } from 'next/image'
import { useRouter } from 'next/navigation'

interface ServiceCard {
    id?: number;
    title: string;
    desc: string;
    date?: string;
    img: string | StaticImageData;
    imgStyle: string;
    contStyle: string;
    descStyle: string;
    servicepage?: boolean;
    handleClick?: () => void;
}

export default function ServiceCard(props: ServiceCard) {

    const router = useRouter()

    function handleClick() {
        props.servicepage && router.push(`/services/${props.id}`)
    }
    
    return (
        <div className={`card-container ${props.contStyle} dark:bg-slate-600`} onClick={handleClick}>
            <Image src={props.img} className={`card-img ${props.imgStyle}`} width={300} height={300} alt=''/>
            <span className='card-date'>{props.date}</span>
            <h3 className='text-xl font-bold mb-5 dark:text-slate-200'>{props.title}</h3>
            <p className={`card-description ${props.descStyle} dark:text-slate-50`}>{props.desc}</p>
            <span className='text-service-card-orange flex mt-auto dark:text-orange-700'>View full information <Image className='ml-6' src={servicearrow} alt="" /></span>
        </div>
    )
}

This is the file structure:
enter image description here
NOTE: “services” is the products page I am talking about.

I am new to TypeScript, but still I don’t think adding some new types should have caused this to stop working. Thanks in advance.

I do not even know what to try, because I can not find anything to help me out online and not being familiar with typescript makes it even worse.

Translate my PDF using Google’s free translation service

Translate my PDF using Google’s free translation service.

I’m doing a lot of research to use a browser to translate a single PDF translation page without using any pure JS API. But it doesn’t work and I can’t figure out what’s preventing it from working properly. I found this answer Translate PDF file using Google Translate API on Stackoverlow it doesn’t work correctly.

Image of the question on Stackoverlow

AND when I converted its code to pure JS so as not to use any SlimerJS and Phantomjs. It doesn’t work properly and I don’t know what to do.

Here’s the converted JS code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Translator</title>
</head>
<body>
    <form id="pdfForm">
        <input type="file" id="pdfInput" accept=".pdf" required>
        <button type="submit">Translate PDF</button>
    </form>

    <script>
        document.getElementById('pdfForm').addEventListener('submit', function(event) {
            event.preventDefault();
            var pdfFile = document.getElementById('pdfInput').files[0];
            if (pdfFile) {
                var pdfUrl = URL.createObjectURL(pdfFile);
                translatePDF(pdfUrl);
            } else {
                alert('Please select a PDF file.');
            }
        });

        function translatePDF(pdfUrl) {
            window.open('https://translate.google.com/translate?hl=en&sl=fr&u=' + encodeURIComponent(pdfUrl));
            
            setTimeout(function() {
                var translationIframe = document.querySelector('iframe');
                if (translationIframe) {
                    setTimeout(function() {
                        translationIframe.contentWindow.print();
                        console.log('PDF translation completed successfully.');
                    }, 5000);
                } else {
                    console.log('Translation iframe not found.');
                }
            }, 5000);
        }
    </script>
</body>
</html>

Here’s the result:

Result image in browser

Now I’d like you to tell me a little more about this so that my code works. Or can you give me a technique so that I can translate my PDF page please? I will do my best to explain my problem to you. So, any help from you will help me a lot…

Vue Js (reusable template)

hello member Iam a beginer in VUE JS and i need some help, is have a sidebar admin template, which i added in my code, one of my code is a registration form and another code displays the data of registered users in a table, now i want to place them in this template if the admin clicks on the dashboard link button it should display a table and when he clicks on the Teams button it should display the register form.

here is my code for HomeView.vue

<template>
  <!--
    This example requires updating your template:

    ```
    <html class="h-full bg-white">
    <body class="h-full">
    ```
  -->
  <div>
    <TransitionRoot as="template" :show="sidebarOpen">
      <Dialog class="relative z-50 lg:hidden" @close="sidebarOpen = false">
        <TransitionChild as="template" enter="transition-opacity ease-linear duration-300" enter-from="opacity-0" enter-to="opacity-100" leave="transition-opacity ease-linear duration-300" leave-from="opacity-100" leave-to="opacity-0">
          <div class="fixed inset-0 bg-gray-900/80" />
        </TransitionChild>

        <div class="fixed inset-0 flex">
          <TransitionChild as="template" enter="transition ease-in-out duration-300 transform" enter-from="-translate-x-full" enter-to="translate-x-0" leave="transition ease-in-out duration-300 transform" leave-from="translate-x-0" leave-to="-translate-x-full">
            <DialogPanel class="relative mr-16 flex w-full max-w-xs flex-1">
              <TransitionChild as="template" enter="ease-in-out duration-300" enter-from="opacity-0" enter-to="opacity-100" leave="ease-in-out duration-300" leave-from="opacity-100" leave-to="opacity-0">
                <div class="absolute left-full top-0 flex w-16 justify-center pt-5">
                  <button type="button" class="-m-2.5 p-2.5" @click="sidebarOpen = false">
                    <span class="sr-only">Close sidebar</span>
                    <XMarkIcon class="h-6 w-6 text-white" aria-hidden="true" />
                  </button>
                </div>
              </TransitionChild>
              <!-- Sidebar component, swap this element with another sidebar if you like -->
              <div class="flex grow flex-col gap-y-5 overflow-y-auto bg-indigo-600 px-6 pb-4">
                <div class="flex h-16 shrink-0 items-center">
                  <img class="h-8 w-auto" src="https://tailwindui.com/img/logos/mark.svg?color=white" alt="Your Company" />
                </div>
                <nav class="flex flex-1 flex-col">
                  <ul role="list" class="flex flex-1 flex-col gap-y-7">
                    <li>
                      <ul role="list" class="-mx-2 space-y-1">
                        <li v-for="item in navigation" :key="item.name">
                          <a :href="item.href" :class="[item.current ? 'bg-indigo-700 text-white' : 'text-indigo-200 hover:text-white hover:bg-indigo-700', 'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold']">
                            <component :is="item.icon" :class="[item.current ? 'text-white' : 'text-indigo-200 group-hover:text-white', 'h-6 w-6 shrink-0']" aria-hidden="true" />
                            {{ item.name }}
                          </a>
                        </li>
                      </ul>
                    </li>
                    <li>
                      <div class="text-xs font-semibold leading-6 text-indigo-200">Your teams</div>
                      <ul role="list" class="-mx-2 mt-2 space-y-1">
                        <li v-for="team in teams" :key="team.name">
                          <a :href="team.href" :class="[team.current ? 'bg-indigo-700 text-white' : 'text-indigo-200 hover:text-white hover:bg-indigo-700', 'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold']">
                            <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border border-indigo-400 bg-indigo-500 text-[0.625rem] font-medium text-white">{{ team.initial }}</span>
                            <span class="truncate">{{ team.name }}</span>
                          </a>
                        </li>
                      </ul>
                    </li>
                    <li class="mt-auto">
                      <a href="#" class="group -mx-2 flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-indigo-200 hover:bg-indigo-700 hover:text-white">
                        <Cog6ToothIcon class="h-6 w-6 shrink-0 text-indigo-200 group-hover:text-white" aria-hidden="true" />
                        Settings
                      </a>
                    </li>
                  </ul>
                </nav>
              </div>
            </DialogPanel>
          </TransitionChild>
        </div>
      </Dialog>
    </TransitionRoot>

    <!-- Static sidebar for desktop -->
    <div class="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-72 lg:flex-col">
      <!-- Sidebar component, swap this element with another sidebar if you like -->
      <div class="flex grow flex-col gap-y-5 overflow-y-auto bg-indigo-600 px-6 pb-4">
        <div class="flex h-16 shrink-0 items-center">
          <img class="h-8 w-auto" src="https://tailwindui.com/img/logos/mark.svg?color=white" alt="Your Company" />
        </div>
        <nav class="flex flex-1 flex-col">
          <ul role="list" class="flex flex-1 flex-col gap-y-7">
            <li>
              <ul role="list" class="-mx-2 space-y-1">
                <li v-for="item in navigation" :key="item.name">
                  <a :href="item.href" :class="[item.current ? 'bg-indigo-700 text-white' : 'text-indigo-200 hover:text-white hover:bg-indigo-700', 'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold']">
                    <component :is="item.icon" :class="[item.current ? 'text-white' : 'text-indigo-200 group-hover:text-white', 'h-6 w-6 shrink-0']" aria-hidden="true" />
                    {{ item.name }}
                  </a>
                </li>
              </ul>
            </li>
            <li>
              <div class="text-xs font-semibold leading-6 text-indigo-200">Your teams</div>
              <ul role="list" class="-mx-2 mt-2 space-y-1">
                <li v-for="team in teams" :key="team.name">
                  <a :href="team.href" :class="[team.current ? 'bg-indigo-700 text-white' : 'text-indigo-200 hover:text-white hover:bg-indigo-700', 'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold']">
                    <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border border-indigo-400 bg-indigo-500 text-[0.625rem] font-medium text-white">{{ team.initial }}</span>
                    <span class="truncate">{{ team.name }}</span>
                  </a>
                </li>
              </ul>
            </li>
            <li class="mt-auto">
              <a href="#" class="group -mx-2 flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-indigo-200 hover:bg-indigo-700 hover:text-white">
                <Cog6ToothIcon class="h-6 w-6 shrink-0 text-indigo-200 group-hover:text-white" aria-hidden="true" />
                Settings
              </a>
            </li>
          </ul>
        </nav>
      </div>
    </div>

    <div class="lg:pl-72">
      <div class="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-gray-200 bg-white px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8">
        <button type="button" class="-m-2.5 p-2.5 text-gray-700 lg:hidden" @click="sidebarOpen = true">
          <span class="sr-only">Open sidebar</span>
          <Bars3Icon class="h-6 w-6" aria-hidden="true" />
        </button>

        <!-- Separator -->
        <div class="h-6 w-px bg-gray-900/10 lg:hidden" aria-hidden="true" />

        <div class="flex flex-1 gap-x-4 self-stretch lg:gap-x-6">
          <form class="relative flex flex-1" action="#" method="GET">
            <label for="search-field" class="sr-only">Search</label>
            <MagnifyingGlassIcon class="pointer-events-none absolute inset-y-0 left-0 h-full w-5 text-gray-400" aria-hidden="true" />
            <input id="search-field" class="block h-full w-full border-0 py-0 pl-8 pr-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm" placeholder="Search..." type="search" name="search" />
          </form>
          <div class="flex items-center gap-x-4 lg:gap-x-6">
            <button type="button" class="-m-2.5 p-2.5 text-gray-400 hover:text-gray-500">
              <span class="sr-only">View notifications</span>
              <BellIcon class="h-6 w-6" aria-hidden="true" />
            </button>

            <!-- Separator -->
            <div class="hidden lg:block lg:h-6 lg:w-px lg:bg-gray-900/10" aria-hidden="true" />

            <!-- Profile dropdown -->
            <Menu as="div" class="relative">
              <MenuButton class="-m-1.5 flex items-center p-1.5">
                <span class="sr-only">Open user menu</span>
                <img class="h-8 w-8 rounded-full bg-gray-50" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="" />
                <span class="hidden lg:flex lg:items-center">
                  <span class="ml-4 text-sm font-semibold leading-6 text-gray-900" aria-hidden="true">Tom Cook</span>
                  <ChevronDownIcon class="ml-2 h-5 w-5 text-gray-400" aria-hidden="true" />
                </span>
              </MenuButton>
              <transition enter-active-class="transition ease-out duration-100" enter-from-class="transform opacity-0 scale-95" enter-to-class="transform opacity-100 scale-100" leave-active-class="transition ease-in duration-75" leave-from-class="transform opacity-100 scale-100" leave-to-class="transform opacity-0 scale-95">
                <MenuItems class="absolute right-0 z-10 mt-2.5 w-32 origin-top-right rounded-md bg-white py-2 shadow-lg ring-1 ring-gray-900/5 focus:outline-none">
                  <MenuItem v-for="item in userNavigation" :key="item.name" v-slot="{ active }">
                    <a :href="item.href" :class="[active ? 'bg-gray-50' : '', 'block px-3 py-1 text-sm leading-6 text-gray-900']">{{ item.name }}</a>
                  </MenuItem>
                </MenuItems>
              </transition>
            </Menu>
          </div>
        </div>
      </div>

      <main class="py-10">
        <div class="px-4 sm:px-6 lg:px-8">
          <!-- Your content -->
        

        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {
  Dialog,
  DialogPanel,
  Menu,
  MenuButton,
  MenuItem,
  MenuItems,
  TransitionChild,
  TransitionRoot,
} from '@headlessui/vue'
import {
  Bars3Icon,
  BellIcon,
  CalendarIcon,
  ChartPieIcon,
  Cog6ToothIcon,
  DocumentDuplicateIcon,
  FolderIcon,
  HomeIcon,
  UsersIcon,
  XMarkIcon,
} from '@heroicons/vue/24/outline'
import { ChevronDownIcon, MagnifyingGlassIcon } from '@heroicons/vue/20/solid'

const navigation = [
  { name: 'Dashboard', href: 'users', icon: HomeIcon, current: true },
  { name: 'Team', href: 'register', icon: UsersIcon, current: false },
  { name: 'Projects', href: '#', icon: FolderIcon, current: false },
  { name: 'Calendar', href: '#', icon: CalendarIcon, current: false },
  { name: 'Documents', href: '#', icon: DocumentDuplicateIcon, current: false },
  { name: 'Reports', href: '#', icon: ChartPieIcon, current: false },
]
const teams = [
  { id: 1, name: 'Heroicons', href: '#', initial: 'H', current: false },
  { id: 2, name: 'Tailwind Labs', href: '#', initial: 'T', current: false },
  { id: 3, name: 'Workcation', href: '#', initial: 'W', current: false },
]
const userNavigation = [
  { name: 'Your profile', href: '#' },
  { name: 'Sign out', href: '#' },
]

const sidebarOpen = ref(false)
</script>
  1. And here is my code for App.vue
<template>
<main>
 
  <RouterView />
 


</main>
</template>

<script>
import { RouterView } from "vue-router";
import "./assets/tailwind.css";
export default {
  components: {
    RouterView,

  
  }
};
</script>

and here is my register.vue

<template>
  <div class="container mx-auto">
    <h1 class="text-3xl font-bold mb-8 text-center">Registration Form</h1>

    <form name="reg" class="max-w-md mx-auto">
      <div class="mb-4">
        <input v-model="Newuser.id" type="text" class="form-input rounded-md shadow-sm" name="userid" placeholder="User ID" required>
      </div>
      <div class="mb-4">
        <input v-model="Newuser.user_name" type="text" class="form-input rounded-md shadow-sm" name="username" placeholder="User Name" required>
      </div>
      <div class="mb-4">
        <input v-model="Newuser.user_email" type="email" class="form-input rounded-md shadow-sm" name="useremail" placeholder="User Email" required>
      </div>
      <button type="submit" @click.prevent="addUser" class="btn bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-full w-full">Register User</button>
    </form>
  </div>
</template>

<script>
export default {
  components: {
  },
  data() {
    return {
      RegisteredUser: [],
      Newuser: {
        id: "",
        user_name: "",
        user_email: "",
        userid: " ",
      }
    };
  },
  methods: {
    addUser() {
      let userid = document.forms['reg']["userid"].value;
      let username = document.forms['reg']['username'].value;
      let useremail = document.forms['reg']['useremail'].value;
      const EmailPattern = /^[^s@]+@[^s@]+.[^s@]+$/;

      if(userid == ""){
        alert('please enter your id....');
        return false;
      } 
      else if(username == ""){
        alert('please enter your username...');
        return false;
      }
      else if(useremail == "" ){
        alert('please enter your email.....')
        return false;
      }
      else if(!EmailPattern.test(useremail)){
        alert('please enter a valid email');
        return false;
      }

      if (this.UserIdExists(userid, this.RegisteredUser)) {
        alert("User ID already taken....");
        return false;
      }

      if (this.Newuser.id.trim() !== "" && this.Newuser.user_name.trim() !== "" && this.Newuser.user_email.trim() !== "") {
          const user_data = this.RegisteredUser.push({
            id: this.Newuser.id,
            user_name: this.Newuser.user_name,
            user_email: this.Newuser.user_email,
            isFavorite: false, // Initialize isFavorite property
          });
          console.log('Adding user:', this.Newuser);
          console.log(user_data)
          this.Newuser.id = "";
          this.Newuser.user_name = "";
          this.Newuser.user_email = "";
        }
    },
    toggleFavorite(index) {
        this.RegisteredUser[index].isFavorite = !this.RegisteredUser[index].isFavorite;
      },
      // Check if the user id already exists...
    UserIdExists(existId, RegisteredUser) {
      return RegisteredUser.some(user => user.id === existId);
    },
  


  },

created() {
      // Retrieving data from sessionStorage when the component is created
      const str = sessionStorage.getItem('registeredUsers');
      if (str) {
        this.RegisteredUser = JSON.parse(str);
        console.log(this.RegisteredUser);
      }
    },

    watch: {
      RegisteredUser: {
        handler(newVal) {
          // Saving data to sessionStorage whenever RegisteredUser changes
          sessionStorage.setItem('registeredUsers', JSON.stringify(newVal));
        },
        deep: true
      }
    }
}
</script>

here is my UserTable.vue code

<template>
  <div class="container mx-auto flex flex-col h-full">
    <h1 class="text-3xl font-bold mt-7 mb-4 text-center">Registered Users</h1>

    <div class="flex-grow overflow-x-auto">
      <table class="w-full bg-white shadow-md rounded-lg overflow-hidden">
        <thead class="bg-purple-700 text-white">
          <tr>
            <th class="px-3 py-2">User ID</th>
            <th class="px-3 py-2">User Name</th>
            <th class="px-3 py-2">User Email</th>
            <th class="px3 py-2">Action</th>
          </tr>
        </thead>
        <tbody class="text-gray-700">
          <tr v-for="(user, index) in users" :key="index" class="bg-gray-100">
            <td class="border px-3 py-1">{{ user.id }}</td>
            <td class="border px-3 py-1">{{ user.user_name }}</td>
            <td class="border px-3 py-1">{{ user.user_email }}</td>
          </tr>
        </tbody>
      </table>
    </div>

  </div>
</template>



<script>
export default {
  data() {
    return {
      users: [] // Initialize users array to store retrieved data
    };
  },
  mounted() {
    // Retrieve data from sessionStorage when the component is mounted
    const storedData = sessionStorage.getItem('registeredUsers');
    if (storedData) {
      // Parse the stored data and assign it to the users array
      this.users = JSON.parse(storedData);
    }
  }
}
</script>

Learning Java for beginners [closed]

I’m currently in the process of transitioning into a software engineering role, and I’ve decided to begin my journey by learning Java. However, I’m unsure which version of Java I should start with, and I’m also seeking recommendations for free tutorials to kickstart my learning.

Previously, I was learning Python, and someone suggested that I first delve into Java before progressing to React.js. With that in mind, could anyone provide guidance on where I should begin with Java? Additionally, I’d greatly appreciate any recommendations for high-quality tutorials to help me get started on the right foot.

Thank you in advance for your assistance!

I’ve been searching around, but I’m feeling quite lost.

Angular: Generating a report pdf from template keys

I have a report template (doc/docx) that needs to be filled by the data stored in a Firebase database. And converted to PDF at the end.

I know Apryse documentation does this ,however; I am looking for free options that can be implemented based on our needs.

Thanks,

For example:

Dear {{firstname}},

This report has been developed by the {{departmentName}}. This document provides a {{pointInTime}},{{summaryActionableKey}} key lessons learned in safety framework and concepts.

I want the template keys {{ }} to be filled out automatically with data that we have in the database.

React, confused in useState

Can anyone explaine me please, just start learn React, I’m confused in one thing in this code:

import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red",
  });

  const updateColor = () => {
    setCar((previousState) => {
      return { ...previousState, color: "blue" };
    });
  };

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button type="button" onClick={updateColor}>
        Blue
      </button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Car />);

previousState , If we only called setCar({color: “blue”}), this would remove the brand, model, and year from our state,
so previousState concatenating them, but how previousState accessed brand, model and year? ewhen they were attributed to him?

previousState is not a keyword no?

How to use a js library inside t-name template in odoo

I am trying to use a multiselection library inside a template (<t t-name=…) rendered by qweb.render.
the library works fine in home page (<template id=…), but it won’t work in <t t-name=…
enter image description here

i am using odoo 15 community

Can any one help me with this.
Best regards

i ve called the .js and .css files of the library in web.assets_frontend.

  • the Not working code:
<templates id="template" xml:space="preserve">
    <t t-name="t_lead_form">
        <select multiple="multiple" name="language" class="b_multiselection">
              <option value="js">JavaScript</option>
              <option value="html">HTML</option>
              <option value="css">CSS</option>
            </select>
    </t>
</templates>
  • The working code:
<template id="createFormModal">
<select multiple="multiple" name="language" class="b_multiselection">
                                  <option value="js">JavaScript</option>
                                  <option value="html">HTML</option>
                                  <option value="css">CSS</option>
                                </select>
</template>

Social Media Search Api [closed]

I am making social media sentiment analysis as my mini project for ongoing semester . I want to fetch textual data related to a certain keyword from platforms like facebook,twitter,instagram and other social media platform so that i can perform sentiment analysis on that data .

How do I fetch data from keywords . If there are free public api’s or let me know method so that i can fetch data

Fast processing of large text files in NodeJS

I have to process large text files efficiently in NodeJS and can’t seem to improve further than the code below.

The input file is a ~50 Gb files of text, the processing logic is to compute some type of sums and produce an output file of aggregated data.

At first, i hit the Heap Space limit trying to read the whole file at once, so I partionned the reading part into chunks of 1,000,000 lines but that’s as fast as I could go, namely 1 hour and 20 mins for 300,000,000 lines. I tried to a promise based approach where the aggregation of the chunks happen in parallel with the next chunk reading, also thought about workers but that’s not ideal for passing large data over to the threads.

I would like help in reviewing and improving this code, I am not sure the aggregation does run in parallel of the next read phase or does it?

I am using the line-reader convenience library.

async function parseFileFast(fileName_) {
    var end, start = Date.now();
   ///... basic checks omitted

    var chunkSize = 3000000;
    var chunkIndex = 0; 
    var chunkCounter = 0;
    var lineCounter = 0;
    var chunkData = []; 
    console.log("processing .. " + fileName_);

    var result = [];
    // return new Promise((ok, ko) => {
    lineReader.eachLine(fileName_, async function(line) {
        chunkData.push(line);
        chunkCounter++;
        lineCounter++;

        if (chunkCounter >= chunkSize) {
            console.log("reaching boundary .. " + chunkIndex);
            console.log("processed lines so far .. " + lineCounter); 
            aggregate(chunkData, chunkIndex).then((data) => {
                result.push(...data.frames); 
            }); 
            chunkData = [];
            chunkCounter = 0;
            chunkIndex++;
        }
    }, async function(err) {
        if (err) throw err; 
        var status = writeOutput2(result, fileName_.replace(".csv", "3.csv"));
        end = Date.now();
        console.log("finished processing everything in sec: " + ((end - start) / 1000));
        return status;
    }); 
}

function aggregate(dataSet, index){ 
    return new Promise((resolve, reject)=>{
        var frames = new Map(); 
        dataSet.forEach((line) => {
            frames = processFrames(line, frames);
        }); 
        var result = { frames: frames, index: index};
        resolve(result);
    })
}

How do I make an about:blank cloak work automatically similiar to Interstellars?

I already got an about; blank cloak, but you have to click it for it to work, is there any way to cloak the site right as you open it?

The script I used was

<button onclick="openGame()">about:blank cloak</button>
    <script>
        function openGame() {
    var win = window.open()
    var url = "https://learnmathswithme.weebly.com"
    var iframe = win.document.createElement('iframe')
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.style.border = "none";
    iframe.src = url
    win.document.body.appendChild(iframe)
    }
    </script>

which I found off the internet (since I’m not a coder), is there a change I can make to cloak the site automatically?