Dynamic Routes in ReactJS

how to create dynamic routes integrated with menu management

Let’s say I have data like the following:
[{"menu_id": 1,"menu_name": "test","menu_url": "/","menu_status": true,"subMenus": [{"subMenu_id": 1,"subMenu_name": "Sub Test","subMenu_url": "/sub-test"}]}].

Then from the menu data, how do I connect it to the route directly?
an example of an expected route is that the route can perform a map function on its data so that the route can be like the following analogy:
const routes [{path: subMenu.subMenu_url /menu.menu_url}]


WordPress open accordion code snippet. Request failed with status code 418

I am very new to javascript and php.

I am trying to write script in the Code Snippets plugin for a wordpress site to make anchor links to accordions open the accordion.

For example, the URL https://challengingbehavior.org/pyramid-model/overview/resources/#generalResources when clicked, should open the page, then scroll down to and open the accordion ‘General Resources’ with ID #generalResources.

Here is the code I created

function add_this_script_footer(){ ?>

<script>

$(document).ready(function(){
var hash = window.location.hash;
if(hash){
var element = $(hash);
if(element.length){
element.trigger('click');
}
}
});

</script>

<?php }

add_action('wp_footer', 'add_this_script_footer'); ?>

When I try to activate the snippet, it gives me the error “Could not create snippet. Request failed with status code 418.”

screenshot of code with error

I found this online… https://wordpress.org/support/topic/could-not-create-snippet-request-failed-with-status-code-418/
But not knowing enough about code, I don’t know if this is my problem or something else.

If it matters…Dreamhost, WordPress 6.4.2, PHP 8.3.

Any help would be appreciated.

Connecting Deployment method (github) through api/code

I was wondering if anyone had any remote idea on how to automatically connect a deployment method through github but through code. I can spin up a server, with env variables, and get a build running, which is great, but I need that last crucial step of having the deployment method connected to specific repo and a branch of it without needing to manually do so.

To summarize, I have the apps already deployed with an initial one time build, and env variables setup, **but then I have to manually connect the deployment method to a repo on Github and enable automatic deploys. How can I automate this part? **

Deploy Method on heroku for Github

You can see what portion of the server I’m referring to in the picture below, and then also I’ll post my current code on how I spin up the server in javascript. Any help will be appreciated.

// Define an async function to deploy the app
export async function deployApp(name, envVariables, githubBranch) {
  try {
    // Create a new Heroku app
    const app = await heroku.post('/apps', {
      body: {
        name: name
      }
    });

    // Set config variables for the app
    for (const key in envVariables) {
      await heroku.patch(`/apps/${app.id}/config-vars`, {
        body: {
          [key]: envVariables[key]
        }
      });
    }

    // Deploy the code to the Heroku app
    // Note: This assumes that the code is hosted on a Git repository
    let tarballUrl = await fetchTar(githubBranch)
    let addGithub = await heroku.post(`/apps/${app.id}/builds`, {
      body: {
        source_blob: {
          url: tarballUrl
        }
      }
    });
    console.log("Add Github Results", addGithub)
  }catch(err) {
    console.log(err);
  }
}

‘/youtubei/v1/’ at “www.googleapis.com”, gives out a 405 error page

for some reason this url: https://www.googleapis.com/youtubei/v1/ gives out this:

  1. That’s an error.
    The request method GET is inappropriate for the URL /youtubei/v1/. That’s all we know.

and i tried:
https://www.googleapis.com/youtubei/v1/search?key=[api_key_goes_here] and it won’t work that way either and
i wonder why this give out a 405 error page?
the project im doing here is for innertube.

How to route a modal login/register form in React?

I’m working on my diploma project web site. There is a button on the main page which makes a modal window with a login form pops up. Also there is a button on this login form which makes a login form toggle to a register form in the same modal window. I struggled routing login modal window and register modal window.

MainPage.js

import React, { useState } from "react";
import "../App.css";
import Footer from "../Components/Footer";
import Navbar from "../Components/Navbar";
import Button from "../Components/Button";
import ModalLogin from "../Components/ModalLogin";
import RegisterModal from "../Components/RegisterModal";

const MainPage = () => {
  const [isModalOpen, setModalOpen] = useState(false);
  const [isLoginForm, setLoginForm] = useState(true);

  function authorize() {
    setModalOpen(true);
    setLoginForm(true);
  }

  function closeModal() {
    setModalOpen(false);
  }

  function toggleForm() {
    setLoginForm((prev) => !prev);
  }

  return (
    <div className="app-container">
      <div className="main-container">
        <Navbar />
        <div className="intro-section-container">
          <h1>
            Цифровая
            <br />
            образовательная платформа
            <br />
            “Название не придумал”
          </h1>
          <p>
            Откройте дверь в мир музыки с нашим электронным дневником.
            <br />
            Присоединяйтесь прямо сейчас!
          </p>
          <div className="intro-buttons-container">
            <Button color="button-primary" label="Войти" onClick={authorize} />
            <Button color="button-outlined" label="Подключить школу" />
          </div>
        </div>
        {isModalOpen &&
          (isLoginForm ? (
            <ModalLogin onToggleForm={toggleForm} onClose={closeModal} />
          ) : (
            <RegisterModal onToggleForm={toggleForm} onClose={closeModal} />
          ))
        }
      </div>
      <Footer />
    </div>
  );
};

export default MainPage;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import NoPage from './Pages/NoPage';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
        <Route path="*" element={<NoPage />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>
);

App.js

import "./App.css";
import MainPage from "./Pages/MainPage";

function App() {
  return (
    <MainPage />
  );
}

export default App;

I’ve tried different ways routing these forms, but none worked

Downloading a GeoJSON file from ORS API Call – JS Vanilla

I’m hunting high and low to try and get some answers to this.

I’m trying to make an API call to OpenRouteService to generate a geoJSON response.

I have a download button that calls the function buildPolygon.

How can I get the function to download the API call as a geoJSON file in JS vanilla?

function buildPolygon() {
    let request = new XMLHttpRequest();

    request.open('POST', "https://api.openrouteservice.org/v2/isochrones/driving-car");
    
    request.setRequestHeader('Accept', 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8');
    request.setRequestHeader('Content-Type', 'application/json');
    request.setRequestHeader('Authorization', 'My_Key_Here');
    
    request.onreadystatechange = function () {
      if (this.readyState === 4) {
        console.log('Status:', this.status);
        console.log('Headers:', this.getAllResponseHeaders());
        console.log('Body:', this.responseText);
      }
    };

    var coordstext = document.getElementById('coords').value;
    var range = document.getElementById('mileage2metres').value;
    var resID = document.getElementById('restoid').value;
    var rangetype = document.getElementById('polygontype').value;
    var rangetime = document.getElementById('drivetime').value;
    
    if (document.getElementById('drivemileage').checked) {
    const body = '{"locations":[['+coordstext+']],"range":['+range+'],"id":"'+resID+'","range_type":"'+rangetype+'"}}';
    } else { 
    const body = '{"locations":[['+coordstext+']],"range":['+rangetime+'],"id":"'+resID+'","range_type":"'+rangetype+'"}}';
    };

    request.send(body);
}

I’ve not been able to find a solution to pass the data to be able to download a file.

How to close with button

I am trying to figure out how to close this dialog modal. As of now, my JS code consists of

const emDialog = document.getElementById('emDialog');
const bookingBtn = document.getElementById('bookingBtn')

setTimeout(() => {
    emDialog.showModal()
},500);

As this opens the modal. I do have a close button which consists of just

 <div class="dlg-btn">
                <button class="cancelBtn" value="cancel" formmethod="dialog"><i class="bi bi-x-lg"></i></button>
            </div>

which does its job to close. However, im unsure how this exactly closes the dialog without anything else. I am attempting to have the dialog window close upon the click of an anchor tag (as the link is an api for booking, the dialog overlays the booking page).

I have tried including the value and form method within the <div>, <a>, and <button> however this doesnt work. I have also tried to do an event listener with the Element ID for all of those as well. However this reads a console error stating addEventListener is null. I have checked the syntax and everything was correct, however from what I have read it seems like it loads before the DOM? Im unsure, but I couldnt find any information on fixing it that I could understand anyway. Any recommendations and help would be appreciated. Here was my JS for the close button if youd want to check my work.

bookingBtn.addEventListener("click", function(e){
    e.preventDefault();
    emDialog.close();
    console.log("close");
});

Edit draggable points using Highcharts

I’ve seen examples online about the how to make draggable points in highcharts, but I can’t seem to find an example of how to have the draggable feature as a way to edit where the point is located, and how to use a textbox (tooltip) as a way to edit the data for the point as well. I’ve been reading up in the documentation and can’t seem to find a way. The only way I can think to make this happen is using the custom html table code in the tooltip function, but I can’t seem to get it to work. What I’m really wanting at the end of the day is to allow the user two methods of editing data points: either by dragging the point, or entering in the data into a field manually (preferably the tooltip when they hover over the data point). Does anyone have any suggestions or know if this is even possible? I’ve tried many searches online and in Stack Overflow and have not had any success finding someone who’s been able to do this yet…Your help is appreciated in advance as usual.

how to manipulate colors to quickly update many dots on html canvas

I wrote a simulation in js, and there’s an animation component.

There are a bunch of circles on an html canvas. I want to remove 1 circle.

Normally I just clear the canvas and redraw everything every frame.

Is there some way for me to remove that one circle by drawing a new circle over top of it ? Like in the way (if I am correct) that purple #f0f undoes green #0f0.

I’m struggling a bit with this on the canvas, so maybe I’m way off. But my thinking is, imagine a given pixel has the original color c0. And because of the circle I drew, it got hit with color c1. So now the pixel has the new color c2=f(c0,c1). I’m trying to get a color c3, such that when I layer c3 onto c2, I get c0, like c0=g(c3,c2).

The point is to save time by avoiding a redrawing of every point.

Anyhow, is this approach, or something similar, possible ?

Decryption JS i need help because i cant find how i can deobfuscate [closed]

Hello i want to know if you can help me to decrpy this project, the project is closed and the owner had delete all github and links to the discord so for me there is only this shitty code who i can’t decrypt.
I try everything but dont work but i know it’s possible because a man already do for similar code type please help me

Here is the paste bin because there is too character for stackoverflaw

Here is the pastebin
because there is too character
for stackoverflaw 
so my link is here
https://pastebin.com/raw/B7hGT9sQ

Achieving Human-Like Rotational Poses in 2D Graphics Similar to Bitstrips

I’m working on a 2D character rendering system and I’m trying to replicate the rotation system used in Bitstrips. Bitstrips allowed for 2D character rotation in 45-degree increments, presenting various views (e.g., front, front-left, left, back-left, back, etc.). I’m encountering difficulties in positioning the character’s body parts during these rotations.

For instance, when the character has extended limbs (such as arms spread out like a T-pose) and is rotated, the challenge arises in ensuring that the limbs appear correctly positioned relative to the body’s orientation:

Bitstrips seemingly achieved this by rotating around an imaginary third Z-axis while confined to a 2D environment, which, mathematically, I’m not entirely sure how to do.

I’m specifically seeking guidance on how to position and render these body parts to emulate a realistic rotation without distorting their proportions. The goal is to retain the anatomical accuracy and alignment of body parts as the character is rotated, offering the illusion of a fluid and lifelike rotation.

There is a video here which shows an example of rotating the character.

I would greatly appreciate any insights into how to code something like this, methodologies, or reference materials that could shed light on achieving this rotational effect in a 2D canvas or any similar implementations that mimic human-like rotations. Thank you for your assistance.

Middleware next can’t connect to mongo

The next code is a middleware for Next. The idea is read the subdomain and search into the database if the subdomain exists.

import { getValidSubdomain } from '@/lib/getValidSubdomain';
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import * as mongoDB from 'mongodb';
let cachedDb: mongoDB.Db = null;

export function middleware(req: NextRequest) {
  const host = req.headers.get('host');
  const subdomain = getValidSubdomain(host);
  console.log({subdomain})

  if(!subdomain) return NextResponse.next()
  console.log({MONGOURL: process.env.MONGO_URL})

   mongoDB.MongoClient.connect(process.env.MONGO_URL, {
     useNewUrlParser: true,
     useUnifiedTopology: true,
   })
     .then((client) => {
       const db = client.db();
     })
  
});
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: '/(.*)',
}

But when I try to connect to mongo, it throws me this error on console:

- error node_modules/bson/lib/bson/symbol.js (2:0) @ <unknown>
- error Cannot read properties of undefined (reading 'custom')

How to set the value of the data held by the variable rather than the variable itself?

Lets say I have variable x.

x is equal to document.querySelector('h1').textContent;

Is it possible to set the value of text content rather than reassigning the value of the variable using = or some other JavaScript operation? I know that I could just set x to document.querySelector('h1'); and reassign the text by doing x.textContent = 'Hello.' I’d just like to know if there is some operation to avoid that.

I’ve tried changing the variable type to let, const, and var.

When I do this

let x = document.querySelector('h1').textContent;
x = 'Hi.'

It only reassigns the x variable to hold the value ‘Hi.’
I wanna know if there’s a way to assign the textContent of h1 using the variable without having to change the value of the variable to hold just the h1 element.

I can’t come up with a google search query that gives back the results I want. “How to change the value of the data held in the variable rather than the variable” is the best I’ve come up with and nothing matches what I’m searching. Thanks.

How to send a whole prepared HTTP request in javascript?

I’ve got a prepared HTTP request like the following:

POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

licenseID=string&content=string&/paramsXML=string

I need to send this whole request to the destination in Javascript, and wouldn’t like to have to convert it to a JSON object, and then pass it to a function such as fetch. How can I do that?