Displaying loading screen until static Next.js app is rendered

I want to display a loading screen before the whole static page is loaded. I am using modules:export to create the static page. But I can not listen to the window load event as when NextJs executes, the window has already been loaded.

I tried using an external script using next/script, but I can’t get my head around how to listen to it from inside the next app.

If anyone has any idea on how to achieve this, please help me. Thank you.

How to find the array name where a property does not exist?

I define the session name based on the array of objects in the data, and then it renders whether it is a session or an item. When rendering a session, if the session has the property ‘nome,’ it will display ‘section.nome,’ but not all sessions have the ‘nome’ property. I would like it so that if the ‘nome’ property does not exist in the session array, the name of that array is rendered instead. For instance, the section ‘horarioIntervalo’ does not have the property ‘nome’, so I would like it to render ‘horarioIntervalo’. Is it possible?

const data = [
  {
    _id: "64e502ec6b4bfaafb4e1466c",
    nome: "ESF Centro - Médico",
    endereco: {
      rua: "Angelo Perucchi, 30 - Centro",
    },
    fone: "48 3444 6065",
    especialidades: [
      {
        _id: "64e500d16b4bfaafb4e14667",
        nome: "Clínico Geral - Consulta",
        profissionais: [
          {
            _id: "6405d8f341fb166e83f43f5d",
            nome: "Braulio Portela",
            label: "Braulio Portela",
            value: "6405d8f341fb166e83f43f5d",
            horarioIntervalo: [
              {
                dias: [1, 2, 3, 4, 5],
                intervalo: {
                  inicio: "12:00",
                  fim: "13:00",
                },
              },
              {
                dias: [5],
                intervalo: {
                  inicio: "13:00",
                  fim: "17:00",
                },
              },
              {
                dias: [1, 2, 3, 4, 5],
                intervalo: {
                  inicio: "10:00",
                  fim: "11:40",
                },
              },
              {
                dias: [1, 2, 3, 4],
                intervalo: {
                  inicio: "15:00",
                  fim: "16:40",
                },
              },
              {
                dias: [5],
                intervalo: {
                  inicio: "13:00",
                  fim: "15:00",
                },
              },
            ],
            espacoAgendamento: "00:30",
            periodoAtendimento: {
              inicio: "2023-08-22",
              fim: "2023-12-31",
            },
          },
        ],
      },
    ],
  },
];
  function renderSection(section, sectionIndex, parentIndex) {
    const combinedIndex = `${parentIndex}-${sectionIndex}`;
    return (
      <div key={combinedIndex}>
        <div
          onClick={() => toggleSection(combinedIndex)}
          style={{
            cursor: "pointer",
            padding: "10px",
            border: "1px solid #ccc",
            background: selectedSections[combinedIndex] ? (parentIndex === sectionIndex ? "yellow" : "green") : parentIndex === sectionIndex ? "red" : "blue",
          }}>
          {section.nome}
        </div>
        {selectedSections[combinedIndex] && renderItems(section, combinedIndex)}
      </div>
    );
  }

  return <div>{data.map((section, index) => renderSection(section, index, index))}</div>;

Qualtrics conjoint experiment Javascript randomization condition

I am building a conjoint experiment in Qualtrics with JavaScript about vote choice and democratic norm violations. In a typical conjoint you let all attribute levels be random. However, this is, not realistic in the case of an election since there is only one candidate from each party.

Here is the code I am using right now:

    // Set number of choices (number of elections);
    var CJ_numChoice = 3;

    // Vectors containing all attribute levels:
    var CJ_eth = ["White", "South Asian", "East Asian", "Indigenous"];
    var CJ_gender = ["Man", "Woman"];
    var CJ_age = ["35", "65"];
    var CJ_pid = ["Liberal", "Conservative", "NDP"];
    var CJ_occup = ["Lawyer", "Political Staffer", "Construction worker", "Business person"];
    var CJ_exp = ["No experience", "Mayor", "Member of provincial legislature", "Member of Parliament"];
    var CJ_wel = ["Spending on welfare should be kept the same", "Spending on welfare should be increased", "Spending on welfare should be reduced"];
    var CJ_enviro = ["Must find a balance between reducing greenhouse gas emissions and maintaining jobs in the oil and gas sector", "Must prioritize reducing greenhouse gas emissions over the jobs in the oil and gas sector", "Must prioritize jobs in the oil and gas sector over reducing greenhouse gas emissions"];
    var CJ_court = ["A prime minister should always adhere to court decisions even though they might seem politicized", "A prime minister should not be bound by court decisions he or she regards as politicized"];
    var CJ_prot = ["The prime minister should not be allowed to ban non-violent opposition protests under any circumstances", "The prime minister should be free to ban non-violent opposition protests if they are disruptive to society"];

    // Fisher - Yates shuffle:
    function shuffle(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

    // Shuffle a vector, choose the first entry:
    function shuffle_one(theArray) {
        var out = shuffle(theArray);
        return out[0];
    }

    var CJ_attribnames = ["Ethnicity", "Gender", "Age", "Party", "Previous occupation", "Prior political experience", "Position on welfare spending", "Position on environmental issues", "Position on courts", "Position on press freedom", "Position on protests rights"];

    function randomize(i) {
        // Randomly draw the attributes for each candidate
        var c1 = [shuffle_one(CJ_eth), shuffle_one(CJ_gender), shuffle_one(CJ_age), shuffle_one(CJ_pid), shuffle_one(CJ_occup), shuffle_one(CJ_exp), shuffle_one(CJ_wel), shuffle_one(CJ_enviro), shuffle_one(CJ_court), shuffle_one(CJ_prot)];
        var c2 = [shuffle_one(CJ_eth), shuffle_one(CJ_gender), shuffle_one(CJ_age), shuffle_one(CJ_pid), shuffle_one(CJ_occup), shuffle_one(CJ_exp), shuffle_one(CJ_wel), shuffle_one(CJ_enviro), shuffle_one(CJ_court), shuffle_one(CJ_prot)];

        
        
        // Save the results
        for (var k = 1; k <= CJ_attribnames.length; k++) {
            var CJ_index = k - 1;
            Qualtrics.SurveyEngine.setEmbeddedData('c' + i + '_attrib' + k + '_name', CJ_attribnames[CJ_index]);
            Qualtrics.SurveyEngine.setEmbeddedData('c' + i + '_attrib' + k + '_c1', c1[CJ_index]);
            Qualtrics.SurveyEngine.setEmbeddedData('c' + i + '_attrib' + k + '_c2', c2[CJ_index]);
        }
    }

    for (var i = 1; i <= CJ_numChoice; i++) {
        randomize(i);
    }
});

Can you help me figure out how to make sure that both candidate parties are always different in the following style: Make candidate 1’s party be random. If candidate 1 is Liberal or NDP Candidate 2 can only be Conservative. if Candidate 1 is Conservative, candidate 2 can randomly be Liberal or NDP.

I have trouble animating my element with html and js

I am trying to animate my input labels to move up after click the way it works is after clicking on input a class which contains the animation i want is assigned to the label, but it is not working.
Here’s the HTML

        <div class="login-container">
            <p class="heading">sign in to your account</p>
            <form>
                <div class="username-group group">
                    <label class="username-input-label " for="username-input">User name</label>
                    <input class="username-input" type="text">
                </div>
                <div class="password-group group">
                    <label class="password-input-label" for="password-input">password</label>
                    <input class="password-input" type="text"> 
                    <!-- <button class="show-password">show password</button>    -->
                </div>
                <div class="confirm-password-group group">
                    <label class="confirm-password-input-label" for="confirm-password-input">confirm password</label>
                    <input class="confirm-password-input"></input>    
                </div>
                <div class="email-group group">
                    <label class="email-input-label" for="email-input">email adress</label>
                    <input class="email-input"></input>    
                </div>
            </form>
            <button class="sign-up">sign up</button>
        </div>   
    <script src="script.js"></script>

CSS

*{
    margin: 0;
    padding: 0;
    font-family: urbanist;
}

body{
    height: 100vh;
    background-color: #496d8d;
    display: flex;
    justify-content: center;
    align-items: center;
}

form{
    width: 130%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 1rem;
}

input{
    border: none;
    border-bottom: 1px solid #082c4c;
    width: 100%;
    background-color: #224f3900;
    padding: 0.2rem 0 0.2rem 0;
    z-index: 99999;
    position: relative;
    color: #ddd;
    font-size: 1.5rem;
    font-weight: 100;
}

input:focus{
    outline: none;
}

.group{
    width: 60%;
}


label{
    display: inline-block;
    transform: translate(0,2.1rem);
    user-select: none;
    color: #ddd;
}

.username-focus-label-animation{
    animation: usenramefocusLabelAnimation 700ms forwards;
}

@keyframes usenramefocusLabelAnimation {
    from {transform: translate(0,2.1rem);}
    to {transform: translate(0,0.1rem);}
}
        
.username-blur-label-animation{
    animation: usenrameBlurLabelAnimation 700ms forwards;
}

@keyframes usenrameBlurLabelAnimation {
    from {transform: translate(0,0.1rem);}
    to {transform: translate(0,2.1rem);}
}


button:not(.show-password){
    background-color: #082c4c;
    scale: 1.8;
    padding: 0.3rem;
    border: none;
    border-radius: 10%;
    cursor: pointer;
    color: #ddd;
    box-shadow: 0 5px 5px 2px #082c4c70,0 2px 10px -1px #0f497b inset;
    transition: 500ms;
}

button:not(.show-password):hover{
    box-shadow: 0 0px 0px 0px #082c4c70,0 2px 10px -1px #0f497b inset;
    background-color: #07345b;

}

.heading{
    font-size: 4rem;
    color: #ddd;
    font-weight: 200;
    text-align: center;
    text-shadow: 0 5px 10px #082c4c90 , 0 15px 10px #082c4c90 ,0 25px 10px #082c4c90;
}

.login-container{
    width: 30%;
    height: 90vh;
    padding: 0.5rem;
    backdrop-filter:  blur(20px);
    background-color: #1d5582;
    border-radius: 10%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    gap: 3rem;
    box-shadow: 0 10px 50px 1px #082c4c inset
}

and JS

let $ = document
let usernameInputLabel = $.querySelector(".username-input-label")
let usernameInput = $.querySelector(".username-input")

let isFocused = false
function focusAnimation() {
    if (isFocused) {
        usernameInputLabel.classList.remove(".username-focus-label-animation")
        usernameInputLabel.classList.add(".username-blur-label-animation")
        isFocused = false 
    }
    else{
        usernameInputLabel.classList.add(".username-focus-label-animation")
        usernameInputLabel.classList.remove(".username-blur-label-animation")
        isFocused = true 
    }
}
usernameInput.addEventListener("click",focusAnimation)

The animation is written correctly and the function seems to work fine. I can’t see what is the problem

javascript cropping issue for chrome extension

I have a Chrome extension that allows the user to take a screenshot from a selected area of their screen.

The flow looks like this:

User clicks the screenshot button in the Chrome Extension popup menu. The popup sends a message to the Background script to capture the tab.
The background script screenshots the entire tab and sends the URL to the content script.
The content script allows the user to draw a rectangle on the screen and it crops out that area of the screen from the screenshot and sends it to the server.

The Issue: When the user selects the area to crop, the final result is scaled in and shifted to the left and up a bit, I was able to fix this by implementing a ratio system just like in a post by user (https://stackoverflow.com/users/8586250/ryan) I came across during one of my searches. but right now, im struggling making the system work when the page is scrolling (as that disrupts the accuracy ). I also noticed that when it comes to some webpages , even without the page scrolled , the area the user selected is off by a bit, instead of capping out the word I selected , it crops out the area a little bit above the intended area.

here is my current code:

(function() {
    let startX, startY, div;
 
    const dpr = window.devicePixelRatio || 1; // Device Pixel Ratio
    const bodyStyle = window.getComputedStyle(document.body);
    const bodyTransform = bodyStyle.transform || bodyStyle.webkitTransform || bodyStyle.mozTransform || bodyStyle.msTransform;
    const bodyScale = bodyTransform.includes('matrix') ? parseFloat(bodyTransform.split(',')[3]) : 1;

    function getCursorPosition(e) {
        return {
            x: (e.clientX + window.scrollX) * dpr * bodyScale,
            y: (e.clientY + window.scrollY) * dpr * bodyScale
        };
    }
    
 

  

    function onMouseDown(e) {
        
    
       
        let cursorPos = getCursorPosition(e);
        startX = cursorPos.x;
        startY = cursorPos.y;
    
        div = document.createElement('div');
        div.style.position = 'absolute';
        div.style.border = '2px solid black';
        div.style.left = `${startX / (dpr * bodyScale)}px`;
        div.style.top = `${startY / (dpr * bodyScale)}px`;
        div.style.zIndex = '2147483647';
        div.style.pointerEvents = 'none';
        div.style.boxSizing = 'border-box'; // Include border in the width and height calculations
        div.style.transform = `scale(${1 / bodyScale})`; // Counteract the body scaling
        div.style.transformOrigin = 'top left';
        document.body.appendChild(div);
    
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    }
    
    function onMouseMove(e) {
       
    
        let cursorPos = getCursorPosition(e);
        const width = Math.abs(cursorPos.x - startX);
        const height = Math.abs(cursorPos.y - startY);
    
        div.style.width = `${width / (dpr * bodyScale)}px`;
        div.style.height = `${height / (dpr * bodyScale)}px`;
        div.style.left = `${Math.min(cursorPos.x, startX) / (dpr * bodyScale)}px`;
        div.style.top = `${Math.min(cursorPos.y, startY) / (dpr * bodyScale)}px`;
    }
    
    function onMouseUp(e) {
       
    
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    
        let cursorPos = getCursorPosition(e);
        const bodyPaddingLeft = parseInt(bodyStyle.paddingLeft, 10);
        const bodyPaddingTop = parseInt(bodyStyle.paddingTop, 10);

        const coordinates = {
            left: (Math.min(cursorPos.x, startX) - bodyPaddingLeft) / (dpr * bodyScale),
            top: (Math.min(cursorPos.y, startY) - bodyPaddingTop) / (dpr * bodyScale),
            width: (Math.abs(cursorPos.x - startX)) / (dpr * bodyScale),
            height: (Math.abs(cursorPos.y - startY)) / (dpr * bodyScale)
        };
    
        console.log('Coordinates:', coordinates);
        chrome.runtime.sendMessage({
            action: 'captureSelectedArea',
            coordinates: coordinates
        });
    
        div.parentNode.removeChild(div);
       
    }
})();


// funtion that recieves coordinates 

function processSS(request) {
   
        const img = new Image();
        img.onload = () => {
            console.log('Loaded image size:', img.naturalWidth, img.naturalHeight);

            const ratio = img.naturalWidth / window.innerWidth;
            console.log('Screen to image ratio:', ratio);

            const scaledLeft = request.coordinates.left * ratio;
            const scaledTop = (request.coordinates.top + window.scrollY) * ratio; // Including vertical scroll offset
            const scaledWidth = request.coordinates.width * ratio;
            const scaledHeight = request.coordinates.height * ratio;

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = request.coordinates.width;
            canvas.height = request.coordinates.height;

            ctx.drawImage(img,
                scaledLeft, scaledTop,
                scaledWidth, scaledHeight,
                0, 0,
                canvas.width, canvas.height
            );

            const croppedDataUrl = canvas.toDataURL('image/png');
            console.log('Cropped image data URL:', croppedDataUrl);

          

        console.log('Image data to load:', request.imageData);
        img.src = request.imageData;
    }).
}

I got an error of Internal server and integrity error how can i solve this

I got an error when i want to fetch value from html page to ajax, and i got null.

view.py
`def placeorder(request):
if not ‘userid’ in request.session:
return redirect(‘login’)

if request.method == 'POST':
    print("hii")
    neworder = Order()
    neworder.user_id = request.session['userid']
    neworder.fname = request.POST.get('firstname')
    neworder.lname = request.POST.get('lastname')
    neworder.address = request.POST.get('address')
    neworder.city = request.POST.get('city')
    neworder.state = request.POST.get('state')
    neworder.country = request.POST.get('country')
    neworder.zipcode = request.POST.get('code')
    neworder.phone = request.POST.get('phone')
    print(neworder.fname)
    #PAYMENT MODE:
    # neworder.payment_mode = request.POST.get('payment_mode')
    neworder.payment_id = request.POST.get('payment_id')

    cart = Cart.objects.filter(user=request.session['userid'])
    cart_total_price = 0
    for item in cart:
        cart_total_price = cart_total_price + item.product.Price * item.quantity

    neworder.totalprice = cart_total_price
    neworder.save()

    neworderitems = Cart.objects.filter(user=request.session['userid'])
    for item in neworderitems:
        OrderItem.objects.create(
            order=neworder,
            product=item.product,
            price=item.product.Price,
            quantity=item.quantity 
        )

        #Decrease the quantity from order stocks:
        # orderproduct = Products.objects.


    Cart.objects.filter(user=request.session['userid']).delete()
    messages.success(request, "Your order is placed!")

return redirect("home")`

js file:
`$(document).ready(function(response){

$('.paywithrazorpay').click(function (e){
    e.preventDefault();

    var fname = $("[name='firstname']").val();
    var lname = $("[name='lastname']").val();
    var address = $("[name='address']").val();
    var city = $("[name='city']").val();
    var state = $("[name='state']").val();
    var country = $("[name='country']").val();
    var code = $("[name='code']").val();
    var phone = $("[name='phone']").val();
    var token = $("[name='csrfmiddlewaretoken']").val();
    if(fname == "" || lname == "" || address == "" || city == "" || state == "" || country == "" || code == "" || phone == ""){
        // swal("Alert!","All fields are mandatory", "error");
        alert("error")
        return false;
    }
    else{
        // console.alert(fname)
        $.ajax({
            method : "GET",
            url : "/proceed_to_pay",
            dataType : "json",
            // datatype : "datatype",
            success: function (response){
                var options = {
                    "key": "rzp_test_xftiEQRdK00lAf", // Enter the Key ID generated from the Dashboard
                    "amount": response.total_price * 100, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
                    "currency": "INR",
                    "name": "NithClothing",
                    "description": "Test Transaction",
                    "image": "https://example.com/your_logo",
                    // "order_id": "order_IluGWxBm9U8zJ8", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
                    "handler": function (responseb){
                        alert(responseb.razorpay_payment_id);
                        console.log(fname);
                        $.ajax({
                            method:"POST",
                            url: "placeorder",
                            // headers:{
                            //     "X-CSRFToken": token
                            // },
                            data:  {
                            'fname': fname,
                            'lname': lname,
                            'address':address,
                            'city': city,
                            'state': state,
                            'country': country,
                            'code': code,
                            'phone': phone,
                            'payment_id': responseb.razorpay_payment_id,
                            'csrfmiddlewaretoken': token,
                            }  ,
                            // dataType: JSON,
                            success: function (responseb) {
                                window.location.href = '/home'
                            } 
                        });
                    },
                    "prefill": {
                        "name": fname+ " "+lname,
                        // "email": "[email protected]",
                        "contact": phone
                    },
                    // "notes": {
                    //     "address": "Razorpay Corporate Office"
                    // },
                    "theme": {
                        "color": "#3399cc"
                    }
                };
                var rzp1 = new Razorpay(options);
                rzp1.open();
            }
        
        });
    }
});

});`

I want the value of form which i fill as a input to save in database after payment.

npm run build doesn’t recognize the “bootstrap” command

I recently upgraded my project to use Lerna v7, and when running the command npm run build, I encountered the following error:

enter image description here

Following the provided link, I realized that the “bootstrap” command is no longer supported by default in Lerna v7. The documentation suggests changes to the lerna.json file, but I’m still having difficulty fixing this issue.

Could someone guide me on how to adjust my project to address this specific error? I appreciate any help or insights you can provide.

Lerna Update: The project has been updated to Lerna version 7 as recommended. The error appeared after this update.

Reading the Documentation: The Lerna documentation was consulted, especially the section regarding changes in version 7. It was identified that the “bootstrap” command is no longer supported by default.

parse arrays in array structure to unordered list in js

How to parse js array in the form similar to:

const arr = [
            "&&",
            [
                "==",
                "first",
                "1-1"
            ],
            [
                "&&",
                [
                    "==",
                    "second1",
                    "2-1"
                ],
                [
                    "==",
                    "second2",
                    "2-2"
                ]
            ]
        ]

to HTML unordered (ul) list in the form:

    <li>&&
        <ul>
            <li>first == 1-1</li>
            <li>&&
                <ul>
                    <li>second1 == 2-1</li>
                    <li>second2 == 2-2</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

As you can guess, I need an UI to edit arr content. Arr represents form of ‘where’ filter definition in JSON string. So when user changes list (adding or removing nodes in unordered list)i will need to parse changes back to array, but first things first.
Maybe there is some library for that but i was unable to find it.

I tried recursion like this:

    function arrayToHTML(arr, container) {
    if (!Array.isArray(arr) || arr.length === 0) return
    const operator = arr[0]
    const conditions = arr.slice(1)
    if (operator === '&&') {
    this.arrayToHTML(conditions, container)
    }
    }

How to add an href link instead of replacing some last letters in a paragraph

I have a problem I’d like to get help with.
Here’s my HTML:

<div class="post--content">Lorem ipsum dolor sit amet,nconsectetur adipiscing.Lorem 
 vipsumdolor sit amet,nconsectetur adipiscing.Lorem ipsum dolor sit amet,nconsectetur  
 adipiscing.Lorem ipsum dolor sit amet,nconsectetur adipiscing.Lorem ipsum dolor sit  
 amet,nconsectetur adipiscing.</p>

<a href="link" target="_blank">Read more</a>

My CSS:

.post--content {
    max-width: 300px;  
    line-height: 11.6px;  
    display: -webkit-box;  
    -webkit-line-clamp: 2;  
    -webkit-box-orient: vertical;  
    overflow: hidden;  
}

I want to hide my text if its size exceeds two lines of my width. Then dynamically set my href link at the end of this second line. This href link will bring the user to the entire article. The goal of this is independently of text’s size always will put my href link in this paragraph.
https://codepen.io/DaroGawlik/pen/jOdgrbo?editors=1111

Change the style of an element with css whose style has already been modified with javascript

I have a “filter bar” that is displayed when the screen has a certain width, and it disappears when the screen is to narrow. I have implemented this in my code by using media queries and it works.

When the screen is narrow, a button shows up, to display the hidden bar. I have implemented this code in javascript, and when I click on it, the bar is displayed/hidden : it works.

Now, my problem is : when I display the hidden bar with the button (so the window is narrow), and I increase the size of the window until reaching a width for which the bar have to shows up, it doesn’t. It seems like the javascript imposes the style of the bar, so that the media queries don’t work. How to manage this ?

My code with the important elements is shown below :

function displayHideFiltrerPar() {

    let tmp = document.getElementById('container-left-small-screen');

    if (tmp.style.display == "none" || tmp.style.display == "") {
        tmp.style.display = "inline-block";
    } else {
        tmp.style.display = "none";
    }

}
@media (min-width: 576px) and (max-width: 767px) {
  
 .res-button-filtrer-par {
    display: flex;
    margin-bottom: 2em;
  }

  #container-left-small-screen {
    display: none;
    position: absolute;
    width: 50%;
    top: -130px;
  }
}

@media (min-width: 768px) and (max-width: 991px) {
  /* Size M  */
 .res-button-filtrer-par {
    display: none;
  }

  #container-left-small-screen {
    display: inline-block;
  }
}
<button class="res-button-filtrer-par res-button" type="button" onClick="displayHideFiltrerPar();">
    <span>Display filter bar</span>
</button>

<div id="container-left-small-screen">
    Filter bar
</div>

Differences between approaches while sending a file from the server

I want to know the difference between these 2 approaches while sending a file to the browser using nodejs.

  1. Reading the file in memory and sending it using res.send() method

    app.get('/send-pdf', (req, res) => {
        const filePath = path.join(__dirname, 'path_to_your_pdf.pdf');
        const fileContent = fs.readFileSync(filePath);
    
        res.setHeader('Content-Type', 'application/pdf');
        res.send(fileContent);
    });
    
  2. Using streams in nodejs

    app.get('/stream-pdf', (req, res) => {
        const filePath = path.join(__dirname, 'path_to_your_pdf.pdf');
        const fileStream = fs.createReadStream(filePath);
    
        res.setHeader('Content-Type', 'application/pdf');
        fileStream.pipe(res);
    });
    

    I know that at server it is better to use streams as I don’t have to load the entire file in memory before sending. But I want to know whether there is any difference for the client. Since it will receive the data in chunks in both cases.

What does res.sendFile() method of express.js do different than what I did in previous 2 approaches.

I searched this question but was not able to find the answer. I went to read the source code of express.js and they were using this library for the same.

How can i fetch data from mysql using axios?

I want to fetch / get data from my mysql database in my laravel project. Here i can save data and i wrote a script to show data list using axios and javascript but showing error.
Can you help to where is my error?

here is my Routes

Route::get('/blogs', [BlgoCategoryController::class, 'index'])->name('categories.index');
Route::get('/blogs/{category}', [BlgoCategoryController::class, 'show'])->name('categories.show');
Route::post('/blogs', [BlgoCategoryController::class, 'store'])->name('categories.store');
Route::put('/blogs/{category}', [BlgoCategoryController::class, 'update'])->name('categories.update');
Route::delete('/blogs/{category}', [BlgoCategoryController::class, 'destroy'])->name('categories.destroy');

I wrote these scripts in my controller file

class BlgoCategoryController extends Controller {



public function index(Request $request) {
    $perPage = $request->perPage ?? 5;
    $keyword = $request->keyword;

    $query = BlogCategory::query();

    if ($keyword) {
        $query = $query->where('category_name', 'like', '%' . $keyword . '%');
    }

    $categories = $query->orderByDesc('id')->paginate($perPage)->withQueryString();

    return view('admin.blogs.categories', compact('categories'));
}

public function show(BlogCategory $category) {
    return $category;
}
//Store News Customer
function store(Request $request){
    $validated = $request->validate([
        'category_name' => 'required|string|max:50'
    ]);

    $category = BlogCategory::create($validated);
    return response()->json($category, Response::HTTP_CREATED);
}

public function update(Request $request, BlogCategory $category) {
    $validated = $request->validate([
        'category_name' => 'required|string|max:50'
    ]);

    $category->update($validated);

    return response()->json($category);
}

public function destroy(BlogCategory $category) {
    $category->delete();

    return response()->json(null, Response::HTTP_NO_CONTENT);
} }

I want to fetch data in this view file

<div id="loader" class="LoadingOverlay d-none">
    <div class="Line-Progress">
        <div class="indeterminate"></div>
    </div>
</div>
<div class="card shadow">
    <div class="card-header">
        <div class="row">
            <div class="col-md-6 col-sm-12">
                <h5>{{__('Blog Categories')}}</h5>
            </div>
            <div class="col-md-6 col-sm-12 text-right">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#categoryModal">
                    {{__('Add Category')}}
                </button>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-2 px-2">
                <div class="form-group">
                    <label>Per Page</label>
                    <select id="perPage" class="form-control form-select-sm form-select">
                        <option>5</option>
                        <option>10</option>
                        <option>15</option>
                    </select>
                </div>
            </div>

            <div class="col-md-2 px-2">
                <div class="form-group">
                    <label>Search</label>
                    <div class="input-group">
                        <input value="" type="text" id="keyword" class="form-control">
                        <button class="form-control btn btn-success" type="button" id="searchButton">Search</button>
                    </div>
                </div>
            </div>
        </div>

        
        <div class="row">

            <div class="col-md-12 p-2 col-sm-12 col-lg-12">
                <div class="table-responsive bg-white rounded-3 p-2">
                    <table class="table table-bordered" id="tableData">
                        <thead>
                            <tr class="bg-light">
                                <th>{{__('Category ID')}}</th>
                                <th>{{__('Category Name')}}</th>
                                <th>{{__('Category Slug')}}</th>
                                <th>{{__('Action')}}</th>
                            </tr>
                        </thead>
                        <tbody id="tableList">
                        
                        </tbody>
                    </table>
                </div>
            </div>


            <div class="col-md-2 p-2">
                <div class="">
                    <button onclick="handlePrevious()" id="previousButton" class="btn btn-sm btn-success">{{__('Previous')}}</button>
                    <button onclick="handleNext()" id="nextButton" class="btn btn-sm mx-1 btn-success">{{__('Next')}}</button>
                </div>
            </div>

        </div>


    </div>
</div>

And here is my Javascript

let currentPage = 1

// Function to fetch and display the list of customers
async function getList() {
    const perPage = document.getElementById("perPage").value
    const keyword = document.getElementById("keyword").value

    try {
        function showLoader() {
            document.getElementById('loader').classList.remove('d-none')
        }
        const response = await axios.get(
            `/blogs?page=${currentPage}&perPage=${perPage}&keyword=${keyword}`)
            console.log(response);
        updateTable(response.data)
    } catch (error) {
        console.error('Error fetching customer data:', error);
    } finally {
        function hideLoader() {
            document.getElementById('loader').classList.add('d-none')
        }
    }
}

// Function to update the table with customer data
function updateTable(data) {
const tableList = document.getElementById("tableList");

    // Check if there are no categories to display
    if (!data.data.length) {
        tableList.innerHTML = '<tr><td colspan="4" class="text-center">No categories found.</td></tr>';
        return;
    }

    // Build the rows HTML string
    const rowsHtml = data.data.map(category => {
        return `<tr>
                    <td>${category.id}</td>
                    <td>${category.category_name}</td>
                    <td>${category.category_slug}</td>
                    <td>
                        <button data-id="${category.id}" class="btn editBtn btn-sm btn-outline-success">Edit</button>
                        <button data-id="${category.id}" class="btn deleteBtn btn-sm btn-outline-danger">Delete</button>
                    </td>
                </tr>`;
    }).join('');

    // Update the table with the new rows
    tableList.innerHTML = rowsHtml;
}


// Event listeners for pagination and search
document.getElementById('perPage').addEventListener('change', () => {
    currentPage = 1
    getList()
})


document.getElementById('searchButton').addEventListener('click', () => {
    currentPage = 1
    getList()
})

// Functions for handling pagination buttons
function handlePrevious() {
    if (currentPage > 1) {
        currentPage--
        getList()
    }
}

function handleNext() {
    currentPage++
    getList()
}

// Function to delete a customer
async function deleteCategory(id) {
    let isConfirmed = confirm("Are you sure you want to delete this category?")
    if (isConfirmed) {
        try {
            function showLoader() {
            document.getElementById('loader').classList.remove('d-none')
        }
            await axios.delete(`/blogs/${id}`)
            getList()
        } catch (error) {
            console.error('Error deleting category:', error)
        } finally {
            function hideLoader() {
            document.getElementById('loader').classList.add('d-none')
        }
        }
    }
}

// Attach event listeners to dynamically created buttons
document.getElementById('tableList').addEventListener('click', function(event) {
    const target = event.target

    if (target.classList.contains('deleteBtn')) {
        const categoryId = target.getAttribute('data-id')
        deleteCategory(categoryId)
    }

    if (target.classList.contains('editBtn')) {
        const categoryId = target.getAttribute('data-id')
        fillUpUpdateForm(categoryId)
    }
})

// Initial list fetch
getList()

Please help me to show the data list.

Toggle Button With Props & emit

this is my first time using props and I can’t figure out what’s the problem

I want to make a component of the toggle button and then use it anywhere with an entry data,
but it doesn’t work as I expect
could you please help me to fix this?
here is my component:

<template>
  <div>
    <label v-for="(label, option) in options" :key="option">
      <input
        type="radio"
        :value="option"
        :checked="option = value"
        @change="$emit('input', option)"
      />
      <slot :name="option">
      {{ label }}
    </slot>
    </label>
  </div>
</template>
<script>
export default {
  name: 'ToggleSwitch',
  props: {
    value: {
      type: String,
      required: true
    },
    options: {
      type: Object,
      required: true
    }
  }
}
</script>

and here is where I want to use this button :

  <toggle-switch v-model="value" :options="options">
  <template #Single>
  <p>test slot</p>
  </template>
  <template #Subscription>
  <p>test slot2</p>
  </template>
  </toggle-switch>
<script>
import ToggleSwitch from '../components/ToggleSwitch.vue'
export default {
  components: {
    ToggleSwitch,
  },
  data() {
    return {
      value: 'Single',
      users: useUsersListStore(),
    }
  },
  computed: {
    options() {
      return {
        Single: 'ggg',
        Subscription: 'bbb',
      }
    }
  },
</script>

Google Sheets | Google appscript parse CSV into multiple Google Sheet Files

I have a CSV file that is provided to me which is over 100mb. I want to convert this into a google sheet but i know the limitations of Google Sheets are as follows:

  • Maximum Cells: 5 million cells per sheet, meaning a sheet can have a maximum of 5 million rows and 1 column, 1 million rows and 5 columns, and so on.
  • Maximum Sheets: 200 sheets per spreadsheet.
  • Maximum File Size: 50MB for a single sheet.

So what i want to do is import this csv as a blob and then break it out into 10mb segments and create new google sheets for each piece.

I have this code so far:

function splitFileIntoChunks(fileId) {
  try {
    // Get the file by ID
    var file = DriveApp.getFileById(fileId);

    // Define the maximum chunk size in bytes (10MB)
    var chunkSizeBytes = 10 * 1024 * 1024;

    // Get the file's size
    var fileSizeBytes = file.getSize();

    // Create a folder to store the chunks
    var folder = DriveApp.createFolder("FileChunks_" + file.getName());

    // Calculate the number of chunks needed
    var numChunks = Math.ceil(fileSizeBytes / chunkSizeBytes);

    // Read and split the file into chunks
    var blob = file.getBlob(); // Get the Blob object once
    var bytePosition = 0; // Initialize the reading position
    for (var i = 0; i < numChunks; i++) {
      var chunkSize = Math.min(chunkSizeBytes, fileSizeBytes - bytePosition); // Adjust for last chunk

      var chunkData = blob.getBytes(chunkSize);
      var chunkBlob = Utilities.newBlob(chunkData);

      // Create a new file for the chunk in the folder
      var chunkFileName = file.getName() + "_chunk_" + (i + 1) + ".part";
      var chunkFile = folder.createFile(chunkBlob.setName(chunkFileName));

      bytePosition += chunkSize; // Update position for the next chunk
    }

    // Optionally, return a status or message
    return "File split into chunks successfully";

  } catch (e) {
    // Handle any errors here
    console.log("Error: " + e.toString());
    return "Error: " + e.toString();
  }
}

when it gets to this line:

var chunkData = blob.getBytes(chunkSize);

I get an error:

Error: Exception: The parameters (number) don’t match the method
signature for Blob.getBytes.

Any ideas what I maybe doing wrong here?

How to enable users to access their user data in firebase

These are my firebase realtime database rules;

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
 
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth.id === $uid",
        ".write": "auth.id === $uid"
      }
    }
  } 
}

Now; I want when the user logs in, he should be able access his user data.

However at the moment am getting the access denied response that the client does’nt have the required permissions to access the desired data and yet he has successfully logged in.

Help me on how I can enable users to read their user data on login;

The following is my attempt;

//my web app's Firebase configuration
var firebaseConfig = {
      // my configurations
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth()
const database = firebase.database()




// Set up our login function
function login () {
  // Get all our input fields
  email = document.getElementById('email').value
  password = document.getElementById('password').value

  // Validate input fields
  if (validate_email(email) == false || validate_password(password) == false) {
    alert('Email or Password is Outta Line!!')
    return
    // Don't continue running the code
  }
  

  var database_ref = database.ref()
  auth.signInWithEmailAndPassword(email, password)
  .then(function() {
    // Declare user variable
    var user = auth.currentUser
    
    
    // Create User data
    var user_data = {
      last_login : Date.now()
    }
    
    // Push to Firebase Database
    database_ref.child('users/' + user.uid).update(user_data)
    
    
    
    const usersRef = database.ref('users');
    const userRef = usersRef.child(user.uid);
        
        
    // Add this user to Firebase Database
        //var database_ref = database.ref()
    
    userRef.once('value')
      .then(snapshot => {
        const userData = snapshot.val();
        alert(userData); // Access the retrieved user data
      })
      .catch(error => {
        alert(error);
      });
    

    
    
    // DOne
    alert('User Logged In!! && verified ' + user.emailVerified + " usernameIs "+ JSON.stringify(user.uid))

  })
  .catch(function(error) {
    // Firebase will use this to alert of its errors
    var error_code = error.code
    var error_message = error.message

    alert(error_message)
  })
}