Angular useHash=true,all routes should have hash ,except few component routes without hash , to implement MFA ,no server side Apache changes

Kindly provide solution for below :
Requirement : By default all page routes should have # in route
expect for 2 specific pages say config -> / config instead of /#/config
Note: CHanges in Server side like apache or nginx , can’t be done as its managed by different team
Kindly suggest some solution ,
FYI: Kindly find stackblitz link , I could not find solution with usehash true ,
found an approach by keeping usehash false

Any possibility to do from Angular this implementation , please provide solution forked as sttackblitz comment , appreciated , thanks !

https://stackblitz.com/edit/angular-ivy-7e5kbsrf?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fcontact.component.ts,src%2Fapp%2Fproduct.component.ts,src%2Fapp%2Fapp.routes.ts,src%2Fapp%2Fcustom-url-serializer.service.ts,src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fhome.component.ts,src%2Findex.html

Issue on refresh or unable to find solution

Why is my frontend returning a blank object?

I’m building an API with Nodejs and my backend is as follows:

if (output && Array.isArray(output) && output[0]) {
            const generatedImageUrl = output[0];  // URL of the generated image

            console.log(`Output: ${output}`)
            return response.status(200).send({generatedImageUrl: generatedImageUrl});

        } else {
            console.error("Error: No valid output from Replicate");
            response.status(500).send({ error: "No valid output from Replicate" });
        }

The ‘Output:’ console.log logs the URL perfectly, but by the time it reaches my frontend:

ry {
      const response = await fetch('https://XXX/devetc', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {

        const apiResponse = await response.json();
        
        console.log("Full API response:", apiResponse);

The console logs:

Full API response: {generatedImageUrl: {…}}
  generatedImageUrl: {}[[Prototype]]: 

I’m using Vue JS framework. Can anyone understand why I’m not able to pull through the response?

Thanks in advance!!

I’ve tried to use .then, I’ve tried to send it as plain text as well as JSON, I’ve tried to use a NPM package for stringifying objects…

How to put the eye button inside the input’s password right end using Tailwind CSS

I am a beginner learning Tailwind CSS and I can’t put the eye icon inside the input’s password container. It always go underneath the password input or sometimes it only goes to the right end side of the password input rather than inside. I’ve tried asking chatGPT and vercel to fix it, but it seems that the output is what I described.

<section class="min-h-screen flex items-center justify-center pt-16">
      <div
        class="bg-white p-10 mx-auto w-1/3 bg-transparent xs:max-md:w-4/5 md:max-lg:w-3/5 rounded-xl text-black my-10 shadow-xl"
      >
        <div class="login-form-container">
          <h1 class="text-4xl font-semibold text-center poppins text-black">
            Log in
          </h1>
          {% if messages %}
          <div class="text-center my-3">
            {% for message in messages %}
            <p class="text-red-500">{{ message }}</p>
            {% endfor %}
          </div>
          {% endif %}

          <div class="login-form">
            <form method="POST">
              {% csrf_token %}
              <!-- Email Input -->
              <div class="username-container my-5">
                <input
                  required
                  type="text"
                  name="username"
                  id="username"
                  placeholder="Username"
                  class="border-green-500 w-full h-full py-3 px-5 rounded-full placeholder-gray-300 border focus:ring-1 focus:ring-green-500 focus:border-green-500"
                  value="{{ form.username.value|default:'' }}"
                />
              </div>
              <!-- Password Input -->
              <div class="password-container my-5 relative">
                <input
                  required
                  type="password"
                  name="password"
                  id="password"
                  placeholder="Password"
                  class="border-green-500 w-full py-3 px-5 pr-12 rounded-full placeholder-gray-300 border focus:ring-1 focus:ring-green-500 focus:border-green-500"
                  value="{{ form.password.value|default:'' }}"
                />
                <button
                  type="button"
                  class="absolute right-3 top-1/2 -translate-y-1/2 flex items-center justify-center text-gray-500 hover:text-gray-700 focus:outline-none"
                  onclick="togglePasswordVisibility()"
                >
                  <svg
                    class="h-6 w-6 text-emerald-500"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
                    />
                  </svg>
                </button>
              </div>

              <!-- Remember Me and Forgot Password -->
              <div class="flex justify-between w-full">
                <div>
                  <input type="checkbox" name="remember-me" id="remember-me" />
                  <label for="remember-me">Remember me</label>
                </div>
                <a
                  href="#"
                  class="hover:underline cursor-pointer"
                  id="forgot-password-link"
                  >Forgot Password?</a
                >
              </div>
              <!-- Log In Button -->
              <button
                type="submit"
                class="w-full text-center bg-green-500 rounded-full my-5 p-3 font-semibold text-white hover:bg-green-600 transition duration-300 ease-in"
              >
                Log In
              </button>
              <p class="text-center poppins">
                Don't have an account?
                <a
                  href="{% url 'users:signUp' %}"
                  class="hover:underline font-bold text-blue-500"
                  >Sign Up</a
                >
              </p>
            </form>
          </div>
        </div>
      </div>
    </section>

How to proceed with web page that works great on desktop but not on phones?

I’ve been working on my first modern website using plain vanilla html, css, and javascript. The site works perfectly on my laptop, but the only android browser that it works on is Firefox. The others show a blank screen. Part of the problem is that I’m using a shared worker, which is not supported on chrome for android (and probably others as well), but I’m not sure if that’s the only problem. I’m also using standard web components (custom elements with shadow root, templates, and slots).

I’m looking for some advice. How would you approach this problem? I could try using dedicated workers instead of a shared worker, but I have to actually deploy the code in order to see if it works on the phone. There must be a better way. What do you suggest?

Using jQuery function with different HTML ID’s

I want to use jquery function multiple times with different ID’s to upload different images. For example if I use input field with id=myImg1 for upload an image, it should’t upload this image for input field with id=myImg=2, but it does so. I want to try something like for loop, but don’t understand how to do it.

I’ve tried this code:

$(function() {
    $(":file").change(function() {
      if (this.files && this.files[0]) {
        for (var i = 0; i < this.files.length; i++) {
          var reader = new FileReader();
          reader.onload = imageIsLoaded;
          reader.readAsDataURL(this.files[i]);
        }
      }
    });
  });
  
  function imageIsLoaded(e) {
    $('div[id^=myImg]').append('<img src=' + e.target.result + '>');
  };
<input type="file" multiple/>
<div id="myImg1"></div>
          
<p>Геоморфология</p> 
<input type="text" placeholder="" name="place" class="input"/><br>
<input type="file" multiple/> 
<div id="myImg2"></div>    

This results in
this

Can you make sortable.js work with boostrap 5 modal?

I’m building a checklist app for fun and I’m trying to use sortable.js with python django.

I can make a sortable list work in this example with the html as follows


    {% extends 'BJJApp/base.html' %}
    {% load static %}
    {%load crispy_forms_tags %} 
    {% block content %}

    <br><br>

    <div id="standalone-items-container">
        {% for item, formset, links in standalone_items_formsets_links %}
        <div class="modal fade" id="exampleModalToggle-{{ item.id }}" aria-hidden="true" aria-labelledby="exampleModalToggleLabel-{{ item.id }}" data-item-id="{{ item.id }}" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5" id="exampleModalToggleLabel-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};">{{ item.title }}</h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form method="POST" id="main-form-{{ item.id }}" action="{% url 'viewitem' item.id %}">
                            {% csrf_token %}
                            <div class="form-group">
                                <label for="title">Title</label>
                                <input type="text" name="title" class="form-control" id="title-{{ item.id }}" value="{{ item.title }}" required disabled>
                            </div>
                            <div class="form-group">
                                <label for="memo">Memo</label>
                                <textarea name="memo" rows="5" class="form-control" id="memo-{{ item.id }}" disabled>{{ item.memo }}</textarea>
                            </div>
        
                            
                            
                            <div class="form-group form-check">
                                <input type="checkbox" name="important" class="form-check-input" id="important-{{ item.id }}" {% if item.important %}checked{% endif %} disabled>
                                <label class="form-check-label" for="important">Important</label>
                            </div>
                        </form>
                    </div>
        
                    <div id="links-{{ item.id }}">
                        {% if links %}
                            <ul>
                                {% for link in links %}
                                    <li><a href="{{ link.url }}" target="_blank">{{ link.url|urlizetrunc:50 }}</a></li>
                                {% endfor %}
                            </ul>
                        {% else %}
                            <p>&nbsp;&nbsp;&nbsp;&nbsp;No links available for this item.</p>
                        {% endif %}
                    </div>
                    <div class="d-flex justify-content-end">
                        <a href="{% url 'updatelinks' item.id %}" style="display: none" id="updatelinks-{{ item.id }}">
                            <button type="button" class="btn btn-warning me-5">
                                Add or Remove Links
                            </button>
                        </a>
                    </div>
                    <br>
                    <div class="modal-footer" >
        
                        <button type="button" id="edit-button-{{ item.id }}" class="btn btn-primary me-2" onclick="toggleEdit({{ item.id }})">Edit</button>
                        <!-- Complete Button Form (if item is not completed) -->
                        {% if item.datecompleted is None %}
                        <form method="POST" action="{% url 'completeitem' item.id %}" style="display:inline-block;">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-success me-2">Complete</button>
                        </form>
                        {% endif %}
        
                        <!-- UnComplete Button Form (if item is completed) -->
                        {% if item.datecompleted %}
                        <form method="POST" action="{% url 'uncompleteitem' item.id %}" style="display:inline-block;">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-success me-2">UnComplete</button>
                        </form>
                        {% endif %}
        
                        <!-- Delete Button Form -->
                        <form method="POST" action="{% url 'deleteitem' item.id %}" style="display:inline-block;">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
        
                    </div>
                    
                </div>
            </div>
        </div>
        
        <!-- 
        <button class="btn btn-primary" id="exampleModalToggleButton-{{item.id}}" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal" style="color: {% if item.important %}red{% else %}inherit{% endif %};" onclick="storeModalId('{{ item.id }}')">
            {{ item.title }}
        </button> -->
        
        <div class="card mb-3" style="max-width: 800px;" draggable="true" data-item-id="{{ item.id }}">
            <div class="card-body d-flex justify-content-between align-items-center"  style="cursor: pointer;">
            <!-- <div class="card-body d-flex justify-content-between align-items-center" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal"  onclick="storeReferrerAndModal('{{ item.id }}', false)"  style="cursor: pointer;"> -->
                <!-- Card Content -->
                <div>
                    <h5 class="card-title" id="card-title-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};" >{{ forloop.counter }}. {{ item.title }}</h5>
                    <p class="card-text">{{ item.memo }}</p>
                </div>
        
                <!-- Buttons -->
                <div>
                    
                <button class="btn btn-primary" id="exampleModalToggleButton-{{item.id}}" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal"  onclick="storeReferrerAndModal('{{ item.id }}', false)">
                    Details
                </button>
                    <!-- Complete Button Form (if item is not completed) -->
                    {% if item.datecompleted is None %}
                    <form method="POST" action="{% url 'completeitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-success">Complete</button>
                    </form>
                    {% endif %}
        
                    <!-- UnComplete Button Form (if item is completed) -->
                    {% if item.datecompleted %}
                    <form method="POST" action="{% url 'uncompleteitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-success">UnComplete</button>
                    </form>
                    {% endif %}
        
                    <!-- Delete Button Form -->
                    <form method="POST" action="{% url 'deleteitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
                </div>
            </div>
        </div>
        
        
        
        
        
        {% endfor %}
        </div>



    {% endblock %}

    {% block scripts %}
    <script src="{% static 'Checklist/Checklist.js' %}" ></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const container = document.getElementById('standalone-items-container');
            const csrfToken = '{{ csrf_token }}'; // CSRF token for secure POST requests

            Sortable.create(container, {
                animation: 150, // Smooth animation while dragging
                onEnd: function (event) {
                    // Get the updated order of item IDs
                    const updatedOrder = Array.from(container.children).map((card, index) => {
                        // Update the displayed order on the card
                        const titleElement = card.querySelector('.card-title');
                        titleElement.textContent = `${index + 1}. ${titleElement.textContent.split('. ').slice(1).join('. ')}`;
                        return card.dataset.itemId;
                    });

                    // Send the updated order to the backend
                    fetch("{% url 'update_item_order' %}", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "X-CSRFToken": csrfToken, // CSRF token for Django
                        },
                        body: JSON.stringify({ order: updatedOrder }),
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error("Failed to update order.");
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log("Order updated:", data);
                    })
                    .catch(error => {
                        console.error("Error updating order:", error);
                    });
              },
            });
        });
    </script>



    {% endblock %}

in my views I have

def test5(request):
    items = Item.objects.filter(user=request.user, datecompleted__isnull=True)
    if request.user.profile.role == "instructor":
        courses = request.user.checklist_courses.filter(related_course__isnull=False)
    else:
        courses = request.user.checklist_courses.exclude(
            creator__profile__role="instructor"
        )
    courses_percentages = []
    standalone_items_formsets_links = []
    course_items_formsets_links = []
    standalone_items = items.filter(courses__isnull=True).order_by("order")
    course_items = items.filter(courses__isnull=False)

    for item in standalone_items:
        LanguageFormSet = inlineformset_factory(Item, Link, fields=("url",), extra=1)
        formset = LanguageFormSet(instance=item)
        links = Link.objects.filter(item=item)
        standalone_items_formsets_links.append((item, formset, links))

    for item in course_items:
        LanguageFormSet = inlineformset_factory(Item, Link, fields=("url",), extra=1)
        formset = LanguageFormSet(instance=item)
        links = Link.objects.filter(item=item)
        course_items_formsets_links.append((item, formset, links))

    for course in courses:
        total_items = course.items.count()
        completed_items = course.items.filter(datecompleted__isnull=False).count()
        # Avoid division by zero
        if total_items > 0:
            progress_percentage = (completed_items / total_items) * 100
        else:
            progress_percentage = 0
        courses_percentages.append((course, progress_percentage))

    return render(
        request,
        "BJJApp/test5.html",
        {
            "standalone_items": standalone_items,
            "courses_percentages": courses_percentages,
            "standalone_items_formsets_links": standalone_items_formsets_links,
            "course_items_formsets_links": course_items_formsets_links,
        },
    )

def update_item_order(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            item_ids = data.get("order", [])

            # Update the order field for each item
            for idx, item_id in enumerate(item_ids, start=1):
                Item.objects.filter(id=item_id).update(order=idx)

            return JsonResponse({"success": True})
        except Exception as e:
            return JsonResponse({"success": False, "error": str(e)}, status=400)

    return JsonResponse(
        {"success": False, "error": "Invalid request method."}, status=405
    )

this works fine and I can drag and drop and update the order number and display the updated number of the items in the card.

but when I change it to modal, it doesn’t work and doesn’t update. Can anyone help?

{% extends 'BJJApp/base.html' %}
{% load static %}
{%load crispy_forms_tags %} 
{% block content %}

<br><br>

<div id="standalone-items-container">

    {% for item, formset, links in standalone_items_formsets_links %}
    <div class="modal fade" id="exampleModalToggle-{{ item.id }}" aria-hidden="true" aria-labelledby="exampleModalToggleLabel-{{ item.id }}" data-item-id="{{ item.id }}" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalToggleLabel-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};">{{ item.title }}</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" id="main-form-{{ item.id }}" action="{% url 'viewitem' item.id %}">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="title">Title</label>
                            <input type="text" name="title" class="form-control" id="title-{{ item.id }}" value="{{ item.title }}" required disabled>
                        </div>
                        <div class="form-group">
                            <label for="memo">Memo</label>
                            <textarea name="memo" rows="5" class="form-control" id="memo-{{ item.id }}" disabled>{{ item.memo }}</textarea>
                        </div>
    
                        
                        
                        <div class="form-group form-check">
                            <input type="checkbox" name="important" class="form-check-input" id="important-{{ item.id }}" {% if item.important %}checked{% endif %} disabled>
                            <label class="form-check-label" for="important">Important</label>
                        </div>
                    </form>
                </div>
    
                <div id="links-{{ item.id }}">
                    {% if links %}
                        <ul>
                            {% for link in links %}
                                <li><a href="{{ link.url }}" target="_blank">{{ link.url|urlizetrunc:50 }}</a></li>
                            {% endfor %}
                        </ul>
                    {% else %}
                        <p>&nbsp;&nbsp;&nbsp;&nbsp;No links available for this item.</p>
                    {% endif %}
                </div>
                <div class="d-flex justify-content-end">
                    <a href="{% url 'updatelinks' item.id %}" style="display: none" id="updatelinks-{{ item.id }}">
                        <button type="button" class="btn btn-warning me-5">
                            Add or Remove Links
                        </button>
                    </a>
                </div>
                <br>
                <div class="modal-footer" >
    
                    <button type="button" id="edit-button-{{ item.id }}" class="btn btn-primary me-2" onclick="toggleEdit({{ item.id }})">Edit</button>
                    <!-- Complete Button Form (if item is not completed) -->
                    {% if item.datecompleted is None %}
                    <form method="POST" action="{% url 'completeitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-success me-2">Complete</button>
                    </form>
                    {% endif %}
    
                    <!-- UnComplete Button Form (if item is completed) -->
                    {% if item.datecompleted %}
                    <form method="POST" action="{% url 'uncompleteitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-success me-2">UnComplete</button>
                    </form>
                    {% endif %}
    
                    <!-- Delete Button Form -->
                    <form method="POST" action="{% url 'deleteitem' item.id %}" style="display:inline-block;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
    
                </div>
                
            </div>
        </div>
    </div>
    
    <!-- 
    <button class="btn btn-primary" id="exampleModalToggleButton-{{item.id}}" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal" style="color: {% if item.important %}red{% else %}inherit{% endif %};" onclick="storeModalId('{{ item.id }}')">
        {{ item.title }}
    </button> -->
    
    <div class="card" style="max-width: 800px;" data-item-id="{{ item.id }}">
        <div class="card-body d-flex justify-content-between align-items-center" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal"  onclick="storeReferrerAndModal('{{ item.id }}', false)"  style="cursor: pointer;">
            <!-- Card Content -->
            <div>
                <h5 class="card-title" id="card-title-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};" >{{ forloop.counter }}. {{ item.title }}</h5>
                <p class="card-text">{{ item.memo }}</p>
            </div>
    
            <!-- Buttons -->
            <div>
                
            <button class="btn btn-primary" id="exampleModalToggleButton-{{item.id}}" data-bs-target="#exampleModalToggle-{{ item.id }}" data-bs-toggle="modal"  onclick="storeReferrerAndModal('{{ item.id }}', false)">
                Details
            </button>
                <!-- Complete Button Form (if item is not completed) -->
                {% if item.datecompleted is None %}
                <form method="POST" action="{% url 'completeitem' item.id %}" style="display:inline-block;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-success">Complete</button>
                </form>
                {% endif %}
    
                <!-- UnComplete Button Form (if item is completed) -->
                {% if item.datecompleted %}
                <form method="POST" action="{% url 'uncompleteitem' item.id %}" style="display:inline-block;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-success">UnComplete</button>
                </form>
                {% endif %}
    
                <!-- Delete Button Form -->
                <form method="POST" action="{% url 'deleteitem' item.id %}" style="display:inline-block;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
    <br>
    
    
    
    
    {% endfor %}
    </div>



{% endblock %}

{% block scripts %}
<script src="{% static 'Checklist/Checklist.js' %}" ></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const container = document.getElementById('standalone-items-container');
        const csrfToken = '{{ csrf_token }}'; // CSRF token for secure POST requests

        Sortable.create(container, {
            animation: 150, // Smooth animation while dragging
            onEnd: function (event) {
                // Get the updated order of item IDs
                const updatedOrder = Array.from(container.children).map((card, index) => {
                    // Update the displayed order on the card
                    const titleElement = card.querySelector('.card-title');
                    titleElement.textContent = `${index + 1}. ${titleElement.textContent.split('. ').slice(1).join('. ')}`;
                    return card.dataset.itemId;
                });

                // Send the updated order to the backend
                fetch("{% url 'update_item_order' %}", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRFToken": csrfToken, // CSRF token for Django
                    },
                    body: JSON.stringify({ order: updatedOrder }),
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error("Failed to update order.");
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("Order updated:", data);
                })
                .catch(error => {
                    console.error("Error updating order:", error);
                });
            },
        });
    });
</script>



{% endblock %}

Thanks

How do I input API REST data from Excel “console” to cells?

I am able to pull in this weather data in Excel scripts, but I’m not exactly sure how to programmatically get it into the first column, “Column A”.

Any ideas?


function main(workbook: ExcelScript.Workbook) {
  fetch('https://api.weather.gov/gridpoints/ILN/44,38/forecast')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response error');
      }
      return response.json();
    })
    .then(data => {
      for (i in data.properties.periods) {
        console.log(data.properties.periods[i].name);
      }
    })
    .catch(error => {
      console.error('Fetch error:', error);
    });
}

Listen to NextJs Link navigation from script with SSG

NextJs Link replaces classic navigation with preloaded HTML and DOM swap, but the script, provided with next/script is not called on such navigation. So it works only on initial page load and stops working when navigating with Link.

This can be fixed by using a instead of Link.

But I want to keep that preloading and still be able to run my script on each navigation. Also, I’m using full SSG for my website.

Here is the simplified script:

// Button clicks work only no the initial load.

<Script id="enable-modal-button-script">
{`
  const button = document.getElementById('button')
  button && button.addEventListener('click', () => {
    document.getElementById('modal').showModal()
  })
`}
</Script>

2d array – group by first item and calculate average of corresponding number

I have a 2d array which contains a list of series with title, rating, and time spent watching. For example:

let seriesList = [["Squid Game", 3.5, "4 days"], ["Squid Game", 2.5, "3 days"], ["Buffy the Vampire Slayer", 5, "32 days"], ["The Fosters", 3, "5 days"]];

A series can appear multiple times with a different rating. I would like to calculate the average rating for each series (and get another 2d array with each series appearing only once).

So far, I used reduce() on the array in order to do the sum of all the ratings, but I can’t figure out how to get the number of ratings so I can divide by it.

let seriesList = [["Squid Game", 3.5, "4 days"], ["Squid Game", 2.5, "3 days"], ["Buffy the Vampire Slayer", 5, "32 days"], ["The Fosters", 3, "5 days"]]; // example of values in my array, but it's actually much longer and it will change with each new series i watch
    
let seriesListAverage = Object.values(
    seriesList.reduce((accumulator, currentValue) => {

      if (accumulator[currentValue[0]]) {
        accumulator[currentValue[0]][1] += currentValue[1]; // do the sum of all ratings
      }
      else {
        accumulator[currentValue[0]] = currentValue;
      }
      return accumulator;
    }, {})
);

console.log(seriesListAverage); // Result: [["Squid Game", 6, "4 days"], ["Buffy the Vampire Slayer", 5, "32 days"], ["The Fosters", 3, "5 days"]]

// Expected result: [["Squid Game", 3, "4 days"], ["Buffy the Vampire Slayer", 5, "32 days"], ["The Fosters", 3, "5 days"]]

(If it matters, the script is written in Apps Script, I get the values for seriesList from a sheet of my Sheets file, and I print the result into another sheet. That’s why I need a 2d array.)

Wanted to simulate an API or network error to display the error modal in testcafe

test('should amount field and name field reset after submit', async ()=>{
 
 const amountInput = await Selector('.amount');
 await t.typeText(input, 10);

 const nameInput = await Selector('.name');
 await t.typeText(input, "test");

 await t.click(Selector('button'));

 await t.click(Selector('transfer'));

 after calling api...

 showing error modal
})

I am using TestCafe for automation testing. After clicking on the transfer button, I want to simulate an API or network error to display the error modal. Then, will close the modal to verify that the input values are not reset.

Nextjs Algolia re-rending issue

Implemenatation overview:
For frontend, we’re using Nextjs and Shopify for backend. We’re using Algolia’s react-instantsearch library for products data display on the Product listing pages (PLPs). We have a parent component called collection.js in which the product data is fetched from algolia and that product data is iterated through ProductItemTile.js component to pass each product data to be displayed on PLP. We show around 102 or 104 products per page. Since, we don’t get complete product data from Algolia, an additional api is made to shopify to get additional details per product (get-plp-product-data) in ProductItemTile component.

Issue:
When we the reload the PLP, multiple get-plp-product-data api are fired more than the number of products on any PLP page except page 1.

Tech stack:
Nextjs, Shopify, Algolia

We’re suspecting it could be issue because of re-rendering but we’re haven’t found the exact cause of it.

How can I create a diagram like this one using react and some front end library like mui?

I am new to front end design and have issues creating nice diagrams. I want to create a snake like roadmap diagram for my page that uses routing to go to new pages from each snake link. I have added a diagram for my goal to see if anyone has any libraries/components I could use that would help me with something like this.
(https://i.sstatic.net/lGYyf3P9.png)

I have tried creating this myself but it is very ugly with basically just a thick line connecting boxes.

429 Too Many Requests” error when using the OpenAI API

I’m encountering a “429 Too Many Requests” error when using the OpenAI API in my web application. I’ve implemented a retry mechanism with exponential backoff, but the error persists even after retries. Here’s the relevant part of my code:

async function getResponse() {
    const apiKey = 'YOUR_API_KEY';
    let retryCount = 0;
    const maxRetries = 10;
    let backoff = 1000; // initial backoff time in milliseconds

    while (retryCount < maxRetries) {
        try {
            const response = await fetch('https://api.openai.com/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    model: "gpt-3.5-turbo",
                    messages: [{ "role": "user", "content": userInput }]
                })
            });

            if (response.status === 429) {
                console.warn(`Rate limit exceeded. Retrying in ${backoff / 1000} seconds...`);
                await new Promise(resolve => setTimeout(resolve, backoff));
                backoff *= 2; // exponential backoff
                retryCount++;
            } else if (response.ok) {
                const data = await response.json();
                // Process response data
                break;
            } else {
                console.error('Unexpected error:', response);
                break;
            }
        } catch (error) {
            console.error('Error:', error);
            break;
        }
    }

    if (retryCount === maxRetries) {
        console.error('Max retries reached.');
    }
}

After creating the Api key from OpenAI I have paste it in the above code where it says ‘YOUR_API_KEY’

Despite handling retries and backoff properly, the “429 Too Many Requests” error still occurs frequently. Could anyone provide insights or suggestions on how to better manage this error, or any possible ways to optimize API calls to avoid hitting rate limits?

How to get a paragraph of text to display only when a certain radio button is checked

I believe I’m working in Javascript (go easy on me, I know basic – intermediary HTML). In the checkout section of our e-commerce website, there’s a page that displays all active UPS shipping options, plus Warehouse Pickup (all of which is pulled from our database: Netsuite), so the customer can choose how they would like their order to be shipped.

I’m trying to update this page so that 1-2 sentences of text will appear underneath of the shipping options ONLY when “Warehouse Pickup” (internal id #: 171) is selected. But when I try entering the code that I thought would make that happen, it crashed that page of checkout. What did I do wrong and how can I correct it?

I’ve attached a screenshot of the webpage so you can see how it looks and works. screenshot of checkout page showing shipping methods

The part I added to make the text appear is (plus, I added a <% { %> at the end to close it out):

<% if (shipmethod.get('internalid')="171") { %>
            <% =_('Please note: For orders under $100, a $0.10/shopping bag fee will be applied to your order upon fulfillment, as required by City of Annapolis Ordinance 5-24. To learn more about the Annapolis Plastic Bag Ban Act, <a hred="https://www.annapolis.gov/2197/Plastic-Bag-Reduction-Act#:~:text=Effective%20January%2022%2C%202025%2C%20retailers,bring%20reusable%20bags%20for%20shopping." target="_blank"'>.')translate() %>

Here’s the full code:

<form class="delivery-options" action="">
<fieldset style="margin-bottom:36px;">
    <legend class="delivery-options-header section-header">
        <%= _('Delivery Options:').translate() %>
    </legend>
    <span class="delivery-option-label">
        <%= _('<em>For Canadian shipping addresses, we recommend using USPS Priority Mail. To choose this option, select UPS Ground below and click Continue. Then continue checking out. On the Review Your Order page, use the text box at the bottom to request our staff to change the shipping method to USPS Priority Mail.</em>').translate() %>
    </span><P></p><br><p></P>
    <% if (!view.model.get('isEstimating') && !view.wizard.application.getUser().get('addresses').get(view.model.get('shipaddress'))) { %>
        <%= _('Warning: Please enter a valid shipping address first').translate() %>
    <% } else if (!shipping_methods.length) { %>
        <%= _('Warning: No Shipping Methods are available for this address').translate() %>
    <% } else { %>
        <% shipping_methods.each(function (shipmethod) { %>
        <% if(custentity5 && custentity5.length > 0 && shipmethod.get('internalid') == "5213") { %>
            <% is_active = order_delivery_method === shipmethod.get('internalid') %>
            <label class="delivery-option<%= is_active ? ' active' : '' %>" data-id="<%= shipmethod.get('internalid')%>" data-account="<%=custentity5[0].value%>">
                <input
                    type="radio"
                    name="delivery-options"
                    id="delivery-options-<%= shipmethod.get('internalid')%>"
                    value="<%- shipmethod.get('internalid')%>"
                    <%= is_active ? 'checked' : '' %>
                >
                <span class="delivery-option-label">
                    <%= shipmethod.get('name') %>
                </span>
            </label> 
        <% if (shipmethod.get('internalid')="171") { %>
            <% =_('Please note: For orders under $100, a $0.10/shopping bag fee will be applied to your order upon fulfillment, as required by City of Annapolis Ordinance 5-24. To learn more about the Annapolis Plastic Bag Ban Act, <a hred="https://www.annapolis.gov/2197/Plastic-Bag-Reduction-Act#:~:text=Effective%20January%2022%2C%202025%2C%20retailers,bring%20reusable%20bags%20for%20shopping." target="_blank"'>.')translate() %>    
        <% } else if(custentity6 && custentity6.length > 0 && shipmethod.get('internalid') == "5214") { %>
            <% is_active = order_delivery_method === shipmethod.get('internalid') %>
            <label class="delivery-option<%= is_active ? ' active' : '' %>" data-id="<%= shipmethod.get('internalid')%>" data-account="<%=custentity6[0].value%>">
                <input
                    type="radio"
                    name="delivery-options"
                    id="delivery-options-<%= shipmethod.get('internalid')%>"
                    value="<%- shipmethod.get('internalid')%>"
                    <%= is_active ? 'checked' : '' %>
                >
                <span class="delivery-option-label">
                    <%= shipmethod.get('name') %>
                </span>
            </label> 
        <% } else if(shipmethod.get('internalid') != "5213" && shipmethod.get('internalid') != "5214") { %>                
            <% is_active = order_delivery_method === shipmethod.get('internalid') %>
            <label class="delivery-option<%= is_active ? ' active' : '' %>" data-id="<%= shipmethod.get('internalid')%>">
                <input
                    type="radio"
                    name="delivery-options"
                    id="delivery-options-<%= shipmethod.get('internalid')%>"
                    value="<%- shipmethod.get('internalid')%>"
                    <%= is_active ? 'checked' : '' %>
                >
                <span class="delivery-option-label">
                    <%= shipmethod.get('name') %>:
                </span>
                <span class="delivery-option-rate">
                    <%= shipmethod.get('rate_formatted') %>
                </span>
            </label>
        <% } %>
        <% } %>
        <% }); %>
    <% } %>
</fieldset>