Skip to main content

Posts

Showing posts from January, 2024

Python Pygame Physics Simulation Collison Not Working [duplicate]

I am trying to make a physics simulation using pygame but the collision is having problems. It gets shaky whenever there is a collision with another block because gravity is applied, but Rect collision only works when it is a pixel or more. I tried to make it so gravity = 0 for every block when it collides at a slow enough velocity, but that causes the blocks to hover due to certain collisions. Sorry for the whole file I do not even know where to start to fix my problem. import pygame import math # pygame setup pygame.init() screen = pygame.display.set_mode((1280, 720)) clock = pygame.time.Clock() running = True dt = 0 swap = 1 enemy_rect = pygame.Rect(500,500,20,20) objects= [[600,300,20,20,0,1.57,10,'blue',.2]] object=pygame.draw.rect(screen, 'blue', (600,300,20,20)) walls= [[0,700,1300,99999,0,0,99999]]#,[200,300,100,200]] while running: # poll for events # pygame.QUIT event means the user clicked X to close your window for event in pygame.event.get():...

Plot lines using vertices and faces in matplotlib

I would like to plot 2 circles with differents radius using matplotlib given their faces and vertices. This is my code to define the circles and to plot them. r2,r3=2,3 n_t3=5 n_t2=n_t2 theta_t3=torch.linspace(0,2*torch.pi,n_t3,device=torchdeviceId) VT3 = torch.stack((r3*torch.cos(theta_t3),r3*torch.sin(theta_t3)),dim=1) theta_t2=torch.linspace(0,2*torch.pi,n_t2,device=torchdeviceId) VT2 = torch.stack((r2*torch.cos(theta_t2),r2*torch.sin(theta_t2)),dim=1) VT=torch.vstack((VT2,VT3)) FT3 = torch.cat((torch.arange(0,n_t3-1).reshape(n_t3-1,1),torch.arange(1,n_t3).reshape(n_t3-1,1)),dim=1) FT2 = torch.cat((torch.arange(n_t3,n_t3+n_t2-1).reshape(n_t2-1,1),torch.arange(n_t3+1,n_t3+n_t2).reshape(n_t2-1,1)),dim=1) FT=torch.vstack((FT2,FT3)).to(torchdeviceId) xt, yt = ( VT[FT,0].detach().cpu().numpy(), VT[FT,1].detach().cpu().numpy(), ) plt.figure() plt.plot(xt,yt,label='target',marker='x',markersize=10,alpha=0.2,lw=10); plt.show() But i have this weird result whe...

discord embed freezes on 2nd execution

I have a problem with a slash command, with an embed actually. When I run the slash command, I get an embed with a button with a label "xN" (where N - any number from 1 to 99). This embed gets edited every 2 seconds, and the button's label and id increase by 1. If I click the button, callback function is called, some logic gets executed in the callback function and the main function stops. And it all works as intended, until 2nd try and all the following. On 2nd try the embed just stops, nothing gets edited and button is not being changed, and when I click the button nothing happens. Here is the screenshot: On this screenshot the first /test run worked properly, embed was being edited every two seconds, button's label and id were increasing by 1 and when I clicked the button it edited the embed with "stop function" message from callback function and ended the function (maybe the function wasn't ended tho ??), but when I run it 2nd time, it just freez...

Why do the end and flush parameters affect how quickly python prints to the console?

I noticed that when using print() , these parameters significantly affected how quickly it got to the VSCode console, in ways that I do not understand. I used time.time to time some for loops counting to 100,000 with different parameters. No end character specified, flush=false : 13.01 s No end character specified, flush=true : 13.97 s Why did this take longer than with the buffer? It seems like without the middleman it should go faster. End=" " , flush=false : 0.47 s This seems like it would be the same as the first case, but printing a space instead of a newline character, does the newline character take that long to print? Does it have some sort of special functionality in the console? End=" " , flush=true : 6.46 s Once again, why is it longer without the buffer? And this one was 13x longer?! Edit: I've only grown more confused: Printing with "end='\n'" takes even longer than the first one! I thought all it was doing by default was...

Python remove all posts and images (media) via Wordpress REST API

I feel like this should be something several other people already accomplished... to write a script that removes all sample data from a dev webpage using the Wordpress Rest API. Right now I try to automate posting images and posts, which works and leads to several of hundreds posts and images blowing up my database. Looking for a script doing that, neither ChatGPT nor browsing the web has provided any good answers. Any ideas where to look for scripts like that or how to write it yourself? source https://stackoverflow.com/questions/77850567/python-remove-all-posts-and-images-media-via-wordpress-rest-api

How to find element in QTreewidget in python?

How to select this element in Qtreewidget using the path to an element? How to select this element in Qtreewidget using the path to an element? The path is written as an example string: parent/parent/parent/parent/element I create a tree from the list of similar cloths in this way: def makeTree(self): self.treeWidget.clear() data = talkToViz(SimpleLabels.IPSerwer) FunctionsWindow.dataGlobal = data treeWidget = self.treeWidget items = {} def makeChild(parentPath, name): if '^^^' in name: FunctionsWindow.colorRow = True name = name.replace('^^^', '') if parentPath in items: parent = items[parentPath] else: if not parentPath: parent = items[''] = treeWidget else: splitPath = parentPath.split('/') parent = makeChild('/'.join(splitPath[:-1]), splitPath[-1]) if parentPath: ...

Trim with transition/fade using FFMPEG given a list of timestamps

I have a video and a list of timestamps that I want to filter. [ { "timestamp": [10, 20], "state": true }, { "timestamp": [30, 40], "state": false }, { "timestamp": [50, 60], "state": true }, { "timestamp": [70, 80], "state": true } ] I have a script like this to trim based on state. video_path = Path(video_in.name) video_file_name = video_path.stem timestamps_to_cut = [ (timestamps_var[i]['timestamp'][0], timestamps_var[i]['timestamp'][1]) for i in range(len(timestamps_var)) if timestamps_var[i]['state']] between_str = '+'.join( map(lambda t: f'between(t,{t[0]},{t[1]})', timestamps_to_cut)) if timestamps_to_cut: video_file = ffmpeg.input(video_path) video = video_file.video.filter( "select", f'({between_str})').filter("s...

Ploty heatmaps in subplots: how to set aspect ratio?

There is a similar question, but it only asks this for a regular figure. The respective answers do not work with subplots: https://stackoverflow.com/a/55239488/2215205 https://stackoverflow.com/a/71579181/2215205 px.imshow(df, aspect='equal') is ignored entirely with fig.add_trace() . Manipulating the figure layout in that respect is only applied to the first subplot, not all of them: import pandas as pd import plotly.express as px import plotly.graph_objects as go ## Example data df = pd.DataFrame([[0,0,0,0,0], [0,0,1,0,0], [0,1,2,1,0], [0,0,1,0,0], [0,0,0,0,0], ]) ## Subplots w/ go.Heatmap() layout = dict( # yaxis=..., # xaxis=..., # width=plot_width, # height=plot_height, # autosize=False, yaxis_scaleanchor="x" , # <---- only works in 1st subplot :( ) fig = go.Figure(layout=layout).set_subplots(rows=1, cols=2, subplot_titles=[...

Sonoma Python 3.8 was manually installed yet system shows 3.9.6

I have a mac running on Sonoma OS. I know it comes with python automatically, but I need a version 3.8 or less for some projects Im working on for school. However, I have installed 3.8 using homebrew which was installed, but the version of python didnt change. I've tried to update it using pyenv and I haven't been able to update the version. The crazy thing is that even though the version is stated as 3.9.6, if I look for it, I can't find it. Here is what I did so far: $ brew update $ brew install python@3.8 $ python3 --version Python 3.9.6 $ which python3 /usr/bin/python3 $ which python3.8 /usr/local/bin/python3 $ which python3.9 python3.9 not found $ brew install pyenv echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(pyenv init -)"' >> ~/.bash_profile source ~/.bash_profile Restart your shell so the path chan...

how can i fix this script for deleting bad words in chats

words_to_filter = ["badword1", "badword2", "badword3"] @bot.event async def on_message(message): print(f"on_message event triggered") # Add this line if message.author == bot.user: return for word in words_to_filter: if word in message.content: print(f"Bad word found: {word}") # check on_message event await message.delete() #message delete await message.channel.send(f"{message.author.mention}, դուք օգտագործել եք արգելված բառ ձեր հաղրոդագրությունում") # after deleting message send message return else: print('Falseee') # if script not working print 'Falseee' return await bot.process_commands(message) terminal output: I tried several options to check if all events are working the function of the code is to remove bad words in the message after running the code, when I send any word in the...

Line 22:6: React Hook useEffect has a missing dependency: 'auth.token'. Either include it or remove the dependency array

Error webpackHotDevClient.js:115 ./src/components/Layout/Routes/private.js Line 22:6: React Hook useEffect has a missing dependency: 'auth.token'. Either include it or remove the dependency array Line 22:7: React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked react-hooks/exhaustive-deps Private.js import { useState, useEffect } from "react"; import { useAuth } from "../../../context/auth"; import React from "react"; import { Outlet } from "react-router-dom"; import axios from "axios"; import Spinner from "../../spinner"; export default function PrivateRoute() { const [ok, setOk] = useState(false); const [auth] = useAuth(); useEffect(() => { const authCheck = async () => { const res = await axios.get("/api/v1/auth/user-auth"); if (res.data.ok) { setOk(true); } else { ...

Make GPT (Store) instructions output exact JavaScript code pattern answer [closed]

I have created a GPT app in the store, that outputs JavaScript Web Components. Since GPT is trained on old Web Components GPT is biased in its output. For example, because older blogs and even MDN say "use super() first in the constructor" , GPT outputs: constructor() { super(); const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props); let shadow = this.attachShadow({ mode: 'open' }); shadow.append( createElement( "style", innerHTML = `` )); } But uou can use JavaScript before super() because it sets and returns the this scope. I want it to write: constructor() { const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props); super() .attachShadow({ mode: 'open' }) .append( createElement( "style", innerHTML = `` )); } These are my instructions (related to this part of the code): * Include a `createElement(tag, props={})=>Object.assig...

How to replace a xml tag in a word document using python-docx and BS4

I am trying to remove all the text from a word document and leave just the images. I tried doing for p in document.paragraphs: p.text = '' but that removes everything so then i set a condition like: for p in document.paragraphs: if len(p.text)>0: p.text = '' it worked but did not save the images within paragraphs that included text, and it came with its own set of problems like empty bullet points and lists, etc. final solution i came up to is get all the paragraphs that have images using beautiful soup and then loop through the paragraphs using docx to remove those that dont have images. here is the problem, there are images that are inside paragraphs with words around them, I tried using beautiful soup to remove those texts like: soup = BeautifulSoup(p._p.xml , 'xml') for txt in soup.find_all('w:t'): txt.string.replace_with("") print(soup.prettify()) document.paragraphs[i] =...

Test if exception is thrown from a function that accepts user input

For an assignment I am trying to test whether a ValueError exception is raised depending on user input Here is my program that I am testing: def prompt_num_integers(): while True: try: # converting to int raises ValueError if input can't convert num_of_integers = int(input("How many integers do you want to store: ")) if num_of_integers < 1: raise ValueError except ValueError: print("Sorry, I didn't quite understand that.") continue else: return num_of_integers def prompt_integers(): # prompt user for number of integers then store that value into a variable num_of_integers = prompt_num_integers() # list for storing the integers integer_list = [] # integer for keeping count of current num of integers x = 0 while x < num_of_integers: try: # check if current num of integer equals total num o...

Backup uploaded and extracted, but at 99% of DB restoration, I am getting errors while WP migrating (plugin "All-in-one-migration")

I created an EC2 instance and installed PHP, MySQL , Apache and WordPress. I configured the below four files: sudo vim /etc/php/8.1/apache2/php.ini Change maximum file size upload limitation. Upload_max_filesize, post_max_size, max_execution_time, max_input_time, memory_limit and max_file_uploads sudo vim /etc/apache2/apache2.conf .htaccess by (<Directory /var/www/> AllowOverride All) sudo vim /var/www/html/wp-config.php Set you DB credential and define('FS_METHOD', 'direct'); sudo vim /etc/ssh/sshd_config Set password authentication Plugin ---- All-IN-ONE-MIGRATION Stage >> File Import 100% extract 100% Getting error in 99% of DB restoration GET https://35myip6/wp-admin/admin-ajax.php?action=ai1wm_status&ai1wm_import=1&secret_key=x2huyD7Y84n0&_=1704795105444 net::ERR_CONNECTION_REFUSED load-scripts.php?c=0&load%5Bchunk_0%5D=jquery-core,jquery-migrate,utils&ver=6.4.2:2 POST http://35.myip---18/...

How to evaluate promisified function in a browser context?

I need to inject third-party script into my page in playwright browser and then run js function. This work fine in native browser. Here is my index.html for testing: <script text="text/javascript" src="https://newassets.hcaptcha.com/c/2458d9b/hsw.js"></script> <script text="text/javascript"> const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmIjowLCJzIjoyLCJ0IjoidyIsImQiOiJuZVZwYWZrT0FRNnhNNUJCV3Vwa01HdWM0ZFVxWGVRS0YwY0xiRlA5L2MrTVo0WlkxaWlvT3hvY3lqRFE4RGJYT2R6MGFsVmFmeEhENVBIWHUyYWFjUHBNUXRIL0t1RUEvNndDRVVGNWhIQnJEMUNuNUZnd2JwdkdOUVJ1WkdXVXZrTlVFRnJhS0lnaW9uOTg1bHl2eW1jQmU4SmlES25oc3MrcklsdkVGU2lPSEpJQ1JpNVo3Mzd3RzM4eDlKZC9adGNBTngyaEdFYy91THpSaUE4OUNPdmU2RVdXTG4rTWNTTmxwVVE4WHVDTmt4akFwWmlodTJzN1B3L3daUzNRIiwibCI6Imh0dHBzOi8vbmV3YXNzZXRzLmhjYXB0Y2hhLmNvbS9jLzNhODRjMTUiLCJpIjoic2hhMjU2LXV4L0ZDV2M4ZS9vWTN1cGFINnRVeWpQN2hMbGhwR295OG45ZVdWdVdNS009IiwiZSI6MTcwNTMyOTA3MywibiI6ImhzdyIsImMiOjEwMDB9.lZsCbqodE16TzXJclh4oYIVHmJH12zV23...

NameError: name 'run_gui_update_in_thread' is not defined

Can someone tell me whats wrong with my code, whenever i delete something, a new error pops up the code is a dumpster fire to be honest. tkinter is having errors with simple task, most of the pip installs aren't required, and the code doesn't connect to the plc. The task the code is supposed to connect to the plc and give the status of the tag into microsoft SQL server management Studio. Would very much appreciate any ideas or help. Thanks. import threading import tkinter as tk from tkinter import ttk import datetime import time import logging import pyodbc from pylogix import PLC import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import tkinter as tk import threading # ... other necessary imports ... # Define global variables root = None tree = None plc_thread = None running = False # Flag to control the PLC reading thread def read_and_write_plc_data(): """Read data from PLC and write to database.""" global runn...

No python virtualenv is available error when running nodeenv -p

I have installed nodeenv for node.js and virtualenv for python and would like to link both by using the command nodeenv -p in virtualenv. I get this error No python virtualenv is available. any ideas what my be missing. the virtualenv has it all and i having running django in it. I tried to install and reinstall but it did not work. I am using MAC OS SONOMA source https://stackoverflow.com/questions/77813024/no-python-virtualenv-is-available-error-when-running-nodeenv-p

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory - removing sourcemaps still fails

Our team has a CRA application and we are using the following script to build locally and in bitbucket pipelines node --max-old-space-size=8192 scripts/build.js We are all getting this error now with our source code FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory 1: 0x111336665 node::Abort() (.cold.1) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 2: 0x11002f1c9 node::Abort() [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 3: 0x11002f3ae node::OOMErrorHandler(char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 4: 0x1101a41d0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 5: 0x1101a4193 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 6: 0x1103458e5 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/apple/.nvm/versions/...

How do I show a error message if no product is found?

I have a search.js file that reads a json file and retrieves information about some products, and then displays it in the page. I am trying to show a error message if no product is found when searching, and this part is almost working. If a search for a non-existent product, the error message appears correctly: enter image description here The problem is, if I search for a product that the name isn't similar to another one, the error still appears.. for example: enter image description here enter image description here Json file structure is like this: [ { "nome": "Carro", "apelido": "ft.car", "desc": "descrição", "img": "/img/carro.png", "link": "/pag/carro.html" }, { "nome": "Carreta Bi-Trem", "apelido": "ft.big.truck", "desc": "descrição", ...

Sorting data / refresh page with new query - Django5 ListView

I am trying to perform a query on the same page using Django. After selecting data from the dropdown and clicking the button, the information should be filtered accordingly. However, I couldn't find a solution to get the data after selecting from my dropdown and will refresh the page using Django. Is this possible? Here's my views.py class DocListView(ListView): model = Document template_name = 'docs/documents.html' paginate_by = 5 context_object_name = 'doc_list' def get_queryset(self): return Document.objects.all() source https://stackoverflow.com/questions/77806097/sorting-data-refresh-page-with-new-query-django5-listview

Can't delete "^M\n" from a .txt file

I'm generating a .txt from a SQL database. But for some reason, some of my data is not just plain text. My .txt file looks like this: PC001|1FSTFJ|BE21|Rooftop PC002|JVQ2F9|BE22|Basement PC003|JY1035W1|BE22|Basement^M\n I tried some Python and Bash scripts with the help of gpt, but it doesn't work: #!/bin/bash file_path="file.txt" sed -i 's/\^M\n//g' "$file_path" This script literally does nothing, and I don't understand why. And the Python script: def clean_file(file_path): try: with open(file_path, 'r') as file: lines = file.readlines() cleaned_lines = [] for line in lines: # Diviser la ligne en champs, en supposant qu'ils sont séparés par '|' fields = line.strip().split('|') # Nettoyer chaque champ individuellement cleaned_fields = [field.rstrip('M').strip() for field in fields] # Reco...

To read Ethernet frames on Canoe using Python

i am a beginner in automation to understand how to read ethernet frames from canoe trace using python. Please help me to understand and how to read either from command prompt or should i have to write driver level code to read ethernet frames? source https://stackoverflow.com/questions/77795772/to-read-ethernet-frames-on-canoe-using-python

Numpy: Accessing sub ndarrays with multiple index lists

I am trying to access (more precisely: add to) a subset of a numpy array using multiple index lists. However, what is working perfectly with slices, does not work as expected using arbitrary index lists: import numpy as np # this one works: A_4th_order = np.zeros( (4,2,4,2) ) sub_a = np.ones( (3,1,3,1) ) i = k = slice(0,3) j = l = slice(1,2) A_4th_order[i,j,k,l] += sub_a # this one doesn't: B_4th_order = np.zeros( (4,2,4,2) ) sub_b = np.ones( (3,1,3,1) ) i = k = np.array([0,1,2], dtype=int) j = l = np.array([1], dtype=int) B_4th_order[i,j,k,l] += sub_b How can I achieve this operation in an efficient and readable manner? source https://stackoverflow.com/questions/77793897/numpy-accessing-sub-ndarrays-with-multiple-index-lists

Why can't I put two while statements on top of each other?

I am fairly new to python, so this is probably a beginner mistake, but depending on how I order the while statements, it either doesn't load, or doesn't update time. import time clock = 0 Basically, when I put the while statements in this order, the code actually runs, but the second while statement never activates. while 1<2: x = inpu(input('What do you want to do?')); if x == "time": print(clock) else: print(x) while 2<4: time.sleep(5) clock += 1 When I put the while statements like this, the code just doesn't run. while 2<4: time.sleep(5) clock += 1 while 1<2: x = inpu(input('What do you want to do?')); if x == "time": print(clock) else: print(x) I didn't go into detail about inpu() , but it basically says, if you type ___ in the input, it will respond with ___. One of those options is "clock", which will print the clock value. Wh...

Getting a very simple stablebaselines3 example to work

I tried to model the simplest coin flipping game where you have to predict if it is going to be a head. Sadly it won't run, given me: Using cpu device Traceback (most recent call last): File "/home/user/python/simplegame.py", line 40, in <module> model.learn(total_timesteps=10000) File "/home/user/python/mypython3.10/lib/python3.10/site-packages/stable_baselines3/ppo/ppo.py", line 315, in learn return super().learn( File "/home/user/python/mypython3.10/lib/python3.10/site-packages/stable_baselines3/common/on_policy_algorithm.py", line 264, in learn total_timesteps, callback = self._setup_learn( File "/home/user/python/mypython3.10/lib/python3.10/site-packages/stable_baselines3/common/base_class.py", line 423, in _setup_learn self._last_obs = self.env.reset() # type: ignore[assignment] File "/home/user/python/mypython3.10/lib/python3.10/site-packages/stable_baselines3/common/vec_env/dummy_vec_env.py"...

how to solve this warning in python?

enter image description here the init .py, all the file in datasets can run successfully, but why the main.py says NoModuleNamed 'coco'?, the coco.py can run successfully either. By the way , the engine.py raises the same problem as main.py i tried to change the root path of the coco data, but it doesn't work, source https://stackoverflow.com/questions/77776068/how-to-solve-this-warning-in-python

How do I correctly resume a session for a user?

I've just started learning next.js (TypeScript) and I've run into a problem. I need to authorize a user to restore his session. The authorization key is a token that is stored in cookies. How to implement this task correctly? At the moment, I have simply created a component in which I have embedded RootLayout , and in the component itself I am already executing an API request to search for a user by token, but with this approach I get various errors. Perhaps there are some other options? 'use client'; import { fetcher } from '@/helpers/fetcher'; import { useUserStore } from '@/store/user'; import { QueryCache, useQuery } from '@tanstack/react-query'; import { deleteCookie, getCookie } from 'cookies-next'; import { useEffect } from 'react'; export default function Auth() { const { user, setUser } = useUserStore(); const rememberToken = getCookie('remember_token'); if (user == null && rememberToken !=...

Encode audio data to string (Flask) and decode it (Javascript)

I have a Python Flask app with the method shown below. In the method I'm synthesizing voice from text using Azure text to speech. @app.route("/retrieve_speech", methods=['POST']) def retrieve_speech(): text= request.form.get('text') start = time.time() speech_key = "my key" speech_region = "my region" speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=speech_region) speech_config.endpoint_id = "my endpoint" speech_config.speech_synthesis_voice_name = "voice name" speech_config.set_speech_synthesis_output_format( speechsdk.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3) synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=None) result = synthesizer.speak_text_async(text=text).get() if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: # Convert to wav audio = AudioSegment...

Recommend extraction api/library for better extracting all information in a pdf using Nodejs [closed]

What library or API is the best at extracting information in a PDF file in Nodejs. Things like text (how they properly are structured), images (couple with information on images like text if it got one), table etc... I'm aware of libraries like pdf-extract and the rest but most of them capabilities are limited to just extracting text and pretty much can't do other stuffs I mentioned above. Also, I don't want to mix many different libraries to do the tricks. So what do you suggest? Via Active questions tagged javascript - Stack Overflow https://ift.tt/aTZwn7q

Injecting React components into webpages using content scripts in browser extensions

I am creating a React-based browser extension and I am trying to inject a React component into webpages using content scripts. However, it seems like using React or ReactDOM prevents the content script from loading. Is there any to get around this issue? This is the code that I currently have. It seems like the content script only loads when React and ReactDOM is not used since nothing is logged to the console. import NavBar from "./NavBar"; import React from 'react'; import ReactDOM from 'react-dom'; console.log('Content script is running'); const container = document.createElement('div'); document.body.appendChild(container); ReactDOM.render(<NavBar />, container); Via Active questions tagged javascript - Stack Overflow https://ift.tt/yZtDo8N

Cannot read properties of null in SPA javascript when reading a form in another route

I have the below single page application, but when I go to the login route, and submit, the event listener for the form is not triggered And I get this error : Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at login?session%5Bemail%5D=fdf%40gmail.com&session%5Bpassword%5D=dfdf&session%5Bremember_me%5D=0:34:6 This is the home page <!DOCTYPE html> <html> <head> <title>Vanilla SPA Router</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="css/styles.css" /> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" rel="stylesheet" /> </head> <body> <div id="root"> <nav id="main-nav" class="sidebar"> <a href="/" onclick="route()">Home...

Javascript parse RSS which includes German characters

I am trying to load rss which has German characters included (ö, ä, ü...) xhrRequest.responseText already contains converted characters (\u00f ...) Without manually replacing is there to force right encoding so original characters stay visible? var url = 'https://apolut.net/feed/podcast/' xhrRequest = new XMLHttpRequest(); xhrRequest.onreadystatechange = function() { if (xhrRequest.readyState == 4) { } } xhrRequest.onerror = function(e) { }; xhrRequest.open('GET', url); xhrRequest.setRequestHeader("Content-Type", "text/xml"); xhrRequest.send(); I do have utf on the top of page: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> Via Active questions tagged javascript - Stack Overflow https://ift.tt/Aosi8g1