Best way to show different layouts when pages are cached on CDN

Option 1 – using JSX

<div>
    {window.innerWidth < 550 ? <MobileLayout /> : <DesktopLayout />}
</div>

Option 2 – using CSS

js
<div>
    <MobileLayout className="mobile"/>
    <DesktopLayout className="desktop"/>
</div>

css
@media (min-width: 550px) { 
    .desktop {
        display: none;
    }
}

@media (max-width: 550px) { 
    .mobile {
        display: none;
    }
}

My coworker mentioned that we should avoid option 1 because we cache the page on Fastly and it is possible for a desktop user to be served the mobile layout. I was under the impression that the server responses are cached before the JS is executed and returned to the client. Wouldn’t the conditional render just happen on the client and thus desktop users will see desktop layout and mobile users will see mobile layout even with option 1 for cached pages?

what does Array do in this Javascript function?

I have seen a bit of code similar to this demonstration purpose function, somewhere:

function Pract() {
   let a = Array, b;
   b = 1;
   return b;
}
console.log(Pract())
// Output: 1

However, when I remove Array from the a variable it shows an error:
// And I know this is because b is not defined, but so does b in let a = Array, b;

function Pract() {
    let a = b;
    b = 1;
    return b;
}
console.log(Pract())
// Output: Error

Thanks in advance.

Discord.js question about interaction. is not a function. Why?

I have a code:

client.ws.on('INTERACTION_CREATE', async (interaction) => {
    console.log('interaction.isCommand() ' , interaction.isCommand());
}

But I am getting error on interaction:

TypeError: interaction.isCommand is not a function

why is it happening? I still cant understand that issue.
“discord.js”: “^14.9.0”,

I want to make interaction.reply()

How to allow literal tab character in text input? [duplicate]

I am making a website. I can change the HTML/JS.

How do I let a tab press in input type="text" capture the tab character instead of advancing into the next input?

For example:

  • HTML: <input type="text"><input type="submit">

If I type a<tab>b, then the input should have contents a b (not space, tab). The default is having a as contents, then tab changes focus to submit button.

I need to convert this code to supabase, but there is an error in the join

I need to convert the following SQL code to the subbase using docs API integration (I found almost nothing in the documentation)

SELECT *
FROM public.usuario
JOIN public.usuario_empresa ON public.usuario.id = public.usuario_empresa.usuario_id
JOIN public.empresa ON public.empresa.id = public.usuario_empresa.empresa_id;

The AI ​​itself recommends the following usage

const { data, error } = await supabase
  .from('public.usuario')
  .select('*')
  .join('public.usuario_empresa', { 'public.usuario.id': 'public.usuario_empresa.usuario_id' })
  .join('public.empresa', { 'public.empresa.id': 'public.usuario_empresa.empresa_id' });

but i am getting the error:

  12 |     .from('public.usuario')
  13 |     .select('*')
> 14 |     .join('public.usuario_empresa', { 'public.usuario.id': 'public.usuario_empresa.usuario_id' })
     |     ^
  15 |     .join('public.empresa', { 'public.empresa.id': 'public.usuario_empresa.empresa_id' });

The tables are:

CREATE TABLE public.usuario (
    id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
    nome character varying(100) NOT NULL,
    email character varying(100) NOT NULL,
    telefone character varying(20),
    data_nascimento date,
    cidade_nascimento character varying(100),
    CONSTRAINT usuario_pkey PRIMARY KEY (id)
);

CREATE TABLE public.empresa (
    id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
    nome character varying(100) NOT NULL,
    cnpj character varying(20) NOT NULL,
    endereco character varying(200) NOT NULL,
    CONSTRAINT empresa_pkey PRIMARY KEY (id)
);

CREATE TABLE public.usuario_empresa (
    usuario_id integer NOT NULL,
    empresa_id integer NOT NULL,
    CONSTRAINT usuario_empresa_pkey PRIMARY KEY (usuario_id, empresa_id),
    CONSTRAINT fk_usuario FOREIGN KEY (usuario_id) REFERENCES public.usuario(id),
    CONSTRAINT fk_empresa FOREIGN KEY (empresa_id) REFERENCES public.empresa(id)
);

(I found almost nothing in the documentation about join)

Change the color of a button if at least one option is chosen from a tag

I have a select with several options and a gray button that pretends to be disabled. I want that if at least one option is chosen, the button will change color.

And this is my function, but I can’t make it change the color of the button

var options = document.getElementById('months').selectedOptions;
var value = Array.from(options).map(({
  value
}) => value);
if (value.length > 0) {
  let element = document.getElementById("btn_next");
  element.classList.remove("color");
  element.classList.add("color2");
}
.color {
  background: gray;
}

.color2 {
  background: orange;
}
<form>
  <select id="months" name="months" multiple>
    <option value="January">January</option>
    <option value="Fabruary">Fabruary</option>
    <option value="March">March</option>
    <option value="April">April</option>
    <option value="May">May</option>
    <option value="June">June</option>
    <option value="July">July</option>
    <option value="August">August</option>
    <option value="September">September</option>
    <option value="October">October</option>
    <option value="November">November</option>
    <option value="December">December</option>
  </select>
  <input id="btn_next" type="button" class="color" value="NEXT">
</form>

Issues Passing Data to Components using useNavigate

I have a React app where I am trying to display data fetched from my backend. My goal is to fetch my data (spotify playlists, tracks, and artists) onclick of one of the genres.
then group them all together with promise.all, and send them to the results component with usenavigate:

navigate(`/${genre}`, { state: { artists, playlists, tracks } });

Then in Results, send the relevant data to it’s component (playlists data to playlists component,
tracks data to tracks component, and artists data to artists componenet). but when I click one of the
artists, I still want to send the post request and be routed to /${artist.name} and send all the
data that comes back with it to be displayed in the toptracks component.
I’m pretty positive the data IS being sent to the toptracks component. there is just something wrong
with the data that is getting passed to the artists, playlists, and tracks components.
it is somehow becoming undefined, and I’m not sure why.

These are my errors:

Cannot destructure property 'artists' of 'props.data.artists' as it is undefined.

Uncaught TypeError: Cannot read properties of undefined (reading 'playlists')

Uncaught TypeError: Cannot read properties of undefined (reading 'tracks')

here are the components:

Genres.js

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

function Genres() {
  const [genres, setGenres] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    fetch("/api/genres/")
      .then((response) => response.json())
      .then((data) => setGenres(data.genres))
      .catch((error) => console.log(error));
  }, []);

  function handleClick(genre) {
    const query_params = {
      genre: genre
    };
  
    Promise.all([
      fetch("/api/artists/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(query_params),
      }),
      fetch("/api/playlists/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(query_params),
      }),
      fetch("/api/tracks/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(query_params),
      })
    ])
      .then((responses) => Promise.all(responses.map((response) => response.json())))
      .then(([artists, playlists, tracks]) => {
        console.log({ artists, playlists, tracks });
        navigate(`/${genre}`, { state: { artists, playlists, tracks } });
      })
      .catch((error) => console.log(error));
  }

  return (
    <div>
      <div className="genre-list-container">
        <ul className="genre-list">
          {genres.map((genre) => (
            <li
              className="genre"
              key={genre}
              onClick={() => handleClick(genre)}
            >
              {genre}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

export default Genres;

Results.js

import React from 'react'
import Artists from './Artists'
import Playlists from './Playlists'
import Tracks from './Tracks'
import { useLocation } from "react-router-dom";


function Results() {
  const location = useLocation();

  return (
    <div>
      <Artists data={location.state} />
      <Playlists data={location.state} />
      <Tracks data={location.state} />
    </div>
  );
}

export default Results;

Artists.js

import React, { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";

function Artists(props) {
  const { artists } = props.data.artists;

  const navigate = useNavigate();

  function handleClick(artist) {
    fetch("/api/top_tracks/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ artist_id: artist.id }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        navigate(`/${artist.name}`, { state: { data } });
      });
  }
  // console.log(artists.map((artist) => (artist.name)))
  return (
    <div>
      <div>Artists:</div>
      {artists.map((artist) => (
        <div key={artist.id}>
          <img src={artist.image_url} alt={artist.name} />
          <h1 onClick={() => handleClick(artist)}>{artist.name}</h1>
          <p>Popularity: {artist.popularity}</p>
          <p>Genres: {artist.genres}</p>
        </div>
      ))}
    </div>
  );
}
export default Artists;

TopTracks.js

import React from "react";
import { useLocation } from "react-router-dom";

function TopTracks() {
  const location = useLocation();
  const tracks = location.state;

  return (
    <div>
      
    </div>
  );
}

export default TopTracks;

Playlists.js and Tracks.js are both just console logging the data like so:

import React from "react";

function Tracks(props) {
  const tracks = props.data.tracks.tracks;
  console.log(tracks);
  return (
    <div>

    </div>
  );
}

export default Tracks;

A addEventListener won’t work in a html jQuery dark-light switcher

I tried redoing an “dark-light” mode toggler I got from a codepen. Originally the toggler used a onclick in the html to activate but that didn’t work so I tried makeing a addEventListener to solve the issue but now I realised that didn’t work either, I also tried making it with a jQuery on() but I could not get that to work (probably my fault). So now i’m asking what would be the simplest way of solving this.

Html:

                <label class="switch">
                  <input type="checkbox" id="checkBox" />
                  <span class="slider"></span>
                </label>

JS (jQuery):

$(document).ready(function () {

  $("#main").toggleClass(localStorage.toggled);

  document.getElementById("checkbox").addEventListener("click", darkLight);

  function darkLight() {
    if (localStorage.toggled != "dark") {
      $("body").toggleClass("dark", true);
      localStorage.toggled = "dark";
    } else {
      $("body").toggleClass("dark", false);
      localStorage.toggled = "";
    }
  }

  /*Add 'checked' property to input if background == dark*/
  if ($("main").hasClass("dark")) {
    $("#checkBox").prop("checked", true);
  } else {
    $("#checkBox").prop("checked", false);
  }

});

JavaScript copy properties by reference without modifying the original object

I have objects A and B and would like pass properties of A into B by reference, without passing B’s props into A. I.e.:

const A = { d: 1, e: 2 };
const B = { f: 10, g: 20 };
const C = Object.assign(A, B);

A.d = 10;

console.log(C); // { d: 10, e: 2, f: 10, g: 20} as desired
console.log(A); // { d: 10, e: 2, f: 10, g: 20} but would like just { d: 10, e: 2 }

Is there a way to do this, without using functions/getters to copy things?

owl carousel play and stop buttons for multiple sliders

I wanted to add a play/stop buttons to owl carousel. So far I managed to achive:

  1. Added the play/stop buttons before owl-dots
  2. Wrapped it all in a div.controls for better styling.

and this works well but only with one slider. When adding the next slider the code stops add the play/stop buttons without any errors in the consol.

I have tried to change the querySelector to querySelectorAll but then I get an error Uncaught TypeError: Cannot read properties of undefined (reading 'insertBefore')

It would be perfectly if I could:

  1. have multiple sliders with the buttons
  2. modify if the play/stop buttons will be added before owl-dots or owl-nav for each slider

code:

jQuery(function ($) {
    $(document).ready(function () {

        var owl = $('.slider__carousel');
        owl.owlCarousel({
            loop: true,
            autoplay: true,
            margin: 15,
            animateIn: 'fadeIn',
            animateOut: 'fadeOut',
            dots: true,
            responsiveClass: true,
            responsive: {
                0: {
                    items: 1,
                    nav: true
                },
                700: {
                    items: 1,
                    nav: true
                },
                970: {
                    items: 1,
                    nav: true
                },
                1000: {
                    items: 1,
                    nav: true,
                }
            }
        });

        var owl = $('.logo-slider');
        owl.owlCarousel({
            loop: true,
            autoplay: true,
            autoplayTimeout: 1000,
            autoplayHoverPause: true,
            margin: 15,
            dots: true,

            responsiveClass: true,
            responsive: {
                0: {
                    items: 4,
                    nav: true
                },
                700: {
                    items: 2,
                    nav: true
                },
                970: {
                    items: 5,
                    nav: true
                },
                1000: {
                    items: 6,
                    nav: true,
                }
            }
        });

        var target = document.querySelector('.owl-dots');

        var wrapper = document.createElement('div');
        wrapper.classList.add('controls');

        target.parentNode.insertBefore(wrapper, target);

        wrapper.appendChild(target);

        document.querySelector('.owl-dots').insertAdjacentHTML('beforebegin', '<div class="owl-play-stop-btn"><a class="btn-play"><span class="visually-hidden">Play</span></a><a class="btn-stop"><span class="visually-hidden">Stop</span></a></div>');

        $('.btn-play').ready(function () {
            owl.addClass("hide-play");
        });

        $('.btn-play').on('click', function () {
            owl.trigger('play.owl.autoplay', [1000]);
            owl.addClass("hide-play").removeClass("hide-pause");
        });

        $('.btn-stop').on('click', function () {
            owl.trigger('stop.owl.autoplay');
            owl.addClass("hide-pause").removeClass("hide-play");
        });

    });
});

Django login does not recognize the sent data

I need help. I’m building a web application with Django and React. I’m working on the registration and login functionality, and so far the registration works well and creates a user in the database. However, when I try to log in, it always returns a 401 error, even though the user is in the database.

This is the Django code:

from django.contrib.auth.hashers import check_password
from django.db import models


class Usuario_aplicacion(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.username

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

views.py:

import bcrypt
from django.contrib.auth import authenticate, login
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from .UsuarioSerializer import UsuarioSerializer
from .models import Usuario_aplicacion


@api_view(['POST'])
@csrf_exempt
def registro(request):
    serializer = UsuarioSerializer(data=request.data)
    if serializer.is_valid():
        usuario = serializer.save()
        hashed_password = bcrypt.hashpw(usuario.password.encode('utf-8'), bcrypt.gensalt())
        usuario.password = hashed_password.decode('utf-8')
        usuario.save()
        return Response({'message': 'User created'}, status=201)
    return Response(serializer.errors, status=400)


@api_view(['POST'])
@csrf_exempt
def login_user(request):
    username = request.data.get('username')
    password = request.data.get('password')
    try:
        usuario = Usuario_aplicacion.objects.get(username=username)
        if usuario.check_password(password):
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return Response({'success': True})
    except Usuario_aplicacion.DoesNotExist:
        pass
    return Response({'success': False}, status=401)

UsuarioSerializer.py:

from django.contrib.auth.hashers import make_password
from rest_framework import serializers

from users.models import Usuario_aplicacion


class UsuarioSerializer(serializers.ModelSerializer):
    class Meta:
        model = Usuario_aplicacion
        fields = ['username', 'password', 'email']

    def create(self, validated_data):
        usuario = Usuario_aplicacion(**validated_data)
        usuario.save()
        return usuario

and the form in react:

import React, { useState } from 'react';
import axios from 'axios';

function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    axios.post('http://127.0.0.1:8000/apiusers/login/', {
      username: username,
      password: password,
    })
    .then(response => {
      if (response.data.success) {
        setMessage('Login successful');
      } else {
        setMessage('Login failed');
      }
    })
    .catch(error => {
      setMessage('Login failed');
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="hidden" name="csrfmiddlewaretoken" value="{% csrf_token %}" />
      <label>
        Username:
        <input type="text" value={username} onChange={(event) => setUsername(event.target.value)} />
      </label>
      <label>
        Password:
        <input type="password" value={password} onChange={(event) => setPassword(event.target.value)} />
      </label>
      <button type="submit">Login</button>
      {message && <div>{message}</div>}
    </form>
  );
}

export default LoginForm;

How to build a nextron project without disabling the API routes?

I have a problem with my project. I want to make a desktop app with nextron but when I build it the API routes are closed and it doesn’t even export the js file that makes the request to the API.
Here are the emplacements of the project:
enter image description here
And I also tried to change the next.config.js to try preventing it from blocking the API routes
enter image description here

Can anyone help me?

On some forums I saw that it was imposible but isn’t there a little trick to make it work?

Karate: How to convert a Number to a String in a list

I am getting a map/list from the DB by doing:

myDBList = db2.readRow()

I am trying to compare that list with a nested json object I get from the response doing:

* match $myDBList[*].someValues contains only /myResponse/someValues 

My problem is sometimes some of the values in myDBList are Numbers and values in the response are String. I am getting this error:

$ | actual does not contain expected | actual array does not contain expected item - 123 (LIST:STRING)
$[0] | data types don't match (NUMBER:STRING)

I have tried to convert the object in my list with no success doing:

  • def newList = myDBList.map(x => x + ”)

Value can’t be found in response

I have the following problem, I am trying to scrape a website with a python script but i have the following error, even when checking the website manually (I am inspecting the Network tab, looking for the GET request then click copy – copy response)

I cant find the words : “Welcome Maximilian” , “My Orders”, “My Details”. I dont get why I am not able to find these values.

When looking at the response i see tons of JS Code is that the issue maybe ?

This is the response :

requests.get
    https://pastebin.com/Yauuifzq

My Code is simply logging in (which works fine) then getting the Account Page and check if the response.text contains these values.

I’ve been trying to find a solution to this problem the past few days but can’t seem to solve the problem