Image not appearing after passing it as a function to a template literal [closed]

I created a function that contains a template literal for an image inside the figure element. The problem is when I call that function inside a template literal of the article element, it doesn’t load the image. Here’s the code:

const newImage = (vapeimg) => {
  const figure = document.createElement("figure");
  figure.classList.add("vape_image");
  figure.innerHTML = `
  <figure>
  <img src=${vapeimg.image} alt="" />
  <figcaption> Caliburn Uwell A1 </figcaption>
`;
  return figure;
};

/* create a constant function expression for printing vape contents
using arrow function */
const newVape = (currentVape) => {
  //creates a new element for article
  const newArticle = document.createElement("article");
  //add classes and attributes to article element
  newArticle.classList.add("vape");
  newArticle.setAttribute("id", "pod");
  //add HTML contents to the article element
  newArticle.innerHTML = `
  ${newImage(currentVape)}`;
  return newArticle;
};

my try to use python in html and got this error

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    
     <py-env>
 
    </py-env>
  </head>
  <body> <py-script> 
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer('all-MiniLM-L6-v2')

# Two lists of sentences
sentences1 = ['The cat sits outside',
             'A man is playing guitar',
             'The new movie is awesome']

sentences2 = ['The dog plays in the garden',
              'A woman watches TV',
              'The new movie is so great']

#Compute embedding for both lists
model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
embeddings2 = model.encode(sentences2, convert_to_tensor=True)

#Compute cosine-similarities
cosine_scores = util.cos_sim(embeddings1, embeddings2)

#Output the pairs with their score
for i in range(len(sentences1)):
    print("{} tt {} tt Score: {:.4f}".format(sentences1[i], sentences2[i], cosine_scores[i][i]))
    print ("___________________________________________________")

  </py-script> </body>
</html>

i got this error

JsException(PythonError: Traceback (most recent call last): File “/lib/python3.10/site-packages/_pyodide/_base.py”, line 429, in eval_code .run(globals, locals) File “/lib/python3.10/site-packages/_pyodide/_base.py”, line 300, in run coroutine = eval(self.code, globals, locals) File “”, line 1, in ModuleNotFoundError: No module named ‘sentence_transformers’ )

Add a responsive three-panel slider to hugo

I’m trying to add a slider to my Hugo website that shows three images in a row, and slides to the next set of three images once a button is pressed. If the screen size is small, the slider responds by showing one image at a time.

I was able to make a single-panel slider work in Hugo by adopting tbiering’s hugo slider shortcode. I was not able to modify it to include three images because I’m not familiar with jquery. Instead, I replaced the content of tbeiring’s gallery-slider.html page with this code. I choose this because it uses a flexbox, which makes me think it is more likely to be responsive, and because it is written in javascript, which I have some familiarity with.

The code makes a functional slider, but only shows the alt text. Here’s how I have tried to add the image:

<div class="slider-item" data-position="1"><img src="NS1.jpg" alt="Bird on a tree"></div>

I cannot figure out which folder should hold the image file. I have tried:

  • in content/static (where images usually live in Hugo);
  • in the same folder as the page that references the shortcode;
  • in the same folder as the one containing the shortcode.
  • in any folder, with the absolute path referenced.
  • as a background-image as part of the css ie. background-image:url('file:////path/to/image/NS1.jpg');

To be clear, the path to the image file is correct; it shows up when I plug it into the file browser.

Your help is much appreciated.

How to use styled-components to edit text in components

I’m using styled components for my ReactJS project. I have some h1 tags but want to modify only parts of the text to be different colors. For example, from the text “Discover new subscriptions for whatever you’d like.” I’m trying to make “Discover” a different color.

This is what I tried so far:

I created a new function in the styled-components folder called (if the h1 tag is called InfoH3)

export const InfoH3Pink = styled(InfoH3)color: #FA8072;

and put it in the components file around the text tags:

<InfoH3> <InfoH3Pink>Discover</InfoH3Pink> new subscription for whatever you'd like </InfoH3>

before surrounding it with the new styled component tag

after using the new styled components tags

This does work but it creates a new line. The “Discover” becomes a separate line from the rest of the text. However, I want them to be in the same line like normal text except for the color being different.

Any ideas?

allow native scroll in container during touchmove event like with drag and drop

Is there a way to allow native scrolling easily without heavy JS modifications when you reach the border of a div via custom drag and drop via touchmove listener?
When you drag the text in the div here you’ll see the div inside is scrolling automatically
enter image description here

I provided an example with touchmove listeners but this one does not scroll, when you reach a border with your mouse
enter image description here

Is there an easy way to include a scrolling behavior to the 2nd example?

const element = document.body.querySelector('#draggable');

const isInContainer = (x,y) => {
    const elements = document.elementsFromPoint(x, y)
    return elements.find(el => el && el.classList && el.classList.contains('container')) || false;
}

const onMouseMove = (e) => {
    if(isInContainer(e.pageX, e.pageY)){
        element.style.top = e.pageY + 'px';
        element.style.left = e.pageX + 'px';
    }
}

const onMouseUp = () => {
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp)
}

element.addEventListener('mousedown', (e) => {
    e.preventDefault();
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp)
});

element.appendChild(document.createTextNode(innNa)) will not overwrite with new data

I am working on TTRPG assets to use in my own games. The intended functionality is to take form selections that will be fed into several randomized tables and produce relevant outputs.

Inn generator form: https://output.jsbin.com/pilobob/1/quiet

Currently the Generate Output button correctly appends relevant output below the form when ran on a fresh page, however, further Generate Output events do not overwrite the old data.

            <input type="button" id="submit" onclick="randGen(selection.value);" name="GenerateOutput" value="Generate Output"> 
        </form>
        <div class="genSection" id="genSection">
            <div id="randQua">
                <div id="selection">
            </div>
            <div id="randNam">
                <div id="selection">
            </div>
function randGen(){
    randQua();
    randNam();
}

function randNam(selection){
    var selection = document.getElementById('quality');
    let br="";
    let element=document.createElement("div");
    element.setAttribute("id","selection");
    for(i=0;
    i<1;
    i++){if(selection.value==1){rnd=Math.floor(Math.random()*innNa1.length);
    innNa=innNa1[rnd];
    }else{rnd=Math.floor(Math.random()*innNa2.length);
        innNa=innNa2[rnd];
        }
    br=document.createElement('br');
    element.appendChild(document.createTextNode(innNa));
    element.appendChild(br);
    }
    if(document.getElementById("selection")){document.getElementById("randNam").removeChild(document.getElementById("selection"));
    }
    document.getElementById("randNam").appendChild(element);
    }
    
    
function randQua(selection){
    var selection = document.getElementById('quality');
    let br="";
    let element=document.createElement("div");
    element.setAttribute("id","selection");
    for(i=0;
    i<1;
    i++){if(selection.value==1){rnd=Math.floor(Math.random()*innQu1.length);
    innQu=innQu1[rnd];
    }else{rnd=Math.floor(Math.random()*innQu2.length);
        innQu=innQu2[rnd];
        }
    br=document.createElement('br');
    element.appendChild(document.createTextNode(innQu));
    element.appendChild(br);
    }
    if(document.getElementById("selection")){document.getElementById("randQua").removeChild(document.getElementById("selection"));
    }
    document.getElementById("randQua").appendChild(element);
    }

I need the button to recalculate and append the randGen function (and all contained rnd variables) on click.

JS bin: https://jsbin.com/pilobob/1/edit?html,js

It’s not central to my concerns, however if there is a way to make the appended values append in chronological order instead of inverse chronological order, I would like to be made aware.

Filter data by multiple Query Params when object values have different types

I’ve been trying for days to get this thing to work, and I feel like I have the pieces but I don’t know what I am missing.

My object looks like this when it goes to my service:

GetAllDataFilterDto {
  orgId: 12345,
  status: [ 'approved', 'pending' ],
}

I am using typeorm, this is my query:

  protected getAll(filter: GetAllDataFilter): SelectQueryBuilder<EntityName> {
    const qb = Repository<EntityName>
      .createQueryBuilder('entityName')
      .select([
        'entityName.id',
        'entityName.status',
        'entityName.orgId',
      ])
      .groupBy('entityName.id')
      .where(this.getFilterConditions(filter));

    return qb;
  }

My query uses getMany() but in a different file which is why it’s not included on this function.

Here’s where I am having the issue, my current filter function looks like this:

  protected getFilterConditions(filter: GetAllDataFilter) {
    return _.pickBy(filter, (value, key) => value !== undefined && this.entityProperties.has(key));
  }

entityProperties is a set that looks like this:

Set {
'id',
'status',
'orgId'
}

Currently, this filter works for numbers and if my array only has one value, but when I add two values then it returns the error

trace: QueryFailedError: Operand should contain 1 column(s)

My end goal is to filter my returned data even if there are optional parameters, so all status columns with approved or pending will be returned, but I still need to be able to filter by orgId at the same time.

Please let me know if there is more I should include, thank you.

Adding String Inside an Array Of Array Without Duplication [duplicate]

iam trying trying to insert a string with key inside an array of multiple objects.and i need to push or add the string inside an array present in the object.So the main objective is to 1) add a string into a array which is present in the object and the object is present in a array
2)No duplication should take place when adding it too.

down below is my initial data

status:'good'
array:[{
name:Jason
type:student
attributes:[active:'yes']
      },
{
name:Markie
type:student
attributes:[active:'yes']
      }] 

and this is what iam trying to achieve

status:'good'
array:[{
name:Jason
type:student
attributes:[status:'good',active:'yes'
      },
name:Markie
type:student
attributes:[active:'yes']
      }] ```

how to make a pop up appear only once in html using javascript

i have my age verification pop up i want to appear only once when the site is visited and the pop up keeps appearing each item i refresh my browser, how do i go about it? answer will be much appreciated.

if (document.getElementById("newsletter-popup-form")) {
  setTimeout(function () {
    var mpInstance = $.magnificPopup.instance;
    if (mpInstance.isOpen) {
      mpInstance.close();
    }

    setTimeout(function () {
      $.magnificPopup.open({
        items: {
          src: "#newsletter-popup-form",
        },
        type: "inline",
        removalDelay: 350,
        callbacks: {
          open: function () {
            $("body").css("overflow-x", "visible");
            $(".sticky-header.fixed").css("padding-right", "1.7rem");
          },
          close: function () {
            $("body").css("overflow-x", "hidden");
            $(".sticky-header.fixed").css("padding-right", "0");
          },
        },
      });
    }, 500);
  }, 100);
}

Retrieve stored data in html table even after page is reloaded

I am trying to build a storage list where I select the item from (datalist) html input tag, then I put in a numeric value and calculate the overall price. After clicking on ADd To List button the item is added to the HTML table that has 5 rows which are appended accordingly. Altho, after refreshing the page, the previous data is lost and the table is returned without the inputted data. I would like the table to be displayed with all the inputs even after the page is reloaded. Also, as such that the data is visible for 3 days and after that the data is lost for the following day. Is there a way to do it using localStorage or any other method?

HTML:

<body>
    <div class="allDivs">
        <div class="calculateBox">
            <label for="product-names">Choose an Item</label>
            <input type="text" name="product-names" list="product-names" placeholder="Choose" id="products"/>
            <datalist id="product-names">
                <option value="Flour">Flour</option>
                <option value="Salt">Salt</option>
                <option value="Sugar">Sugar</option>
                <option value="Cheese">Cheese</option>
            </datalist>
            <input class="quantity" type="number" min="1">
            <button class="calculate">Calculate</button>
            <button class="addItem">Add To List</button>
            <div class="printHere"></div>
        </div>

        <div class="historyTable">
            <table class="itemTable">
                <tr>
                    <th>S.NO.</th>
                    <th>ITEM NAME</th>
                    <th>QUANTITY</th>
                    <th>ITEM PRICE</th>
                    <th>TOTAL PRICE</th>
                </tr>
                <tr>
                    <td>1</td>
                    <td>Some item name</td>
                    <td>2</td>
                    <td>45.43</td>
                    <td>90.86</td>
                </tr>
            </table>
        </div>
    </div>
    <script src="./main.js"></script>
</body>

JS :

var dict = {
    'Flour': 100,
    'Salt': 20,
    'Sugar': 80,
    'Cheese': 75
};

document.querySelector('button.calculate').addEventListener('click', function () {
    var item = document.querySelector('#products').value;
    var numOfItems = document.querySelector('.quantity').value;
    var itemPrice = dict[item];
    var total = (itemPrice * numOfItems);
    document.querySelector('.printHere').innerHTML = total;
});

document.querySelector('button.addItem').addEventListener('click', function () {
    var item = document.querySelector('#products').value;
    var numOfItems = document.querySelector('.quantity').value;
    var itemPrice = dict[item];
    var total = (itemPrice * numOfItems);
    var numberOfRows = document.querySelectorAll('tr').length;
    document.querySelector('table').insertAdjacentHTML('beforeend', `
    <tr>
        <td>${numberOfRows}</td>
        <td>${item}</td>
        <td>${numOfItems}</td>
        <td>${itemPrice}</td>
        <td>${total}</td>
    </tr>
    `);
    document.querySelector('#products').value = '';
    document.querySelector('.quantity').value = '';
    // var duplicate = document.querySelector('.itemTable');
    // localStorage.setItem('allData', duplicate);
});

detached elements memory leak, summary points to internal node

I am working on performance and trying to see if my app has any memory leaks. Every time i ran my app and clear state, there are some detached nodes. When trying to see summary, its pointint to internal node, can’t find anything which points to my code.

here is screenshot of heap snapshot

enter image description here

When i ran the app again and again, the memory seems to be same but there is always detached elements. I also tried comparision between different snapshots and delta is zero.

here is screenshot of comparision

enter image description here

Can anyone tell me if there is memory leak in my app or is it fine (this is normal) ?

If this is normal, then i would like to know why there are detached nodes, and if it is not, please tell me how to fix it.

unable to set the value to the new SpeechSynthesisUtterance object

I have a function named TexttoSpeech which is called when the page is reloaded. The problem is I’m not able to set the value to msg.text using DOM. I’m able to see the text in console but not able to assign the value to msg.text . the document.getElementById("text").innerHTML is 1133 long

function TexttoSpeech() {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[7];
  msg.volume = 1; // From 0 to 1
  msg.rate = 1; // From 0.1 to 10
  msg.pitch = 2; // From 0 to 2
  msg.text =  document.getElementById("text").innerHTML
  msg.lang = "es";
  window.speechSynthesis.speak(msg);

}

if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
  TexttoSpeech();
  redirectToNextPage(); //If the page reload this function is called
}

any helpful tips with burnout when first learning CSS,JAVASCRIPT,HTML and all the things to remember with front-end, or any other language?

What are some helpful tips or veteran advice in overcoming or avoiding “learning” burnout when first trying to get into front-end developing? How can you keep it interesting and engaging when all you do for a awile is try to grasp everything? I’m currently in this stage and struggling to stay focused for more than a few hours, i’ve seen a lot of people and friends get burned out after like 2 weeks of grinding and quit.