Why does backslash get matched on the Unicode U+0060 in Javascript? [closed]

I am wondering why does the Unicode for backtick match on backslash?

In JavaScript this code:

const regex = /[/u0060]/g
const sentence = 'it should match only on this ` not  or /';
console.log(sentence.match(regex));

matches on:

> Array ["`", "/"]

The Unicode character for backslash/ is U+002F and the Unicode character for a backtick or “grave accent” ` is U+0060.

In here it properly distinguishes between the two characters but in JavaScript it seems to not be able to differentiate.

Javascript CSS changing navigation visibility

For a project im working on i need to make sure that when a part of the app is being used a different secondary navigation is being shown. the code down below is the different navigations that i need to be shown but when i clock on the desired button my secondary navigation wont appear

Main NAV:

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow">
    <div class="container-fluid">
        <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ProjectBumbo</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-controller="Prognosis" asp-action="Index">Prognosis</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="Rooster" asp-controller="" asp-action="">Planning</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-controller="" asp-action="">Uren registratie</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-controller="" asp-action="">Medewerkers</a>
                </li>
            </ul>
            <partial name="_LoginPartial" />
        </div>
    </div>
</nav>

And when the Prognosis Link is clicked i need to make this navigation appear

<nav class="navbar navbar-expand-md" id="PrognosisNav" style="display:none;">
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="Prognosis" asp-action="Index">Prognose</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="ExpectationLoad" asp-action="Index">Klanten & Collie beheren</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="Standardization" asp-action="Index">Normering beheren</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="StoreInfo" asp-action="Index">Winkel Informatie</a>
        </li>
    </ul>
</nav>

And when the Planning button is clicked i need to load in this nav

<nav class="navbar navbar-expand-md" id="RoosterNav" style="display:none;">
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="Rooster" asp-action="">Rooster overzicht</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="" asp-action="">Inroosteren</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="" asp-action="">Vervanging</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark border-bottom border-dark" asp-controller="" asp-action="">Verlof Verzoeken</a>
        </li>
    </ul>
</nav>

I tried using this Javascript Code but it won’t work

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const prognosisLink = document.querySelector('a[asp-controller="Prognosis"]');
        const prognosisNav = document.getElementById('PrognosisNav');
        const roosterLink = document.querySelector('a[asp-controller="Rooster"]');
        const roosterNav = document.getElementById('RoosterNav');

        prognosisLink.addEventListener('click', function (event) {
            event.preventDefault();
            prognosisNav.style.display = 'block';
            roosterNav.style.display = 'none';
        });

        roosterLink.addEventListener('click', function (event) {
            event.preventDefault();
            roosterNav.style.display = 'block';
            prognosisNav.style.display = 'none';
        });
    });
</script>

Checkbox value not being returned on checkbox change

I am creating checkboxes from an array of objects. on change, I am not getting back anything.

My code:

let res = [
  { id: "123", fullName: "harry potter", username: "harrypotter" },
  { id: "345", fullName: "hermione granger", username: "hermionegranger" },
  { id: "678", fullName: "ron weasley", username: "ronweasley" },
  { id: "789", fullName: "ginny weasley", username: "ginnyweasley" },
  { id: "987", fullName: "luna lovegood", username: "lunalovegood" },
];

let cbs = document.getElementById("cboxes");
for (const cb of res) {
        cbs.innerHTML += `<div class="form-check form-check-inline">
        <input type="checkbox" class="form-check-input" id="${cb.username}" name="${cb.username}" value="${cb.id}">
        <label class="form-check-label" for="${cb.username}">${cb.username}</label>
        </div>`;
        
let chck = document.getElementById(cb.username);
chck.addEventListener("change", (event) => {
   if (event.currentTarget.checked) {
       alert(`checked ${this.value}`);
   } else {
       alert("not checked");
   }
 });
}
<div id="cboxes"></div>

On checkbox check I want the checkbox value returned. My code is returning nothing.

Typescript configuration to use modules

I am using typescript for this application, I can’t get it to work with modules though. At first I tried with the simple packages installed through npm but I can’t work with local modules either, I tried to import both using .js and .ts extension.
I’m given this error in the browser:

Uncaught ReferenceError: exports is not defined

My .tsconfig is:

"target": "es2016",
 "outDir": "./src/js",
 "rootDir": "./src/ts",
"module": "commonjs", 
"moduleResolution": "node10", // this one I tried to add to resolve the problem
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true

One of the most common solutions, beside changing the .tsconfig file in ways I already did, is to add a exports variable in the script but then I get:

Uncaught ReferenceError: require is not defined

The only thing that seems to work is using parcel to bundle the code, but I’d rather work without bundling every change I make

Priority Matrix in Google Sheets

I am attempting to create something that will pull out a certain number of tasks per category and put them on my daily task list. I currently have it set by priorty only but I want to include a setting for urgency so that even if something is marked lower in priority if it is really urgent that will get pulled first. I am not even sure where to begin to add that factor into the decision making process.

I have very little experience so I apologize in advance at how rough this question is and how overly complex I made the initial code.


function movePriorities() {
  var sourceSheetName = 'Tasks';
  var destinationSheetName = 'To Do';
  var priorityColumnIndex = 2; // Assuming the priority column is the first column (A)

var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName(sourceSheetName);
  var destinationSheet = ss.getSheetByName(destinationSheetName);

  // Get all data from the source sheet
  var data = sourceSheet.getDataRange().getValues();

  // Group data by priority
  var priorityGroups = groupByPriority(data, priorityColumnIndex);

  // Move 5 rows from each priority group to the destination sheet
  for (var priority in priorityGroups) {
    // Skip the first two rows as headers
    var rowsToMove = priorityGroups[priority].slice(2).filter(row => row[priorityColumnIndex - 1] !== ''); // Adjust index to 0-based
    rowsToMove = rowsToMove.slice(0, 5);

    for (var i = 0; i < rowsToMove.length; i++) {
      destinationSheet.appendRow(rowsToMove[i]);
    }
  }
}

// Helper function to group data by priority
function groupByPriority(data, priorityColumnIndex) {
  var groups = {};
  for (var i = 2; i < data.length; i++) { // Start from the third row
    var priority = data[i][priorityColumnIndex - 1]; // Adjust index to 0-based
    if (!groups[priority]) {
      groups[priority] = [];
    }
    groups[priority].push(data[i]);
  }
  return groups;
}  

Check if element is at least half in viewport

I have 4 cards that contain images. When the image is in viewport I want the image to come from the left. I have finished all the css but when I run the JS, it always returns false even if the element is in viewport. I don’t need the whole image to be in the viewport at least half of it and I want it to return true. I have a for each loop that runs through all of the images but it always returns false.

This is the code that I have come up with:

function isInViewport(container) {
  const rect = container.getBoundingClientRect();
  
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

this is the html:

      <div class="col-md-6 col-sm-12 p-0 overflow-hidden bg-dark imageCard">
        <div class="imageCont">
          <img
            src="images/ferrariPhoto1.webp"
            alt=""
            style="width: 100%; height: 100%"
            class="ferrariImageSection"
          />
        </div>
      </div>

How to import a library only if it exists in Vite?

Let’s say in my library I want to import an animation library only if the developer has installed it.

Pseudo code as follows:

let utility = null

// If the library returns the library location as a string
if (Boolean(require.resolve('animation-library'))) {
  import('animation-library').then(library => utility = library.helper)
}

Currently, on Vite (Rollup.js) you get a warning, as the import is analyzed on compilation.

The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

How can I cancel any nested transitions in Framer Motion?

I have the following. It works as expected when I let all transitions finish before I toggle. However, if I would toggle “menu” variable before the first transition (containerVariants) has finished it will revert the animation but the contentVariants one will jump to its visible state right off.

I’m looking for a way that if I would toggle the “menu” while the transition is happening it should revert from where it is, kind of playing backwards of everything as it did on the animation in…

My setup is React, Nextjs 13, Framer motion.

const containerVariants = {
    hidden: {
        scaleX: 0,
        transformOrigin: 'right',
        transition: { duration: 2, when: 'afterChildren' }
    },
    visible: {
        scaleX: 1,
        transition: {
            duration: 2,
            ease: 'easeInOut',
            when: 'beforeChildren'
        }
    }
};

const contentVariants = {
    hidden: { opacity: 0, transition: { duration: 6 } },
    visible: { opacity: 1, transition: { duration: 6 } }
};

const Menu: React.FC<MenuProps> = ({ data }) => {
    const { menu } = useSelector((state: RootState) => state.header);

    if (!data || data.length === 0) {
        throw new Error('Menu data is missing.');
    }

    return (
        <motion.div
            variants={containerVariants}
            initial={false}
            animate={menu ? 'visible' : 'hidden'}
            className="bg-black fixed top-0 w-full h-full flex items-center justify-center">
            <motion.div
                variants={contentVariants}
                className="container mx-auto flex flex-col gap-12">
                {data.map((entry) => {
                    return (
                        <div key={entry.id} className="grid grid-cols-12 gap-5">
                            <div className="col-span-3 text-white uppercase leading-none">
                                {entry.title}
                            </div>
                            <nav className="col-span-9">
                                <ul>
                                    {entry.mainMenuEntries.map((subEntry) => {
                                        const [page] = subEntry?.pageEntry ?? [];
                                        const { id, title, uri } = page as EntryInterface;

                                        return (
                                            <li key={id}>
                                                <Link
                                                    className="text-white text-menuItem leading-tight"
                                                    href={uri || '/not-found-page-entry'}>
                                                    {title}
                                                </Link>
                                            </li>
                                        );
                                    })}
                                </ul>
                            </nav>
                        </div>
                    );
                })}
            </motion.div>
        </motion.div>
    );
};

Hope someone can explain.

Why am I getting this error? (Typescript + Express)

I am getting this error:

No overload matches this call.   The last overload gave the following error.     Argument of type '(req: Request, res: Response) => void' is not assignable to parameter of type 'Application<Record<string, any>>'.

for my 3 auth routes. This is my routes file:

import router, { Router, Request, Response } from "express";

import * as authController from "./controllers/AuthController";
import authenticate, { AuthenticatedRequest } from "./middleware/authenticate";

const appRouter: Router = router();

appRouter.post("/auth/login", authController.login);
appRouter.post("/auth/register", authController.register);
appRouter.post("/auth/refresh-token", authController.refreshToken);
appRouter.get("/protected", authenticate, (req: Request, res: Response) => {
    let user = (req as AuthenticatedRequest).user;
    return res.json(user);
});
export default appRouter;

And here is my route function (To big so I had to cut it, only logic inside):

const login = asyncHandler(async (req: Request, res: Response) => { ... });
const register = asyncHandler(async (req: Request, res: Response) => { ... });
const refreshToken = asyncHandler(async (req: Request, res: Response) => { ... });

I tried checking the request and response interfaces that my routes used but everything seems ok.

Google Maps MaxZoomService reports incorrect max zoom, wish to disable custom zoom button like built-in controls

I am trying to have custom google maps zoom buttons disabled based on the max zoom available for the location. However, the value from the MaxZoomService does not match what the maximum zoom available actually is. This is preventing me from disabling the zoom in button at the same level the built-in buttons seem to be able to do.

In the following demo, you will see the maxZoom report at 19, and then it zooms to 20 after 2 seconds. Then, if you use the controls to zoom out, you cannot get back to 20 with the controls because the maxZoom had reported 19, and I can’t assume if the max zoom is actually 20 or 21 as a workaround.

<html>
  <head>
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "REDACTED",
        v: "weekly",
      });
    </script>
    <style>
      .google-maps-control {
        background: #3C69BE;
        color: white;
        padding: 10px;
        border: solid 1px #45C6EF;
        margin: 10px 0 0 10px;
        cursor: pointer;
      }

      .google-maps-control[disabled] {
        opacity: 0.6;
        cursor: not-allowed;
      }
    </style>
  </head>
  <body>
    <h1>Test Google Maps Max Zoom</h1>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script>
      init();

      let map;
      let zoomInButton;
      let zoomOutButton;
      let maxZoom;

      const center = {
        lat: 45.4633341,
        lng: -98.4512069,
      };

      async function init() {
        await createMap();
        await setAndDemonstrateMaxZoom();
        createCustomControls();
        handleDisabledButtons();
      }

      async function createMap() {
        const { Map, MaxZoomService } = await google.maps.importLibrary("maps");

        map = new Map(document.getElementById("map"), {
          center,
          zoom: 18,
          mapTypeId: "satellite",

          // if I comment this out, the built-in buttons are disabled as expected
          disableDefaultUI: true,

          // isFractionalZoomEnabled: true,
          gestureHandling: 'greedy',
        });

        // use `map` global to assert that map.setZoom(20) surpasses maxZoom 19
        window.map = map;
      }

      async function setAndDemonstrateMaxZoom() {
        const { MaxZoomService } = await google.maps.importLibrary("maps");
        const maxZoomService = new MaxZoomService();

        const result = await maxZoomService.getMaxZoomAtLatLng({
          lat: center.lat,
          lng: center.lng,
        });

        if (result) {
          maxZoom = result.zoom;

          console.warn("getMaxZoomAtLatLng reports 19", maxZoom);

          map.setZoom(maxZoom);

          setTimeout(() => {
            map.setZoom(20);
            console.warn("but maxZoom is actually 20", map.getZoom());
          }, 2000);
        }
      }

      function createCustomControls() {
        zoomInButton = createZoomInControl();
        zoomOutButton = createZoomOutControl();

        zoomWrapper = document.createElement('div');
        zoomWrapper.appendChild(zoomInButton);
        zoomWrapper.appendChild(zoomOutButton);

        map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomWrapper);
      }

      function createZoomInControl() {
        const button = document.createElement('button');
        button.classList.add(...['google-maps-control']);
        button.innerText = '+';
        button.addEventListener('click', () => {
          const zoom = map.getZoom();
          map.setZoom(zoom + 1);
        });

        return button;
      }

      function createZoomOutControl() {
        const button = document.createElement('button');
        button.classList.add(...['google-maps-control']);
        button.innerText = '-';
        button.addEventListener('click', () => {
          const zoom = map.getZoom();
          map.setZoom(zoom - 1);
        });

        return button;
      }

      function handleDisabledButtons() {
        google.maps.event.addListener(map, 'zoom_changed', () => {
          console.log('zoom_changed', map.getZoom());

          const zoom = map.getZoom();

          // disabling the zoom-in button does not replicate the built-in controls here
          zoomInButton.disabled = zoom >= maxZoom ? true : false;

          zoomOutButton.disabled = zoom <= 17 ? true : false;
        });
      }
    </script>
  </body>
</html>

data inserted in email filed is not broadcasted properly to backend, request.is_ajax() returns false

I am following a tutorial about an ecommerce app.

The app is made with Django 4, and ajax is used in the frontend.

I am currently working on a contact page.

compiling the form and submiting should trigger a jquery-confirm popup displaying message “thank you a lot!”.

This is obtained not by simple javascript submit form button
, but via a custom ajax logic.

The problem is that, when I compile and submit the form, the form is validated, the javascript is loaded, but the email data is not transmitted properly (I get None), and in views.py, request.is_ajax() returns None.

This is what happens when I fill up all the form fields and click on submit:

backend:

contact_form.cleaned_data {'fullname': 'John Doe', 'email': None, 'content': 'uvyibuon'}
no ajax in this request: <WSGIRequest: POST '/contact/'>
[20/Nov/2023 16:21:15] "POST /contact/ HTTP/1.1" 200 16035

frontend:

Navigated to http://127.0.0.1:8000/contact/
contact/:255 readyyyy
contact/:261 before submit

Here are my files

mainapp_ecommerce/urls.py

urlpatterns = [
...
path('contact/', contact_page, name="contact"),
]

mainapp_ecommerce/views.py

from .forms import ContactForm

def contact_page(request):

    contact_form = ContactForm(request.POST or None)

    context = {
    "title":"Contact",
    "content":"Welcome to the contact page!",
    "form": contact_form,
    "brand":"new brand name",
    }

    if contact_form.is_valid():
        print("contact_form.cleaned_data", contact_form.cleaned_data)
        
        if request.is_ajax(): # asinchronous javascript and xml
            print("Ajax request")
        
            dict_for_jsonresponse = {
                "message": "thanks!!"
            }
            return JsonResponse(dict_for_jsonresponse)

        else:
            print("no ajax in this request:", request) 

    else:
         print("form not valid")    

    return render(request, "contact/view.html", context )

mainapp_ecommerce/forms.py

class ContactForm(forms.Form):
    # eredita dalla classe form di django

    fullname = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "form-control", 
                "placeholder":"Your full name", 
                "id":"form_full_name"
                }
        )
    )

    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "class": "form-control", 
                "placeholder":"Your email", 
                }
        )
    )
    

    content = forms.CharField(
        widget=forms.Textarea(
            attrs={
                "class": "form-control", 
                "placeholder":"Your content goes here...", 
                }
        )
    )

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not "gmail.com" in email:
            raise forms.ValidationError("Email has to be gmail.com")

mainapp_ecommerce/middlewares.py

class AjaxMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        def is_ajax(self):
            return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
        
        request.is_ajax = is_ajax.__get__(request)
        response = self.get_response(request)
        return response

settings.py

...
MIDDLEWARE = [
    'django.middleware.security.AjaxMiddleware',
...

templates/base.html

    {% load static %}
    <!doctype html>
    <html lang="en">
      <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        

        <!-- <title>Base template</title> -->
        {% include 'base/css.html' %} <!-- questo inietta il codice di una pagina nel punto in cui è messo -->

      </head>



      <body>

        {% include 'base/navbar.html' with brand_name='eCommerce' %}
        <div class='container'>
          {% block content %}
          {% endblock %}
        </div>


      {% include 'base/js.html' %}


        <script>
          $(document).ready(function(){

            console.log("readyyyy")
            // contact form habdrler
            var contactForm = $("contact-form")
            var contactFormMethod = contactForm.attr("method")
            var contactFormEndpoint = contactForm.attr("action")  /* questo lo prende da dove ho scritto action nella view dei contatti */
            
            console.log("before submit")

            contactForm.submit(function(event){
              console.log("entro submit")
              event.preventDefault()  /* quest mi serve a prevenire che lancio il submit premendo invio */
              var contactFormData = contactForm.serialize()
              console.log("serializzazione ok")
              var thisForm = $(this)
              
              $.ajax({

                method: contactFormMethod,
                url: contactFormEndpoint,
                data: contactFormData,

                success: function(data){
                  thisForm[0].reset()  /* empty the form */
                  $.alert({
                    title: "success!",
                    content: "thank you a lot!",
                    theme: "modern",
                  })              
                }, /* success chiudo */

                error: function(error){
                  console.log(error)
                  $.alert({
                    title: "oops",
                    content: "an error occurred",
                    theme: "modern",
                  })
                }, /* chiudo error */

              }) /* chiudo ajax  */


            }) /* chuso contactofrm submint */

        


          })
        </script>



        </body>
    </html>

templates/contact/view.html

  {% extends "base.html" %}

  {% block content %}


  <!doctype html>
  <html lang="en">
    <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      <title>Contact</title>

    </head>

    <body>

      <div class='text-center'>
        <h1>{{title}}</h1>
        <h3>we are working</h3>
      </div>



    <div class='container'>
    <div class='row'>
      <div class='col'>      

        <div class='col-sm-6 col-12 mx-auto'>  <!-- mx auto lo manda nel mezzo -->

          <p>{{ content }}</p>

          <!-- <div class='col-sm-6 col-12'>
          <form method='POST'>
            {% csrf_token %}
            <input type='text' class='form-control' placeholder="Name" name='fullname'>
            <input type='email' class='form-control' placeholder="Email" name='email'>
            <input type='content' class='form-control' placeholder="Your content..." name='content'>
            <button type='submit' class="btn btn-primary">Submit</button>
          </form> -->

          <form class='contact-form' method='POST' action='{% url "contact" %}'>  
            <!-- questo token url mi serve per usare jquery,per essere sicuri che lo mando nel posto giusto. l'url lo prendo dalle views -->
            <!--  il selector della classe lo uso x jquery -->
            {% csrf_token %}
            {{ form.as_p }}
            <br>
            <button type='submit' class="btn btn-primary">Submit</button>
          </form>

        </div>

      </div>

    </div>
    </div>

    <br><br>


      <!-- Optional JavaScript -->
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    </body>
  </html>


  {% endblock %}

Inconsistency with function event.target.getDuration()

When using the function event.target.getDuration() after the initialization of event, I get diferent values for the same video, sometimes a get a float point value with decimals (2221.241), and sometimes an int(2222)

Its not too much of a difference, but it is curious that result is not consisten ¿isn’t it?

Is it a bug wiht the function? Or thas it works that way?

The second one it’s is not even a rounded or a floor value.. it’s a ceil instead…

Best regards

NYT API responds with 401 when api key is from .env file in CRA

I have a React project made with CRA which fetches data from the New York Times API (NYT Times Wire API, to be precise). Until this point I kept the API key inside a component, everything worked well in those circumstances. Then I created an .env file in the root directory (where package.json is) and moved the API key there as REACT_APP_NYT_API_KEY=apiKeyItself. Inside of the component I use it as

const apiKey = process.env.REACT_APP_NYT_API_KEY;
const [url, setUrl] = useState(
    `https://api.nytimes.com/svc/news/v3/content/nyt/homepage.json?limit=100&offset=${urlOffset}&api-key=${apiKey}`
    );

In the console, both apiKey and URL are logged correctly, there is no difference compared to when the apiKey was held in a component, however the NYT API now responds with 401 (unauthorized) and I can’t figure out why.