How to access checked property of a material UI and set it equal to false when pressing another icon (delete icon)?

I hope you are all doing great! I have a question and it would be amazing if someone could give me some information or direction on how to tackle my problem.

My problem is how to access the checked property of a material-ui <Checkbox checked={}/> component and set it equal to false or in other words, toggle it off when pressing a button. My problem is that the delete icon (button) exists in another file which means it is a different component. Furthermore, the button’s onClick={} event has a property onClearSelected which is responsible of erasing strings inside looking like cells.

Further, I hope that I gave you some insight and I did not confuse you further. I would be glad to answer to any questions and I am sorry in advance if it is hard for you to understand what I am trying to imply.

Sincerely,
Nikolaos

Changing background based on weather description using next.js

I am trying to have it so that the background of my weather app will change based on the weather condition using nextjs and the current weather data API. But no image is display. This is my Main

import axios from "axios";
import { useState } from "react";
import Weather from "./Weather";
import Spinner from "./Spinner";
import { data } from "autoprefixer";
import Background from "./Background";

const Main = () => {
  const [city, setCity] = useState("");
  const [weather, setWeather] = useState({});
  const [loading, setLoading] = useState(false);

  //In celsius -(&units=metric) in fahrenheit -(&units=imperial)
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${process.env.NEXT_PUBLIC_WEATHER_KEY}`;

  const fetchWeather = (e) => {
    e.preventDefault();
    setLoading(true);
    axios.get(url).then((response) => {
      setWeather(response.data);
      //   console.log(response.data);
    });
    setCity("");
    setLoading(false);
  }; 

  if (loading) {
    return <Spinner />;
  } else {
    return (
      <div>
        {/* Overlay, so we use a self-closing div */}
        <div className="absolute top-0 left-0 right-0 bottom-0 bg-black/40 z-[1]" />
        <Background
          weatherDescription={data.weather ? data.weather[0].main : null}
        />
        <div className="relative flex justify-between items-center max-w-[500px] w-full m-auto pt-4 text-white z-10">
          <form
            onSubmit={fetchWeather}
            className="flex justify-between items-center w-full m-auto p-3 bg-transparent border border-gray-300 text-white rounded-2xl"
          >
            <div>
              <input
                onChange={(e) => setCity(e.target.value)}
                className="bg-transparent border-none text-white focus:outline-none text-2xl"
                type="text"
                placeholder="Search"
              />
            </div>
            <button onClick={fetchWeather}>
              <BsSearch size={20} />
            </button>
          </form>
        </div>

        {weather.main && <Weather data={weather} />}
      </div>
    );
  }
};

And this is the background component

import React from "react";
import img1 from "../public/assets/Rainy weather.jpg";
import img2 from "../imgs/Cloudy Weather.jpg";

function Background(props) {
  const images = [
    {
      name: "Rain",
      background: img1.src,
    },
    {
      name: "Clouds",
      background: img2.src,
    },
  ];
  const imgURL = images.find((el) => el.name === props.weatherDescription)
    ?.background;
  return (
    <div className="-z-10">
      <img
        src={imgURL}
        className="object-cover w-full min-h-scren"
        key={imgURL}
      />
    </div>
  );
}
export default Background;

I’ve tried if statements and functions, but nothing is working, I’ve found this current template that was working with videos, I’ve tried to change it to use images, but I can’t achieve it. I’m fairly new in coding, so I hope someone can help me.

.getDay() is not a function? [duplicate]

Forgive a C# developer rusty on his Javascript skills.

Getting the error “Uncaught TypeError: d.getDay is not a function
” when trying to call the following method. Can anyone see what I’m doing wrong?

function DefaultDueDate_OnLoad() {
    const currentDate = new Date();
    const currentHour = currentDate.getHours();
    let dueDate = currentDate; // Default to Same Day

    if (currentHour >= 17) // After 5:00 PM (add 2 working days)
    {    
        dueDate += 2;
        dueDate += AddDaysForWeekend(dueDate);
    }
    console.log(dueDate);
}

function AddDaysForWeekend(d) {
    const dayOfWeek = d.getDay();
    let additionalDays = 0;

    switch (dayOfWeek) {
        case 6: // Saturday
            additionalDays = 2;
            break;
        case 0: // Sunday
            additionalDays = 1;
            break;
    }
    return additionalDays;
}

Video player – modification for mobile JS/HTML/CSS [duplicate]

I am learning javascript and using the tutorial I created this player that works correctly on a computer (high resolution) and I would like to modify it so that it works correctly on a mobile as well. I don’t have much experience with js and I would like some advice on what to study in order to modify it. Above all, I want the preview display to work correctly when you place your finger on the timeline. Thanks in advance for the advice. I am attaching the link.

https://codepen.io/aaron1799/pen/MWVeRYY

Express Response not going through

I’m trying to access the Spotify access_token from Postman, but it doesn’t seem to be going through. When I try to submit a GET request on Postman for http://localhost:3001/access, I just get “server running”. Also, keeping the redirect request in ‘/login’ in mind, when calling a get request from the front end, would I call a request for http://localhost:3001/access or http://localhost:3001/login?

server.js

const app = express();
app.use(cors());
app.set('port', 3001);


app.get('/login', (req, res) => {
  const scope = 'user-read-private user-read-email';
  const state = Math.random().toString(36).slice(2,18);

  const auth_query_parameters = new URLSearchParams({
    response_type: "code",
    client_id: client_id,
    scope: scope,
    redirect_uri: redirect_uri,
    state: state
  });
  
  res.redirect('http://accounts.spotify.com/authorize?' + 
  auth_query_parameters.toString());
});

app.get('/access', (req, res) => {
  const code = req.query.code || null;
  const state = req.query.state || null;
  
  const state_mismatch = new URLSearchParams({
    error: 'state_mismatch'
  });

  if (state == null) {
    res.redirect('/#' + 
    state_mismatch.toString());
  }
  else {
    const authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        code: code,
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64')),
        'Content-Type': "application/x-www-form-urlencoded"
      },
      json: true
    };
    request.post(authOptions, (error, response, body) => {
      if (!error && response.statusCode === 200) {
        const access_token = body.access_token;
        res.send({
          'access_token': access_token
        });
      }
    });
  }
  res.send('hello');
})

app.get('/', (req, res) => {
  res.send('server running');
})

app.listen(3001);

How to use Next.js Image with parallax.js?

My site load a big image slowly: https://tikex-dev.com

This is the image: /young-people-dancing-tango-studio.jpg

The challange is, that <img> is created by parallax.js on client side. url is passed as a custom html tag with data-image-src

<section
    className="section-image light ken-burn-center"
    data-parallax="scroll"
    data-image-src="/young-people-dancing-tango-studio.jpg"
    style={{ background: 'transparent' }}
>

then here the js creates the <img>:

(this.$slider = t('<img />').prependTo(this.$mirror))
            : ((this.$slider = a.prependTo(this.$mirror)), (n = !0)),
            this.$mirror
                .addClass('parallax-mirror')
                .css({
                    visibility: 'hidden',
                    zIndex: this.zIndex,
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    overflow: 'hidden',
                })
                .attr('data-source-id', this.$element.attr('id'))

What if image is big? Shall I modify parallax.js, and create a <Image instead of an <img>? It would not do the server side rendering for different dimensions of the image, right?

What approch exist to speed up loading this big image and use it as a background image in a parallax effect?

Shall I convert manually a ‘normal’ size image, instead of the 15MB?

React hooks – Update item in list after edit

I’m new to React Hooks. I am trying to make a small crud app, with add, edit, delete.
I have some issues getting my edit function to work. When I click the edit, the input will add the values of the element that is clicked. But how do I update the item?

const [items, setItems] = useState<any>([]);
const [comment, setComment] = useState("");
const [amount, setAmount] = useState("");

const handleAddSubmit = (e: any) => {
    e.preventDefault();

    const newItem = {
        id: new Date().getTime(),
        comment: comment,
        amount: amount,
        preview: preview
    }
    setItems([...items].concat(newItem));

    setFile(null);
    setComment("");
    setAmount("");
};

 const editItem = (item: any) => {
    setFile(undefined);
    setComment(item.comment);
    setAmount(item.amount);
};

const deleteItem = (id: any) => {
    const updatedItems = [...items].filter((item) => item.id !== id);

    setItems(updatedItems);
}

return (
       <div>
        {items.map((item: any, index: any) => {
                return (
                    <div key={item.id}>
                        <div>{item.comment}</div>
                        <div>{item.amount} $</div>
                        <div onClick={() => editItem(item)}>Edit</div>
                        <div onClick={(e) => deleteItem(item.id)}>Delete</div>
                    </div>
                );
            })}

               <input
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                placeholder="Comment"
            />
            <input
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                type="number"
            />
            <button formAction="submit">Add</button>
        </div>

)

How to read a single bit from a Buffer in TypeScript?

I am aware that a similar question has already been asked before (see How to read a single bit buffer in node), but it seems none of the answers are helful. The first comment that has been accepted, stating to use buf.readUIntLE(), is not working since 2 arguments are expected, but 0 was provided.

Thus, I am currently trying to read a single bit (the 17th one) from a Buffer, but I can’t find a way to easily read it. I have been using buffer.readUInt16BE(0) to read the 4 first bytes of the Buffer and so far it works fine, but I need to assign the 17th bit to a variable.

Note: My Buffer data is Big-Endian and I am coding in TypeScript.

I thought about doing something like:

const myVar: number = parseInt(buffer.readUIntBE(4, 1).toString().slice(0,1));

in order to read, then stringify the 5th byte, then getting the first caracter and convert it into a number, but I find it very clunky.

Is there a simple way to achieve this ?

read all the files in a directory javascript

I want to open a directory which containes a lot of files. I need to copy same information from every file, so I should be able to do something like this:

readdir('directory_name', (err, files) => {
if (err)
    console.log(err);
else {
    files.forEach(file => {
        //copy what I want from the files
    })
}
})

The problem is that the console gives me “readdir is not a function” and in the node_modules folder, in the fs section, there is a “README.md” file with this: “This package name is not currently in use, but was formerly occupied
by another package. To avoid malicious use, npm is hanging on to the
package name, but loosely, and we’ll probably give it to you if you
want it.

You may adopt this package by contacting [email protected] and
requesting the name.”

I’m using Javascript on browser.

Is it possible to open the directory in another way with the same result?

I’m a beginner in JavaScript programming.

Get sprite sheet background position?

I have a table where each cell background is populated by sprites from a sprite sheet when the user clicks the cell.

#design_container td {
  border: solid 1px #333;
  border-width: 0 1px 1px 0;
  width: 15px;
  height: 15px;
  background-image: url("../img/material_sprite.png");
  background-repeat: no-repeat;
}
.material_58 {
  background-position: -192px -48px;
}

Now I am using html5 canvas to make a download image. How can I get the background-position of the cells?
I tried(and failed)

let x = document.querySelector('.material_58').style.backgroundPosition;
console.log(x); // returned nothing/blank

I assume that may be getting the background position of the actual element, not the position of the sprite sheet.
If something like that doesn’t work maybe something like get the actual class description and parse it?
Thank you for your help.

Cypress Error : Cannot read properties of undefined (reading ‘getters’)

I’m doing a component test with cypress 10.3 in a vue project

import { mount } from 'cypress/vue';
import MarcaModal from '@/views/Mantenedores/Marca.vue';

describe('Prueba de componente en search.vue', () => {
  it('Renderizar un mesaje', () => {
    const msg = 'Nuevo';
    mount(MarcaModal, {
      propsData: {
        msg,
      },
    });
    cy.get('data-tes="btn_nuevo').should('have.text', msg);
    cy.get('data-tes="btn_nuevo').should('be.visible');
  });
});

but I get the following error.

TypeError
Cannot read properties of undefined (reading 'getters')

My file.vue is

      axios
        .get(me.$store.getters.server_api + url, {
          params: {
            page: me.page,
            size: me.pageSize,
          },
        })

I have searched but I have not found the solution using vue and cypress, I must also say that the error appears using Jest
I hope you can help me

How can I extract object values from 3 nested json arrays by matched string object values from a separate array and then display it in html/javascript

I would like to match the “title” and “thumbnail” values from one json response array to the values in another response array and show them in an html list. Essentially I’m matching a multidimensional array by regEx to another array and then I’m trying to display the content in a list like the one at the bottom. Any help is appreciated.

Here is the 1st Array

jsonArray =

[
nestedArray_1 [
{
"position": "1",
"title" :"player 1",
"thumbnail: www.picuture.com/jpeg"
},
{
"position": "2",
"title" :"player 1",
"thumbnail: www.picuture2.com/jpeg"
};
],
nestedArray_2 [
{
"position": "1",
"title" :"player 2",
"thumbnail: www.picuture.com/jpeg"
},
{
"position": "2",
"title" :"player 2",
"thumbnail: www.picuture2.com/jpeg"
};
],
nestedArray_3 [
{
"position": "1",
"title" :"player 3",
"thumbnail: www.picuture1.com/jpeg"
},
{
"position": "2",
"title" :"player 3",
"thumbnail: www.picuture2.com/jpeg"
};
]
] 

Below is the the second array it needs to match to

array2 =

["player1_details", "player2_details", "player3_details"]

I would like to have a html list with the title and image values from the jsonArray and the player details from array2.

example:
<ul>
<li>player 1 </li><li>www.picuture1.com/jpeg" </li><li>player1_details </li>
<li>player 2 </li><li>www.picuture2.com/jpeg" </li><li>player2_details </li>
<li>player 3 </li><li>www.picuture3.com/jpeg" </li><li>player3_details </li>
</ul> ```

what does matter do in gray-matter in node js?

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

const postsDirectory = path.join(process.cwd(), 'posts');

//

...
...
...

//

export function getPostData(id) {
    const fullPath = path.join(postsDirectory, `${id}.md`);
    const fileContents = fs.readFileSync(fullPath, 'utf8');

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents);

    // Combine the data with the id
    return {
        id,
        ...matterResult.data,
    };
}

What does matter do in gray-matter in node js?

I am trying dynamic routing in Next.js, please explain the use of the matter() function.

How can I add custom attributes to all heading elements in WordPress?

How to change the heading tags <h1> to <h1 data-splitting> and <h2> to <h2 data-splitting> and <h3> to <h3 data-splitting> and <h4> to <h4 data-splitting> in WordPress?

How can I change them on all pages through hard coding or by change through JS/JQuery? (My pages are fully cached by Cloudflare CDN)

For hard coding, where should I look at, on theme files, or is it coded into the WordPress itself?

There are ID’s and classes such as <div id="nav"> and <div class="sidebar-box"> but what is the above type is called as? Is it same as <h2> + <data-splitting>?

This is required to add some animation effect to the headings – View on Codepen

Now how can I change heading tags?

I added this to the WordPress fuctions.php:-

 function enqueue_my_custom_script() {
    wp_enqueue_script( 'hjs', 'https://example.com/h.js', false );
}

add_action( 'wp_enqueue_scripts', 'enqueue_my_custom_script' );

The h.js has the following code:-

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

    $('h1, h2, h3, h4').attr('data-splitting', '');

});

But this doesn’t add the script to the head.

I even added it manually as <script async src="https://example.com/h.js"> but it does not gets show up in the head.

So I have added the JS file as an inline script in the head, now the script does shows up in the head section as inline JS but doesn’t change the <h1> to <h1 data-splitting> and <h2> to <h2 data-splitting>.

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

    $('h1, h2, h3, h4').attr('data-splitting', '');

});
</script

or as

<script>
jQuery.noConflict()(function($) {
    $('document').ready(function() {

        $('h1, h2, h3, h4').attr('data-splitting', '');

    });
});
</script>

Now the script is present in the head as inline JS but it does not change the heading tags.

Best way to create dynamic navigation on NextJS with firebase?

I’m looking forward to create a web app with NextJS and Google’s Firebase. The app has an admin panel and a public site. In the admin panel should have options to edit the public site’s navigation.

So I was thinking is it wise to have client-side fetching navigation data on each refresh or is there a better way to get dynamic and up-to date navigation data with as little API request as possible?