Javascript: this is undefined inside jquery click function

HTML:

<li><button class="myclass">click me</button></li>

Javascript:

$('.myclass').click(() => {
  let myvar = this;
  console.log(this.tagName);
})

Output in the console is undefined, but I expected button? I need a data-* attribute from that button (you’re looking at reduced/minimalized code), but I cannot even grab the element via this – why not?

nodejs fs.rm(path, { recursive: true, force: true }) throws “ENOTEMPTY: directory not empty”

import { existsSync } from "fs";
import fs from "fs/promises";

export async function makeFolder(path: string) {
if (existsSync(path)) {
try {
await fs.rm(path, { recursive: true, force: true });
} catch (e) {
console.log("ERROR", e);
}
}
await fs.mkdir(path, { recursive: true });
}

ENOTEMPTY: directory not empty

In the dist/resources folder there is a file called default_app.asar. When deleting the file manually the command works but when it’s restored by npm install the error is back. I checked and the file is not used by any process.

Javascript cookie function expiration not working if over 7 days

I have a function to generate a cookie with Javascript and one of the parameters it accepts is days until expiration. I am trying to pass 30 days into it, but it doesn’t seem to work with anything over 7.

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

const btn = document.getElementById('set-cookie');
btn.addEventListener('click', function() {
  console.log('setting cookie');
  createCookie('lorem','ipsum',30);
});
<button id="set-cookie">Set Cookie</button>

If I pass a smaller number, like 5, into the function it works as expected. But anything over 7 just defaults to 7. Any ideas?

dygraphs: Make X-Axis fit to element

how can i make the chart fit the parent element? So that Every Tick i specified in axes.x.ticker is visible. Not just when i pan. I want the whole thing resized to the parent element.

I cannot find an option for this.

My config’s options:

            {
            colors: getColors(),
            includeZero: true,
            connectSeparatedPoints: true,
            axes: {
                x: {
                    ticker(min, max, pixels, opts, dygraph, vals) {
                        let ticks = [];
                        ticks.push({
                            v: new Date('2009-07-12 00:00:00').getTime(),
                            label: '00:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 01:00:00').getTime(),
                            label: '01:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 02:00:00').getTime(),
                            label: '02:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 03:00:00').getTime(),
                            label: '03:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 04:00:00').getTime(),
                            label: '04:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 05:00:00').getTime(),
                            label: '05:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 06:00:00').getTime(),
                            label: '06:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 09:00:00').getTime(),
                            label: '09:00:00'
                        });
                        ticks.push({
                            v: new Date('2009-07-12 11:00:00').getTime(),
                            label: '11:00:00'
                        });

                        return ticks;
                    }
                }
            },
            legend: 'follow',
            legendFormatter: tooltipFormatter,
        },

How to improve “CORS Error” in JavaScript [duplicate]

I make a simple socket connection program between client(react) and server(express).
Here are my codes.

Client

import React, { useEffect } from 'react';
import io from 'socket.io-client';

const App = () => {
    useEffect(() => {
        const socket = io('http://localhost:5000'); // Adjust URL according to your server

        socket.on('connect', () => {
            console.log('Connected to server');
        });

        socket.on('disconnect', () => {
            console.log('Disconnected from server');
        });

        return () => {
            socket.disconnect();
        };
    }, []);

    return <div>Socket connection</div>;
};

export default App;

Server

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors'); // Import the cors middleware

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Use the cors middleware
app.use(cors());

io.on('connection', (socket) => {
    console.log('A client connected');

    socket.on('disconnect', () => {
        console.log('A client disconnected');
    });
});

const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

How can I resolve this error?

“Access to XMLHttpRequest at ‘http://localhost:5000/socket.io/?EIO=4&transport=polling&t=Otx5jx4’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

I want no-error code.

Unable to hear the recorded audio using this package, react-native-audio-recorder-player

Version of react-native-audio-recorder-player

3.6.4

Version of React Native

0.70.3

Platforms you faced the error (IOS or Android or both?)

Android(Android Studio emulator)

Expected behavior

Able to hear the recorded voice note from the recorder.

Actual behavior

After recording a voice note, when I click on play, it is not playing anything.

Steps to reproduce the behabior

Hello, everyone! I am attempting to run the example of this project. It builds without any errors, but after recording, it is not playing the audio back. I have not changed any code in the given example, and I am attaching the screencast for reference. I am new to this, so can anyone help me make it run? Thank you.

How can I optimize this specific part of my p5js code (using trig functions) to reduce lag while maintaining the visual effect?

So, my sketch is running okay on my laptop– I have a MacBook Pro 2021 with 16GB RAM, and my sketch runs ~30 frames per second. However, other people have tried to open my sketch on their own laptops and are experiencing severe lag to the point that some cannot run the sketch at all.

I identified a specific chunk of my code that is almost doubling the lag (when I remove it, I go back up to ~60 FPS), but I don’t know how to change it to reduce lag while also maintaining the visual it draws.

The problem code is the section labeled “yellow connectors” from lines 98-103.
I have tried changing the lines to points, which does make my FPS go from 30 to 60, but it obviously changes the way the yellow connectors look.

I want to change the lines to points, then alter how the points are coded so that the points still appear as a moving series of lines connecting the red and blue double helix.
Perhaps instead of applying a sin function to the yellow connectors, I could use a tan function, or something else?

I don’t know if this is even possible, but I need help!

p5.disableFriendlyErrors = true;

var si=0.1;
var hi=0.1;
let tenet;
let words;
 
function preload() {
  tenet = loadImage('proneil.jpeg');
  words = loadImage('tenetword.png');
}

function setup() {
  console.log('Move your mouse across the screen. Hold down on the "0", "9", or "8" keys on your keyboard to change up the visuals. Click and drag across the screen to change the POV.','Then try different combinations of clicking, dragging, and using your keyboard. Double click to reset. Have fun! :)');
  createCanvas(1000, 600, WEBGL);
  camera(0, 0, (height/1.4) / tan(PI/6), 0, 0, 0, 0.15, 1, 0);
  perspective(1050, width / height, 100, 2000);
  // learned from Coding Train video:
  // https://www.youtube.com/watch?v=BW3D9WwalQE&list=PLRqwX-V7Uu6bPhi8sS1hHJ77n3zRO9FR_&index=6
  blendMode(BLEND);
}

function draw() {
  console.log(frameRate());
  
  //Color changing background
  let bg = map(noise(frameCount*0.01),0,1,-50,100)
  background(60-bg,0,10+bg);
  // Color changing code is from lines 70-73 of:
  // https://editor.p5js.org/EdCavett/sketches/r_JeOy-v
  
  noFill();
  
  //White noise background
  for (var a=0; a<=width*2; a++) {
      strokeWeight(1);
      stroke(255,255,0);
      point(a-650, random(height*3)-1000);
    }
  // Edited from Coding Train video:
  // https://www.youtube.com/watch?v=y7sgcFhk6ZM
  
//BACKGROUND WAVES
  //Continuous sin wave animation
  for (var x=1; x<=height+3000; x=x+5) {
    
    let twist = map(mouseX,0,1000,3*PI,PI)
    
    if (keyIsPressed===true && key==='0') {
      rotateY(PI);
    } else if(keyIsPressed===true && key==='9') {
      rotateY(twist/mouseY);
    } else {
      rotateY(PI*2)
    }
    // Pressing the '0' and '9' keys on the keyboard allows user to rotate the scene in different ways to create cool visuals.
    // https://p5js.org/reference/#/p5/keyIsPressed
    
      var j=(x+hi)/95;
      var z = cos(j*1.4);
  // Base loop from Claire
  // https://editor.p5js.org/clairez/sketches/7CTJFKiO-
  // Changed to sin() & some values changed
  
      //purple shadow
      strokeWeight(18);
      stroke(100,120,150,50);
      point(x-3000, z*height/-3,0);
      
      //red blue strands
      strokeWeight(15);
      stroke(200,200,0,30);
      point(x-2900, z*height/2,0);
      stroke(0,200,200,30);
      point(x-2800, z*height/-1.5,0);
//BACKGROUND WAVES END
  

//FOREGROUND DOUBLE HELIX START!!!!
      var p=(x+si)/95;
      var y = sin(p*1.55);
    
      noFill();

      //white shadow
      strokeWeight(45);
      stroke(255,10);
      point(x-2900, y*height/7);
      stroke(255,10);
      point(x-2900, y*height/-8);
      
      //yellow connectors
      strokeWeight(1);
      stroke(200,200,0);
      line(x-2900, y,x-2900, y*height/8.5)
      stroke(250,200,0);
      line(x-2900, y*height/-8.5,x-2900, y)
    
      //purple shadow
      strokeWeight(35);
      stroke(100,0,100,150);
      point(x-2900, y*height/7.5);
      stroke(100,0,100,150);
      point(x-2900, y*height/-7.5);
      
      //red and blue strands
      strokeWeight(30);
      stroke(255,0,0,150);
      point(x-2900, y*height/7);
      stroke(0,0,255,150);
      point(x-2900, y*height/-8);
    
    if (mouseIsPressed) {
      rotateY(PI);
        x--;
        si+=0.04;
        hi+=0.02;
    } else {
        let zoom1 = map(mouseY,0,600,1050,1049.9);
        perspective(zoom1, 1.6, 100, 2000);
    }
  // Changes animation speed and removes effect of zoom1 when mouse is pressed down.
//FOREGROUND DOUBLE HELIX END!!!!

if(keyIsPressed===true && key==='8') {
  push();
  blendMode(LIGHTEST); // https://p5js.org/reference/#/p5/blendMode
image(tenet,random(-140,-160),random(-110,-90),190,190);
  blendMode(BLEND);
  let shade = map(mouseX,0,1000,10,50)
  tint(255,shade);
image(tenet,random(-145,-155),random(-105,-95),190,190);
image(words,random(-15,-20),random(-100,-95),500,700);
  pop();
  //Photo and text with blend effect appear when "8" key is held down.
         }
    
    }
 si++;
 hi+=3;
 // Sets animation speed 
}

function mouseDragged() {
    let zoom = map(mouseX,0,1000,1050,1050.5) 
    camera(0, 0, (height/1.4) / tan(PI/6), mouseX/8, 0, 0, 0.15, 1, 0);
    perspective(zoom, width / height, 100, 1000);
  }
  // Changes camera perspective when mouse is dragged on the x-axis.


function doubleClicked() {
  camera(0, 0, (height/1.4) / tan(PI/6), 0, 0, 0, 0.15, 1, 0);
perspective(1050, width / height, 100, 1000);
  }
  // Resets camera perspective to normal when mouse is double clicked.

Horizontal div scrolling

I want to create an action using HTML, CSS and JS, when you scroll horizontally on a div.

This code which I found on w3Schools is what I was looking for, but I can not modify it to accept horizontal scroll. Basically it needs to indicate which image is on screen (1 or 2) using lets say dots.

window.onscroll = function() {
  myFunction()
};

function myFunction() {
  if (document.documentElement.scrollTop > 50) {
    document.getElementById("myP").className = "test";
  } else {
    document.getElementById("myP").className = "";
  }
}
body {
  font-size: 20px;
  height: 1500px;
}

#myP {
  position: fixed;
}

.test {
  background-color: yellow;
}
<h1>The onscroll Event</h1>

<p id="myP">
  If you scroll 50 pixels down from the top of this page, the class "test" is added to this paragraph. Scroll up again to remove the class.
</p>

I tried to modify the code from previous link and some others, but without success. This code seem to be the closest to what I need.

How can I return a value that I see in console.log [closed]

I am trying to return the variable found, so I can use the output, but I get an error every time. I am able to see the expected value in console.log. This is just being used to find the appropriate link in an email body but I am using dummy data in the array as an example.

let links = [
  "google.com",
  "facebook.com",
  "twitter.com",
  "outlook.com",
  "amazon.com"
];
let found = links.find(function (element) {
    return element.match("googl");
});
console.log(found);
//return found

Sorry, I have never used javascript and I am trying to use it for a quick logic app but its been very frustrating. I have tried researching it and I see that there is a difference between console.log() and return, but I dont really understand why I cant return ‘found’ still since I am defining it.

Value of an html button is marked as undefined when trying to make changes to a sqlite database

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Carrito</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
</head>
<body>

{% if 'user' in session %}
    <a href="/logout" class="button-54">Cerrar Sesión</a>
{% endif %}

<div class="dropdown">
    <button class="button-54" class="dropbtn">Ver carrito</button>
    <div class="dropdown-content">
        <table cellspacing="2" cellpadding="5">
            <thead>
            <tr>
                <th>Marca</th>
                <th>Referencia</th>
                <th>Precio</th>
            </tr>
            </thead>
            <tbody>
            {% for cart_item, libro in cart_items %}
                <tr>
                    <td>{{ libro.marca }}</td>
                    <td>{{ libro.ref }}</td>
                    <td>{{ libro.price }} €</td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
        <div align="center" style="padding: 10px; width: fit-content; margin: 0 auto; border: 1px solid black; background-color: white;">
            <h2 style="padding: 5px; margin: 0;">Precio total: {{ total_price }}</h2>
        </div>
    </div>
</div>

<div align="center">
    <h1 class="intro">scrapcatlog.com</h1>
</div>

<div class="buscador">
    <form method="post" action="/buscar" id="search-form">
        <div style="display: flex;">
            <input class="campo-busqueda" type="text" name="termino_busqueda" id="search-input" placeholder="Introduce un término de búsqueda">
        </div>
    </form>
</div>

<table cellspacing="2" cellpadding="5" id="search-results">
    <tbody id="search-results-body">
        {% for row in data %}
            <tr>
                <td>
                    <div>
                        <h2 class="titulo">Marca</h2>
                        <span class="datos">{{ row.marca }}</span>
                    </div>
                    <div>
                        <h2 class="titulo">Referencia</h2>
                        <span class="datos">{{ row.ref }}</span>
                    </div>
                    <div>
                        <h2 class="titulo">Precio</h2>
                        <span class="datos">{{ row.price }} €</span>
                    </div>
                    <form method="post" action="/add_to_cart">
                        <input type="hidden" name="libro_id" value="{{ row._rowid_ }}">
                        <button type="submit">Añadir al carrito</button>
                    </form>
                </td>
                <td>
                    <img alt="Imagen centrada" src="/static/images/{{ row.field7.lower() + '.png' }}" class="imagen-red" loading="lazy">
                </td>
            </tr>
        {% endfor %}
    </tbody>
</table>

<script>
const searchInput = document.getElementById('search-input');
    const searchResults = document.getElementById('search-results-body');

    searchInput.addEventListener('input', function () {
        const searchTerm = searchInput.value;
        fetch(`/buscar?termino_busqueda=${searchTerm}`)
            .then(response => response.json())
            .then(data => updateTable(data));
    });

    function updateTable(results) {
        // Actualizar dinámicamente la tabla con los resultados
        searchResults.innerHTML = '';
        results.forEach(row => {
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>
                    <div>
                        <h2 class="titulo">Marca</h2>
                        <span class="datos">${row.marca}</span>
                    </div>
                    <div>
                        <h2 class="titulo">Referencia</h2>
                        <span class="datos">${row.ref}</span>
                    </div>
                    <div>
                        <h2 class="titulo">Precio</h2>
                        <span class="datos">${row.price} €</span>
                    </div>
                    <form method="post" action="/add_to_cart">
                        <input type="hidden" name="libro_id" value="${ row._rowid_ }">
                        <button type="submit">Añadir al carrito</button>
                    </form>

                </td>
                <td>
                    <img alt="Imagen centrada" src="/static/images/${row.field7.toLowerCase() + '.png'}" class="imagen-red" loading="lazy">
                </td>
            `;
            searchResults.appendChild(newRow);
        });
    }
</script>

</body>
</html>

I’ve been working on a project similar to a catalog where I can add items to the cart. I’ve encountered an issue with dynamically generating a form in JavaScript.

In my HTML code, I have a table generated using Jinja2 template engine which displays items retrieved from a database. Each row contains a form with a hidden input field for libro_id.

Here’s a simplified example of my HTML structure:

<form method="post" action="/add_to_cart">
  <input type="hidden" name="libro_id" value="{{ row._rowid_ }}">
  <button type="submit">Añadir al carrito</button>
</form>

In my JavaScript function updateTable, I’m dynamically creating rows for the table based on the data retrieved from the server. However, when I try to assign a unique identifier _rowid_ to each row, it works fine visually, but the libro_id value in the form is marked as undefined, preventing items from being added to the cart.

Here’s the relevant part of my JavaScript code:

<form method="post" action="/add_to_cart">
    <input type="hidden" name="libro_id" value="${row._rowid_}">
    <button type="submit">Añadir al carrito</button>
</form>

I’ve tried various approaches, including iterating through the results array using a for loop, but haven’t been able to resolve this issue. Could someone please assist me in identifying what might be causing this problem and how to fix it? I’m using Flask with Python for server-side processing and SQLite for the database.

Creating Mocha test suites programmatically

I’m currently initializing a Mocha instance, to which I add files:

const mocha = new Mocha({
  ui: "tdd",
  color: true,
});

const testsRoot = path.resolve(__dirname);

mocha.addFile(path.resolve(testsRoot, "one.test.js"));
mocha.addFile(path.resolve(testsRoot, "two.test.js"));

mocha.run(...);

This obviously works as expected, as Mocha will require each file.

However, I’m now switching to generating JS code via Kotlin, which will output a single .js file.
The addFile approach becomes impossible.

I’m thus looking for a solution similar to:

const mocha = new Mocha({
  ui: "tdd",
  color: true,
});

// Made up code
mocha.addSuite("My suite", () => {
  suite.test("my test", () => {
    // ...
  });
);

mocha.run(...);

Does Mocha offer an API that can help for this use case?

How to put the countdown time into a localstorage that even if i refresh the webpage it will still continue and wont rollback

enter image description here

This is the image of what i make after clicking the button the countdown will start to count depends on the value of $time_start but the problem is that it will automatically “Time’s Up” and if i use also the other one source it will countdown but the problem is that if i refresh the countdown will rollback the time.

I want is that if i click the button the remaining time will start to countdown based on the value of $time_start for example in the $time_start i have the value of 00:11:43 then it will convert to a countdown time like 11minutes and 43 seconds then even if i refresh, it will still continue countdown without going back to 11:43 then if it reach 00:00:00 then thats the time that the Time’s Up will appear.

How to match all double quotes inside double quoted values?

Let’s say we want to convert this string to JSON:

let x = '{"my_text":"hello "world"","test2":"tree","blue":"red "yellow","orange":"green, purple "cyan""}';

I have a regex that matches all double quotes inside double quotes, except for the ones around cyan.

/(?<=:"([^,"]*))"(?=([^,]*)",)/g

If I am correct, it is because [^:"] excludes either : or ", while I want to exclude them sequentially (:") from the positive lookbehind.

Now I’ve thought about doing a negative lookbehind after the positive lookbehind, but it’s not matching and I’m not sure why:

/(?<=:")(?<!(.*):"(.*))"(?=([^,]*)",?)/g`

Am I missing something? How do I match all double quotes inside double quoted values?

ActionCable connect method not working with functions?

Context:
I use ActionCable in order to synchronize clients interface depending on events.
If a client lost his connection during broadcast on the server-side, the disconnected client won’t be able to catch on once reconnected.
I am currently trying to solve this problem with an event on the client side asking the server if they are up to date.

Problem:
I am using the “connected” method which is supposed to call a function but it does not work, even if the connection is successful with the server.

this.channel = createConsumer().subscriptions.create({
  channel: "GameChannel", id: this.gameIdValue,
  received: data => this.#handleData(data),
  connected: () => console.log('hello') // No message displayed
});

this refers to the Stimulus context.

Versions:
ActionCable version: 7.1.3,
Chrome version: 122.0.6261.69 (arm64)

Any clue about this problem?

An exception to the problem is that the following code works fine:

this.channel = createConsumer().subscriptions.create({
  channel: "GameChannel", id: this.gameIdValue,
  received: data => this.#handleData(data),
  connected: console.log('hello') // The message is displayed
});

I tried using this.channel.connect, this.channel.online and also using another function defined in the stimulus context… not working

importing data to another site with wordpress php [closed]

I purchased a theme and plugin with all rights and only the URL information of the established websites should come to me, it does not matter if it is a google sheets table or a txt file on any of my servers. how can I do that?

I should receive information about the sites where my theme and plugin are installed. I just want to know which site it was installed on.