What am I missing with these functions?

I am having troubles with the validating of functions. I need to validate my variables and make sure that you can not enter through with out giving a name or number. What am I doing wrong that this is not working?

<script>
    var candyName = false;
    var pricePerLb;
    var numOfLbs;
    var message;
    
    candyName = prompt("Enter the name of the candy: ");
    while(candyName == false){
        alert("Blank is invalid. Enter valid name: ");
        candyName = prompt("Enter the name of the candy: ");
    }

    pricePerLb = parseFloat(prompt("Enter the price per pound: "));
    

    numOfLbs = parseInt(prompt("Enter the average number of pounds sold in a month: "));
    

    if(numOfLbs > 2000 || pricePerLb > 10){
        message = candyName + " that costs $" + pricePerLb + " is sold, on average, " + 
numOfLbs + " lbs a month are a best-selling item.";
    }else{
        message = candyName + " are not a best-selling item.";
    }

    function validate(candyName){
    if(candyName != ""){
        valid = true;
    }else{
        valid = false;
        alert("Blank is invalid: ");
    }
    return valid;


    alert(message);

</script>

How to read each and every time a string is matched within a string

I have a very simple question. Lets say you have this string a and a string called b that is inside of a:

var b="anotherthing";
var a="something"+b+"nsomething"+b;

How to find each line that contains b? Is it something like this:

var b="anotherthing";
var a="something"+b+"nsomething"+b;
for(var i=a.search(b)-1 ; i<a.lastIndexOf(b,a.length) ; i=a.indexOf(b,i+1)){
     ///do something with `i`
}

How does one go for doing something like this as the code shown above DOES NOT work?

double click on any cell will be removed

I want to add this function inside the nested loop inside the function
function :

$("td").dblclick(function(){
             $(this).html(text(" "));
         });

loop :

for(var i = 0; i <nr ;i++)
   {
       table_body += '<tr>';
        for(var j = 0; j < nc; j++)
        {
                table_body += '<td class = "cell" ondrop="drop(event)" ondragover="allowDrop(event)">';
                table_body += '&nbsp&nbsp&nbsp';
                table_body += '</td>';
        }
        table_body += '</tr>';
   }

the reason : when i double click on any cell in the table the content will be removed

how to reset input fild without empty string in react.js

How can I reset the input field if I use it this way?

const [email, setEmail] = useState({ email: "", emailError: "" });
   
    const handleEmail = (inputEmail) => {
    if (/^[^s@]+@[^s@]+.[^s@]+$/.test(inputEmail)) {
      setEmail({ email: inputEmail, emailError: "" });
    } else {
      setEmail({ email: "", emailError: "Invalid Email" });
    }
  };

   <Form.Control type="email"  onChange={(e) => handleEmail(e.target.value)} name="email" 
    placeholder="Enter email" />

Common functions are not executed in Nuxt.js store

Assumption

I wanted to use inject in Nuxt.js to share the same process, and I wanted to use it in Vuex, so I tried to use it in store, but it would not run. How can I use it?

What we want to achieve

I want to execute common functions in store.

Code

store

this.$axios.$post(`${url.POST_API}poss`, {
      post: {
・
・
・
・
      .catch(() => {
        // commit('alertSwitchError', true)
        // setTimeout(() => {
        //   commit('alertSwitchError', false)
        // }, 3000)
        this.$errorHandling
      })
  }

plugin/responsePocessing

const errorHandling = ({ store }) => {
  store.commit('alertSwitchError', true)
  setTimeout(() => {
    store.commit('alertSwitchError', false)
  }, 3000)
}

export default ({ app }, inject) => {
  inject('errorHandling', errorHandling)
}

nuxt.config.js

・
・
・
  plugins: [
・
・
    'plugins/responsePocessing'
  ],

・
・
・

Error

No error.

React Firebase upload images for each post

In Storage need to create a folder for each post and then display all the photos from the folder in posts

Can you suggest the best way to do this? And also when the post is deleted, it is necessary to delete the folder with the photo too

Maybe you have some examples

const [posts, setPosts] = useState([]);
const [image , setImage] = useState("");
const [url , setUrl] = useState("");
const storage = getStorage();

//upload function
      const upload = ()=>{
        const storageRef = ref(storage, `images/${posts.id}/${image.name}`);

        if(image == null) return;
        uploadBytes(storageRef, image).then(() =>{
          getDownloadURL(storageRef).then((url) => {
            setUrl(url);
          })
        })
      }


 <input name='images' type="file" className="light" onChange={(e)=>{setImage(e.target.files[0])}}/>

How to run a custom element’s constructor after it has all of its required attributes?

I’m trying to create a custom element “color-box” that will need an attribute named “color” to identify the box’s color.
So for example, <color-box color="green"></color-box> will give a 100 pixels wide and 100 pixels tall square, with the background-color green.
I don’t have any problems when defining the element directly with HTML by doing <color-box color="red"></color-box>, everything goes fine, but in my case, I need to create this element with only javascript, like this:

let colorBoxElement = document.createElement("color-box");
colorBoxElement.setAttribute("color", "red");
document.body.appendChild(colorBoxElement)

What happens is that the constructor is getting ran before colorBoxElement.setAttribute("color", "red") and that’s not what I want, because I’m using that attribute in my constructor. I want the constructor to run when all of it’s required attributes are there (in this case, only 1: color) or when it’s actually appended to the document body using document.body.appendChild(colorBoxElement)

Is there any possible way of doing this, or at least doing something similar to what I need? Here’s my code:

// Defining the custom element
class ColorBox extends HTMLElement {
  constructor() {
    super()
    let shadow = this.attachShadow({mode: "open"})
    let container = document.createElement("div")
    container.style.width = "100px"
    container.style.height = "100px"
    switch(this.getAttribute("color")) {
      case "red":
        container.style.backgroundColor = "red"
        break;
      case "green":
        container.style.backgroundColor = "green"
        break;
      default:
        throw new Error("Color attribute not valid: " + this.getAttribute("color"))
    }
    shadow.appendChild(container)
  }
}
customElements.define("color-box", ColorBox)

// Creating the custom element
let colorBoxElement = document.createElement("color-box")
// This will get executed after the constructor was ran (problem)
colorBoxElement.setAttribute("color", "green")
// Appending the element to body
document.body.appendChild(colorBoxElement)
<body>
  <color-box color="red"></color-box>
</body>

How to sort sum up all values from object arrays inside react props

I would like to sort three top rated posts. The current function of displaying three post titles and their rating, but I can not sort them by best rating. Please help.

   {posts.slice(0, 3).map((p)=> (
                    <p className='bestTitle'>{p.title} {p.ratings && 
                         ((p.ratings.reduce(function(prev, current) 
                            {return prev + current.rating}, 0)/(20 * p.ratings.length)).toFixed(2)) }</p>
                ))}

The posts will look like this:

{
    posts: 
        {
            title: "abc",
            ratings:
                   username: "abc",
                   rating: 60
        }
}

Angular: access variable which is declared inside subscribe function

I’m trying to access a variable inside a subscribe function but it returns to me undefined, please any suggestions:

I have declared releveBancaireId:number; in a global scope

displayTaskByIdDetails(){
  this._inboxServcie.getTask(this.task.id).subscribe(
       (data) => {
          this.task = data;
          this.releveBancaireId = data.releveBancaireId;  // this is the variable I want to access
      }
  );
}

displayReleveBancaireById(){

  this._relebeBancaireService.getReleveBancaireById(this.releveBancaireId).subscribe( // this is where I want to access that variable as a parameter
      (data) => {
          this.releveBancaire = data;
          console.log(data);
      }
  );
}

Issue with looping through elements in an inner array

I’m having an issue looping through a set of css classes when an iteration of an outer loop is being executed.

What I’m trying to do is to append all the paragraphs under the current heading on to the new text that is being created, however, it only appears to append the first paragraph and then appends the second on to the hext heading.

What I would like is to have all content under each heading to be appended on each eg. para 1,2,3 appended under Heading 1, para 1 & 2 appended under Heading 2 etc.

Any help would be very much appreciated.

Code is below and the script tag that’s required is being created and the script runs without errors, I just need help on getting the correct paragraphs under heading to be joined correctly under each of the headings to form the correct text in the newly created script tag:

            <!DOCTYPE html>
            <html>
            <head>
            <title>Test Append</title>
            <style>
                .accordian-type{margin-bottom: 5px;padding: 10px;background: pink; color:#fff;}
                .accordion.active, p.accordion:hover {background: pink; color:#fff;}
                .accordion:after{color:#fff;}

                @media all and (max-width: 40em) { 
                    .list-test{width:90%;}
                }
            </style>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
            </head>
            <body>
            <header>
            <p>Test header</p>
            </header>

            <section class = "row text-center list-test">
                <h2>
                    Test List
                </h2>
                <p class="accordion accordian-type">List Header 1
                </p>

                <div class="panel">
                    <p>Para 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    <p>
            Para 2 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    <p>
            Para 3 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>

                </div>

                <p class="accordion accordian-type">List Header 2</p>
                <div class="panel">

                            <p>Para 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    <p>
            Para 2 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>


                </div>

                <p class="accordion accordian-type">List Header 3</p>
                <div class="panel">
                            <p>Para 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    <p>
            Para 2 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    <p>
            Para 3 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    
                    <p>
            Para 4 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>

                </div>

                <p class="accordion accordian-type">List Header 4</p>
                <div class="panel">

                    <p>Para 1 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    <p>
            Para 2 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    <p>
            Para 3 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    Para 4 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>
                    <p>
            Para 5 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                    </p>

                </div>

            </section>

            <script>
                var acc = document.getElementsByClassName("accordion");
                var i;

                for (i = 0; i < acc.length; i++) {
                    acc[i].onclick = function(){
                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.display === "block") {
                            panel.style.display = "none";
                        } else {
                            panel.style.display = "block";
                        }
                    }
                }

                var els = document.querySelectorAll(".panel");
                for (var x = 0; x < els.length; x++)
                {
                    if (window.matchMedia("(min-width: 481px)").matches) {
                        els[x].style.display = 'block';
                    }
                }

            </script>
            <script>
            //Question headers & Paragraph Answers

            var scriptTag = document.createElement("script");

            scriptTag.setAttribute("type", "application/ld+json");

            var start = '{"@context": "https://schema.org","@type": "TestPage","mainEntity": [';
            var end = ']}';
            var headings = document.querySelectorAll(".list-test .accordion");
            var paragraphs = document.querySelectorAll(".panel > p");
            var headElement = document.querySelector("header");

            scriptTag.prepend(start);

            for(var i = 0, j = 0; i < headings.length && j < paragraphs.length; i++, j++)
            { 
             scriptTag.append('{"@type": "Question", "name": "' + headings[i].innerHTML + ' ", '); 
             scriptTag.append('"acceptedAnswer": {"@type": "Answer","text": "' + paragraphs[j].innerHTML.trim() + ' "}}, ');
            }

            scriptTag.append(end);

            headElement.append(scriptTag);
            </script>
            </body>
            </html>

Refactor React Javascript Project into React Typescript

I have some .js files and need to refactor them into .ts files (with react).
I have refactored the file reportWebVitals.js into reportWebVitals.ts from this

  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals; 

into this:

const reportWebVitals = (onPerfEntry: any) => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};
 
export default reportWebVitals;

and get the following error within index.js: An argument for ‘onPerfEntry’ was not provided
My index.js file looks like this:

import React from 'react';
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

and my App.js file looks like this:

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Camera from './camera/Camera';

function App() {
  return (
    <Routes>
      <Route path='/' element={<Camera />}></Route>
    </Routes>
  );
}

export default App;

I think, I have successfully refactored the other files, but I am not able to refactor the routing components.
Thank you in advance.

Javascript object not adding new key value pair

Javascript object not adding new key value pair of sample and namespace. Empty object is return

const { lruCaches } = state
console.log('here123456')
lruCaches[namespace] = new LruCache({ maxSize: 500 })
lruCaches.sample = 89
console.log({ lruCaches }, '12345')

Output

here123456

{lruCaches: {…}}
lruCaches:
asMutable: ƒ asMutableObject(opts)
getIn: ƒ getIn(path, defaultValue)
merge: ƒ merge(other, config)
replace: ƒ objectReplace(value, config)
set: ƒ objectSet(property, value, config)
setIn: ƒ objectSetIn(path, value, config)
setPrototypeOf: ƒ ()
update: ƒ update(property, updater)
updateIn: ƒ updateIn(path, updater)
without: ƒ without(remove)
__immutable_invariants_hold: true
[[Prototype]]: Object
[[Prototype]]: Object

Spring Boot non-required requestParams default to null instead of empty string

I’m using Spring Boot for a search tool and I’m having an issue while passing the values from the front-end to the back-end.
So, I have a select field that I’m using for this search tool, it’s used for a search. It has 3 values (PRIVATE,PUBLIC, and ALL). PRIVATE option has the value PRIVATE, PUBLIC option has the value PUBLIC and ALL has the value empty string '' .
When I try to pass in the search api with the empty string, the backend doesn’t get the empty string but he intercepts it as null for some reason.
Here is my code for the front-end HTML / Vue.js

      <div class="col-sm-4 col-12">
    <label for="statut" class="form-label">Statut</label>
    <select name="statut" class="form-select" id="statut" v-model="selectedVisibility">
      <option value="PRIVATE">PRIVATE</option>
      <option value="PUBLIC">PUBLIC</option>
      <option value="">ALL</option>
    </select>
  </div>

Here is my JS:

      async searchBy(){
{
fetch(`http://localhost:100/api/v1/questions/search?statut=${this.selectedVisibility}`, 
   {headers : authHeader()})
  .then(response => response.json())
  .then(data =>
 {  console.log(data);
   this.questions = data })

}
  },

When I pass the ALL value which is an empty String '', Spring Boot defaults it to null instead of keeping that value. I could probably add a conditional inside ( if value is null ) value = ''; but that would take too much time since I have many search tools, so, is there another way to make it take the value of the empty string instead of null?
Here is the backend code :

     @GetMapping("/questions/search")
    @CrossOrigin(origins = "http://localhost:8081")
    public ResponseEntity<List<Question>> getQuestionByAtLeastOne
           (
            @RequestParam(value="statut",required=false) EStatus statut)
            throws ResourceNotFoundException
    {
        List<Question> question= questionRepository.findByAtLeastOne(statut);
        return ResponseEntity.ok().body(question);
    }

The findByAtLeastOne is just a method that does the search but before even getting to that part the value has already been turned to null

ajax update the status so i can see the status of instered data

I have a working a ajax call thats get data form a file and load in to database.

$.ajax({
            xhr: function() {
                // Download progress
                xhr.addEventListener("progress", function(evt){
                    if (evt.lengthComputable) {
                        var percentComplete = (evt.loaded / evt.total)*100;
                        $("#LoadStatus").html("Procent: "+percentComplete+" av "+evt.total+"%");
                    }
                }, false);

                return xhr;
            },
            type: 'POST',
            url: purl,
            data: formdata,
            success: function(data){
                // Do something success-ish
                $("#LoadStatus").html("ALL Availibe data is now in DB");
            }
        });

the function that i call with the API updates a counter of how many rows that have been insterted.
YOu have anyideas how i can do this the best way?

SVG Rectangle renders with size 0x0 using d3

I am new to d3 and I want to make a scatterplot where the name of a node is displayed when the user hovers over a point in the scatterplot using d3. I managed to draw the circles representing the datapoints as well as the text describing the datapoints correctly, however, I also want to add a rectangle as background for the text. The rectagnel looks fine when I inspect it in the browser, but gets rendered with size 0x0 in the upper left corner. I am just playing around, so this whole thing looks a bit rough, but I am currently only concerned with whats going on with the rectangle:

My code looks like this:

<div class="container" style="border: solid; border-color: red;">
    <svg id="svg_chart" width="500" height="500"></svg>
</div>
<script>
let data = {{ data | safe }}; //getting data from server
let bounds =  {{ bounds | safe }}; //getting x/y bounds from server

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

let scatterPlotX = 500;
let scatterPlotY = 500;

const xScale = d3.scaleLinear().domain([bounds['x'][0], bounds['x'][1]]).range([0, scatterPlotX]);
const yScale = d3.scaleLinear().domain([bounds['y'][0], bounds['y'][1]]).range([0, scatterPlotY]);



const svg = d3.select("#svg_chart");

svg.append("g")
    .call(d3.axisLeft(yScale));
svg.append("g")
    .call(d3.axisBottom(xScale));


const group = svg.selectAll("g.dot")
    .data(data)
    .enter()
    .append("g")

    group.append("text")
      .text(function(d){ return d[2];})
        .attr("x", function (d) { return xScale(d[0]) + 5; })
        .attr("y", function (d) { return yScale(d[1]); })
        .attr('opacity', '1')
        .style('pointer-events', 'none');

    group.append("rectangle")
      .attr("x", function (d) { return xScale(d[0]) + 5; })
      .attr("y", function (d) { return yScale(d[1]); })
      .attr("width", function (d) { return d3.select(this.parentNode).select("text").node().getBBox().width; })
      .attr("height", function (d) {  return d3.select(this.parentNode).select("text").node().getBBox().height; })
      .attr('opacity', '1')
      .style("fill", "yellow");

    group.append("circle")
      .attr("cx", function (d) { return xScale(d[0]); } )
      .attr("cy", function (d) { return yScale(d[1]); } )
      .attr("r", 5)
      .style("fill", d => getRandomColor())
      .style("stroke", "black")
      .on('mouseover', function (d, i) {
        d3.select(this).transition()
          .attr('opacity', '.65');
      })
      .on('mouseout', function (d, i) {
        d3.select(this).transition()
          .attr('opacity', '1');
      })
      .on('mouseover', function (d, i) {
        d3.select(this.parentNode).select("text").transition().duration(50)
          .attr('opacity', '1');
        d3.select(this.parentNode).select("rectangle").transition().duration(50)
          .attr('opacity', '1');
      })
      .on('mouseout', function (d, i) {
        d3.select(this.parentNode).select("text").transition().duration(50)
          .attr('opacity', '0');
        d3.select(this.parentNode).select("rectangle").transition().duration(50)
          .attr('opacity', '0');
      })


</script>

Here is a screenshot of what is being rendered in the browser. As you can see, the rectangle element looks fine when inspected, very similar to the circle or text element, however, unlike the other two, it gets rendered in the upper left corner with size 0x0.

enter image description here

What am I doing wrong here?