how do i use prismjs when importing into a web-component

I am attempting to use prismjs from a file I am importing into a web-component.

Here is the function which is supposed to return the prismjs highlighted code block

import Prism from 'prismjs';

function article() {
     const code = `var data = 1`;
     const html = Prism.highlight(code, Prism.languages.javascript, 'javascript')
     const pre = document.createElement('pre')
     const _code = document.createElement('code')
     _code.classList = 'language-js'
     _code.innerHTML = html
     pre.appendChild(_code)

     return pre
}

and here is my web-component

 export default class PostComponent extends HTMLElement {
     constructor() {
         super()
         this.shadow = this.attachShadow({mode: 'open'})
         this.styleSheet = document.createElement('style')

         window.addEventListener('popstate', async (e) => {
             const path = e.state;
             const module = await GetArticle(path)

             this.articleName = module.title()
             this.canvasApp = module.canvasApp()
             this.article = module.article()

             this.shadow.replaceChildren(
                 this.styleSheet,
                 this.articleName,
                 this.canvasApp,
                 this.article
             )
         });

     }

     connectedCallback() {
         this.RenderView();
     }

     RenderView() {
         this.styleSheet.textContent = Style;
     }
 }

I am including the prism.min.css from index.html.

What gets ultimately rendered is an unhighlighted code element which is not what I am looking for. I have tried using Prism.highlightAll() in the article() function and the constructor but neither works.

how to deal with problematic article publication websites

I want to ask regarding the error below
Search engines may use href attributes on links to crawl websites. Ensure that the href attribute of anchor elements links to an appropriate destination, so more pages of the site can be discovered. Learn how to make links crawlable
Uncrawlable Link
div.lb-outerContainer > div.lb-container > div.lb-loader > a.lb-cancel <a class="lb-cancel">
div.lb-dataContainer > div.lb-data > div.lb-closeContainer > a.lb-close <a class="lb-close">
For SEO optimization I’m still at 92%, how can I get it to 100%?

Maybe someone can help, my tutor can contact me further

Maybe I’ve tried changing the coding structure by replacing the anchor with a link that is already fixed. I hope the SEO produced by my articles with organic article types can be 100%

Scrollbar not appearing inside a div in React

I’m trying to implement a vertical scrollbar in my React app within a specific div (.thelist) where tasks are displayed. Despite setting overflow-y: auto and a fixed height, the scrollbar either doesn’t appear, or the tasks overflow the container.

Here’s the relevant code:

Below is my ListNote.js component:

function ListNote({ title, onDelete, onEdit, id }) {
      return (
        <div className="thelist">
            <div className='task-item'>
                <span className='task-name'>{title}</span>
                <div className='button-group'>
                    <button onClick={() => 
onEdit(id)}>Edit</button>
                    <button onClick={() => 
onDelete(id)}>Delete</button>
                </div>
            </div>
        </div>
    );
 }

CSS:

`.thelist {
    padding: 8px;
    height: 300px;
    overflow-y: auto;
}

.task-item {
    display: flex; 
    justify-content: space-between; 
    align-items: center;
    background: #8758ff;
    border-radius: 10px;
    padding: 5px 15px 5px 15px;
    box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.3), 
    0 5px 15px rgba(0, 0, 0, 0.2);
    max-width: 80%;
    margin-left: auto; 
    margin-right: auto;

}

.task-name {
color: #fff;
}`

I also have a header containing the title that should stay fixed at the top.

How can i avoid boilerplate code with Astro.currentLocale?

Here is an example of how i am using the Astro.currentLocale for translations in Astro.

---
import { getRelativeLocaleUrl } from "astro:i18n"

// Components
// imports ...

// i18n
import { getTranslations, type Lang } from "@/i18n/utils"

const lang = Astro.currentLocale as Lang
const t = getTranslations(lang)
---

<div>
    <div>
        <h2>{t("any-title")}</h2>
        <div>
            <a href={getRelativeLocaleUrl(lang, "any/route")}>
                {t("view-details")}
            </a>
        </div>
    </div>
    <div>
        <InventorySummaryLineChart lang={lang} client:load />
        <InventorySummaryBarChart lang={lang} client:load />
        <InventorySummaryPieChart lang={lang} client:load />
    </div>
</div>

In the last div tag, where i have 3 diferent charts i want them to be ‘prerendered’ so the title and description is already translated when it hits the client.

But i am being forced to pass the lang as a prop, because i can’t use window to get the url with the lang, and the document.documentElement.lang neither cause the layout with the lang setted could be rendered later.

How can i avoid then pass the lang as a param to framework components? and be able to get it in server side?

Maybe with a state manager, but how can i avoid rehydration problems?

Javascript error in python code: “Uncaught ReferenceError: map is not defined”

I”ve been desiging a window that shows an interactable map using PyQt5’s QtWebEngineWidgets> Here’s a preview of what I’ve been working on:
Window with interactive map

One of the things I’ve been trying to intergrate is when a user chooses any of the PO sample radio buttons, the map will change location towards where the sample is located. However, whenever I run the code, it gives me this error when the window appears:

js: Uncaught ReferenceError: map is not defined

Additionally, whenever I click any of the radiobuttons, it also gives me this:

js: Map instance not initialized.

I’ve been trying to use javascript to intergrate button functionality inside the map, where clicking on these buttons will show a message through the use of both Javascript and Python. The code is pretty long, so here are snippets of the code where the issues originate, both of which take place inside the UI_MainWindow() class:

def load_map(self):
        import folium
        import os

        center_lat, center_lng = 18.45, -66.08

        self.map_obj = folium.Map(
            location=[center_lat, center_lng],
            zoom_start=15,  # Adjust zoom level
            min_zoom=14,
            max_zoom=17,
            control_scale=True
        )

        html_button = """
        <button onclick="alert('PO1 Button Clicked!')" style="border-radius: 8px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none;">
            PO1
        </button>
        """
        folium.Marker([18.45, -66.08], icon=folium.DivIcon(html=html_button)).add_to(self.map_obj)

        html_button2 = """
        <button onclick="alert('PO2 Button Clicked!')" style="border-radius: 8px; padding: 5px 10px; background-color: #4CAF50; color: white; border: none;">
            PO2
        </button>
        """
        folium.Marker([18.46, -66.07], icon=folium.DivIcon(html=html_button2)).add_to(self.map_obj)

        move_js = """
        <script>
        var map_instance;

        function initializeMap() {
            // Assign the Leaflet map instance created by Folium to the global variable
            map_instance = map;
        }

        function moveToLocation(lat, lng) {
            if (map_instance) {
                map_instance.flyTo([lat, lng], 16);
            } else {
                console.error("Map instance not initialized.");
            }
        }
        </script>
        """
        self.map_obj.get_root().html.add_child(folium.Element(move_js))

        # Ensure the map instance is assigned after the DOM is fully loaded
        init_map_js = """
        <script>
        document.addEventListener("DOMContentLoaded", function(event) {
            initializeMap();  // Initialize the map instance
        });
        </script>
        """
        self.map_obj.get_root().html.add_child(folium.Element(init_map_js))
]
        map_path = os.path.join(os.getcwd(), "map_buttons.html")
        self.map_obj.save(map_path)

        self.webView.setUrl(QtCore.QUrl.fromLocalFile(map_path))

def update_label(self, radio_button):
        if radio_button.isChecked():
            self.sample_selected = True
            self.label_8.setText("MUESTRA SELECCIONADA: " + radio_button.text())

            # Enable buttons
            self.btn1.setEnabled(True)
            self.btn2.setEnabled(True)
            self.btn3.setEnabled(True)
            self.btn4.setEnabled(True)

            # Move the map based on the selected radio button
            if radio_button == self.radio:
                # PO1 selected, move to its location
                self.webView.page().runJavaScript("moveToLocation(18.45, -66.08);")
            elif radio_button == self.radio2:
                # PO2 selected, move to its location
                self.webView.page().runJavaScript("moveToLocation(18.46, -66.07);")
            # same for other buttons

Image Warped in jsPDF PDF Generation, Cannot Set Auto Height and Image Not Appearing in PDF Due to Mixed Content Issues

I’m working on generating a PDF in a web application using jsPDF. One of the challenges I’m facing is adding a logo image to the header of the PDF while maintaining the correct aspect ratio and ensuring it doesn’t get warped. I also encountered a mixed content issue, where the image is served over HTTP while the page is loaded over HTTPS.

Problem: Image Warping in PDF

I need to dynamically set the image height based on its original aspect ratio. According to jsPDF documentation, I cannot set imgHeight to auto, so I tried calculating the image height using the following formula to maintain the aspect ratio:

var imgHeight = (img.height / img.width) * imgWidth;

Current Code for Adding Image:

   function downloadPDF(submissionId, formJSON) {
            console.log('Downloading PDF for submission ID formJSON:', formJSON);
            var submissionCard = document.getElementById('submission-card');
            var pdf = new window.jspdf.jsPDF();
            var parser = new DOMParser();
            var doc = parser.parseFromString(submissionCard.innerHTML, 'text/html');

    // Function to load the image and convert it to base64
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        return canvas.toDataURL("image/png"); // Returns base64 of the image
    }

    // Add logos as header to each page
    function addHeader(pdf, logoSrc, format) {
        if (logoSrc && format) {
            var img = new Image();
            img.src = logoSrc;

            img.onload = function () {
                var pageWidth = pdf.internal.pageSize.getWidth();
                var imgWidth = logoSize; // Width of the image
                var imgHeight = (img.height / img.width) * imgWidth; // Maintain aspect ratio

                var x = (pageWidth - imgWidth) / 2; // Center the image horizontally

                // Convert the image to base64 and add to PDF
                var base64Image = getBase64Image(img);
                pdf.addImage(base64Image, format, x, 10, imgWidth, imgHeight);
            };

            img.onerror = function () {
                console.error('Error loading image:', logoSrc);
            };
        }
    }
    
   
           // Load all logos, process nodes, and then add headers
            Promise.all(logos.map(loadImage)).then(async (loadedLogos) => {
                // Process all content nodes
                for (const node of doc.body.childNodes) {
                    // await processNode(node, loadedLogos, getImageFormat(loadedLogos[0].src));
                    await processNode(node, loadedLogos, loadedLogos.length > 0 ? getImageFormat(loadedLogos[0].src) : null);
                }

                // Add headers to each page
                var totalPages = pdf.internal.getNumberOfPages();
                for (var i = 1; i <= totalPages; i++) {
                    pdf.setPage(i);
                    var logo = loadedLogos[i % loadedLogos.length];
                    var format = getImageFormat(logos[i % logos.length]);
                    addHeader(pdf, logo, format);
                }

                // Save the generated PDF
                pdf.save('submission-' + submissionId + '.pdf');
            }).catch(error => {
                console.error('Error loading images:', error);
            });
        }

Problem: When I use this logic, image is not being displayed because of a mixed content error. The page is being loaded over HTTPS, but the images are being served over HTTP.

I tried to resolve this issue by using ngrok to set up a secure connection (HTTPS) for the application. However, the problem persists. I fetch the image and convert it to Base64 for adding to the PDF. This issue prevents the logo from being displayed in the PDF.

How can I properly set the image height in jsPDF to maintain the aspect ratio without warping the image?

Issues with ToString() method [closed]

I was coding in a library program for school, across an error when writing my toString method, its supposed to return the name of the library patron and the 3 book objects they either have or dont but apparently it says toString is an invalid modifier hovering over toString and Record is expected when hovering over String in the return type in the method

I tried to return info, it gave a syntax error

How to add sub sections into an HTML file from javascript

`Hey everyone, my name is Barry and I am extremely new to coding. Been struggling heavily on this one particular problem. I am asked to Populate the General Recordings List
For this TODO, you must assemble a new and for Billy’s general recordings data. Unlike TODO 4, there is not a section or unordered list in the DOM for the recordings, so you must use jQuery to create those elements, too.
a. Create a recordings and add it below the section for top rated recordings in the sidebar. How can you achieve this with jQuery?

b. Create a , style it, and add it to the .

c. Add a styled for every recording in the recordings Array. What lodash methods can help you here?

d. Add a separate for the title, artist, release, and year of each recording. Give them a class based on their key in the object.

e. Add CSS styling rules to the css/site.css file to style the list items. Can these style rules apply to list items in both the top rated and recordings lists? How can you achieve this with CSS selectors/rules and jQuery?

The resulting HTML should look something like this:

<section id="section-recordings">
  <ul id="list-recordings" class="list-recordings">
    <li class="recording">
      <div class="title">Title: Eastern Rebellion</div>
      <div class="artist">Artist: Cedar Walton</div>
      <div class="release">Release: Timeless</div>
      <div class="year">Year: 1976</div>
    </li>
    <!-- more list items here -->
  </ul>
</section>

//However my HTML file looks like this

<div id="sidebar" class="sidebar">
 <div id="image-container-billy" class="image-container">
  <img id="image-billy" src="images/billy/billy-0.jpg" i="0" width="25%" class="image">
  </div>
  <section id="section-top-rated" class="recordings">
  <header id="header-top-rated" class="header-recordings">Top Rated</header>
  <ul id="list-top-rated" class="list-recordings"></ul>
<li>Voice in the Night</li>
<li>The Shape of Jazz to Come</li>
<li>Like Sonny</li>
<li>Go</li>
<li>The Water Is Wide</li>

<section id="section-recordings">
<ul id="list-recordings" class="list-recordings"></ul>
<div class="title">Eastern Rebellion</div>
<div class="artist">Cedar Walton</div>
<div class="release">Timeless</div>
<div class="year">1976</div>
<div class="title">Soul Food</div>
<div class="artist">Bobby Timmons</div>
<div class="release">Prestige</div>
<div class="year">1966</div>
<div class="title">A Swingin' Affair</div>
<div class="artist">Dexter Gordon</div>
<div class="release">Blue Note</div>
<div class="year">1962</div>
<div class="title">Rejoice</div>
<div class="artist">Pharoah Sanders</div>
<div class="release">Theresa</div>
<div class="year">1981</div>
</section></section>
    </div>

//this is where my code in the js file begins:

const onReady = (data) => {
  // YOUR CODE BELOW HERE //

$('#section-bio').css('color', 'brown');
$('#section-quotes').css('color', 'blue');
  /* eslint-enable */
// TO DO 4 ////


const topRated = data.discography.topRated;

let newSection = document.createElement('section')
topRated.forEach((recording) => {
  $('#section-top-rated').append(`<li>${recording.title}</li>` );
  //let topR = $('#section-top-rated').append(`<li>${recording.title}</li>` );
});
const recordings = data.discography.recordings;

$(`<section id="section-recordings"></section>`).appendTo('#section-top-rated');
//$(`<ul id="list-recordings" class="list-recordings"></ul>`).appendTo('#section-recordings')
//$(`<li class="recording></li>`).appendTo('#list-recordings').appendTo('#list-recordings')
$('#list-recordings').append(`<li class="recording></li>`)
$(`#section-recordings`).append(`<ul id="list-recordings" class="list-recordings"></ul>`)
//$('#list-recordings').append(`<li class="recording></li>`)



recordings.forEach((element) => {
  $(`<li class="recording"></li>`)
  $('#section-recordings').append(`<div class="title">${element.title}</div>` )
  $('#section-recordings').append(`<div class="artist">${element.artist}</div>` )
  $('#section-recordings').append(`<div class="release">${element.release}</div>` )
  $('#section-recordings').append(`<div class="year">${element.year}</div>` )
})

  const uL = document.createElement('ul id="list-recordings" class="list-recordings"')

  uL.appendTo(`#section-recordings`)


  //let newSection = document.createElement('section');
//$(<section id="section-recordings"></section>)
 // const recordings = data.discography.recordings;
  //recordings.forEach(songs){

 // }
  // YOUR CODE ABOVE HERE //
};

Everything i tried has been commented out with the // markers. I have been stuck on this problem all day. I don’t know why but my

  • lists aren’t showing up, and I feel like that makes this problem much more difficult to solve due to their absence; i can’t see where it’s at so I don’t know how to move it around. Just a side note; the actual data.discography.recordings references an array of objects. Any level of assistance would help, even just words of encouragement. Cheers to anyone who attempts to help me with this issue. If I could at least figure out why i can’t find then that would be a huge step. cheers.`
  • Video doesn’t load for Medium devices

    I am creating a website that allows for multiple users to be on a video chat. I have styled it for xs devices and am trying to style it for medium now but for some reason the video won’t play strictly on the medium device (ipad) resolution I am using in chrome web devs. It will play on xs, lg, xl, etc…

    Here is how I create a new video for each user:

    const newElem = document.createElement('div')
    newElem.setAttribute('id', `td-${remoteProducerId}`)
    newElem.innerHTML = '<video id="' + remoteProducerId + '"autoplay class="rounded-xl border border-black w-auto h-auto"></video>'
    videoContainerRef.current.appendChild(newElem)
    document.getElementById(remoteProducerId).srcObject = new MediaStream([track])

    Here is how I style the container:

    <div ref={videoContainerRef} className="grid grid-cols-2 grid- gap-y-1 gap-x-3 w-1/2 p-3"></div>

    I have tried to make the video have a min-width or just set the width and that didn’t work. I have tried to set w/h to auto as well. One thing to note: It works when I load it on a different resolution and then switch it to medium it works… So it seems to just be on load.

    Shopify GraphQL: Create a variant with an inventory quanitity of 999

    I am creating variants for a Shopify product using productVariantsBulkCreate in the Shopify GraphQL API:

    mutation productVariantsBulkCreate($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
      productVariantsBulkCreate(productId: $productId, strategy: REMOVE_STANDALONE_VARIANT, variants: $variants){
        (...)
      }
    }
    

    The input for the variants looks something like this:

    {
        barcode: db_variant.barcode,
        compareAtPrice: db_variant.compareAtPrice?.toFixed(2) || undefined,
        inventoryItem: {
          cost: db_variant.costPerItem,
          harmonizedSystemCode: db_variant.harmonizedSystemCode || undefined,
          measurement: measurement,
          requiresShipping: db_variant.physicalProduct,
          sku: db_variant.SKU,
          tracked: db_variant.trackQuantity,
        },
        inventoryPolicy: db_variant.continueSellingWhenOutOfStock
          ? "CONTINUE"
          : "DENY",
        mediaId: found_mediaId || undefined,
        optionValues: shopify_optionValues,
        price: db_variant.price.toFixed(2),
        taxable: db_variant.chargeTaxes,
      }
    

    I want to set an available quantity of 999 to each variant (in inventoryItem).

    I was previously able to set it with the REST API of Shopify without any inventory location id.

    Is this possible with GraphQL without the inventory location id, which needs the “read_locations” and “read_inventory” scopes?

    Binary Search Tree javascript Array – Data Structures

    I am trying to build a binary tree with a array. I want to take the array, find the root and split right and left side, then perform the same split on each side if needed until two numbers are left and the lowest goes left and the highest goes right. The left side numbers will be lower than the right side numbers.

    class Node {
        constructor(value){
            this.value = value;
            this.left = null;
            this.right = null;
        }
    }
    
    class BinarySearchTree{
        constructor(nums){
            this.nums = nums
            this.root = null
        }
    
        buildtree(nums) {
    
            if (nums.length <= 0) { return null} 
    
            let root = this.root
            //console.log(root)  null
            let mid = Math.floor(nums.length / 2)
            //console.log(nums[mid])3-just mid and 4-mid nums
    
            root = new Node(nums[mid])
            //console.log(root)
    
            let lSide = nums.slice(0, mid)
            console.log(lSide, "left side, unused")
    
            let rSide = nums.slice(mid  + 1, nums.length)
            console.log(rSide, "right side unused")
            
            console.log(lSide.length, rSide.length)
             //while there is something in the queue of each mini array
    
            //total length of array to use as a counter
            let totalLength = lSide.length + rSide.length
            console.log(totalLength)
    
            let i = 0;
    
    
            while(totalLength >= i){
                i++ //console.log(i) I got 7 loops through
    
                //if left side greater 3 and not = null
                if (lSide.length >= 3 && lSide.length != null){
                    //Get the middle of the left side
    
                    let lMid = Math.ceil(lSide.length / 2)
                    //console.log(lMid)
                    
    
                    let parent = new Node(lMid)
                    root.left = parent //everything DIES HERE
                    //buildtree(lSide)
    
                    //I would like to return the function after the while 
                    //loop until the queue is empty but I am having no luc
                    //doing so
                    
                }  if (lSide <= 3 && lSide != null){
                   
                    if(lSide[0] < lSide[1]){
                        let child = new Node(lSide[0])
                        parent.left = child
                    } else if (lSide[0] > lSide[1]){
                        let child = new Node(lSide[1])
                        parent.right = child
                    } else if (rSide.length >= 3 && rSide.length != null){
                        //Get the middle of the left side
                        
                        let rMid = Math.ceil(rSide.length / 2)
                        console.log(rMid)
        
                        let parent = new Node(rMid)
                        root.left = parent
                    }
    
                      else if (rSide <= 3 && rSide != null){
                        if(rSide[0] < rSide[1]){
                            let child = new Node(rSide[0])
                            parent.left = child
                        } else if (rSide[0] > rSide[1]){
                            let child = new Node(rSide[1])
                        }
                    }
                }
            }//while
            return root
            
        }//funct
    } //class
    
    
    
    const nums = [1, 2, 3, 4, 5, 6, 7]
    const bst = new BinarySearchTree(nums)
    //console.log(root.nums)
    console.log(bst.buildtree(nums))
    

    Html code below

    <!DOCTYPE html>
    <html lang="en-US">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <script type="module" src="myscript.js"></script>
        
        <title>Test</title>
      </head>
    
      <body>
        
        
      </body>
    
    </html>
    

    I have tried a bunch of different ways to do this and this is the best logic so far. I wrote the code out like I was talking to myself.

    The problem is in the comments, if get to the first node, send it root.left and while loops does nothing else for me. I know the while loop is still going until variable-i hits the length because I consoled logged it. Can anyone help me move more forward with this.

    My main question is how do I get the current code to flow without logging the first node to the left and dying out.

    how to display a png image obtained as a blob object from an api in Angular 18

    I need to display an png image obtained as a blob object from an api in Angular 18

    From an angular application I am obtaining a png image as a blob object, when I execute the subscribe the object has the and print the object, it has the correct size of the image:

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    However, the image does not display in the view. Devtools throws this error:

    enter image description here

    Several searches on the web claim that this is enough, but it does not work. What am I missing?

    Issue with countires not working for dynamic images [closed]

    I have the following issue i use the following code to show images

    <img id="city-image" src="./assets/images/travel-list/${flight.cityTo}.jpg" alt="${flight.cityTo} Tourist Picture">

    The issue I have is countires like

    Zürich & Málaga can not display images because of the ü and á

    Whats best way to fix this issue?

    Tried some javascript but all images ended up breaking.

    React Native (Expo AV) iOS: Error Code -1002 “NSURLErrorDomain” when trying to play local video from the gallery

    Bonjour,

    Je développe une application React Native en utilisant Expo pour gérer des vidéos locales, et je rencontre un problème sur iOS. J’essaie de lire une vidéo depuis la galerie de l’utilisateur à l’aide du module expo-av. Tout fonctionne bien sur Android, mais sur iOS, j’obtiens l’erreur suivante lorsque j’essaie de lire une vidéo sélectionnée :

    Erreur de lecture de la vidéo: The AVPlayerItem instance has failed with the error code -1002 and domain "NSURLErrorDomain".
    

    Le format de l’URI de la vidéo sur iOS :

    "ph://459071C9-B963-4E65-909E-75C90D79E80A/L0/001"

    Le format de l’URI sur Android (qui fonctionne bien) :
    “file://…”

    Question :
    Pourquoi est-ce que j’obtiens cette erreur uniquement sur iOS, et comment puis-je résoudre ce problème ? Y a-t-il une manière spécifique de lire les vidéos locales depuis la galerie sur iOS (en particulier celles avec des URI au format ph://…) ?

    Merci pour toute aide ou suggestion !