Skip to main content

Posts

Showing posts with the label Web Apps

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

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

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