r/pythonhelp • • Aug 20 '24

Looking for an updated Jodel api

2 Upvotes

Hi. I'm looking for an API for Jodel. Latest I could find hasn't been maintained for 7 years. I would like to write a program to schedule posts.


r/pythonhelp • • Aug 11 '24

If else construction problem

2 Upvotes

Why this code always returns 'Remove 1 number' (the task is to return the missing integer)?

However if I remove else and last return it actually works

def missing_no(nums): # nums is range(0, 101)

for i in range(0, 101):

if i not in nums:

return i

else:

return 'Remove 1 number'

And also how do I write this code as a one-liner?

edit: valid one-liner or can be shorter? ([i for i in range(0, 101) if i not in nums])[0]


r/pythonhelp • • Aug 11 '24

YouTube API quota issue despite not reaching the limit

2 Upvotes

Hi everyone,

I'm working on a Python script to fetch view counts for YouTube videos of various artists. However, I'm encountering an issue where I'm getting quota exceeded errors, even though I don't believe I'm actually reaching the quota limit. I've implemented multiple API keys, TOR for IP rotation, and various waiting mechanisms, but I'm still running into problems.

Here's what I've tried:

  • Using multiple API keys

  • Implementing exponential backoff

  • Using TOR for IP rotation

  • Implementing wait times between requests and between processing different artists

Despite these measures, I'm still getting 403 errors indicating quota exceeded. The strange thing is, my daily usage counter (which I'm tracking in the script) shows that I'm nowhere near the daily quota limit.

I'd really appreciate any insights or suggestions on what might be causing this issue and how to resolve it.

Here's a simplified version of my code (I've removed some parts for brevity):

import os
import time
import random
import requests
import json
import csv
from stem import Signal
from stem.control import Controller
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
from datetime import datetime, timedelta, timezone
from collections import defaultdict
import pickle

SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

DAILY_QUOTA = 10000
daily_usage = 0

API_KEYS = ['YOUR_API_KEY_1', 'YOUR_API_KEY_2', 'YOUR_API_KEY_3']
current_key_index = 0

processed_video_ids = set()

last_request_time = datetime.now()
requests_per_minute = 0
MAX_REQUESTS_PER_MINUTE = 2

def renew_tor_ip():
    with Controller.from_port(port=9051) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)
        time.sleep(controller.get_newnym_wait())

def exponential_backoff(attempt):
    max_delay = 3600
    delay = min(2 ** attempt + random.uniform(0, 120), max_delay)
    print(f"Waiting for {delay:.2f} seconds...")
    time.sleep(delay)

def test_connection():
    try:
        session = requests.session()
        session.proxies = {'http':  'socks5h://localhost:9050',
                           'https': 'socks5h://localhost:9050'}
        response = session.get('https://youtube.googleapis.com')
        print(f"Connection successful. Status code: {response.status_code}")
        print(f"Current IP: {session.get('http://httpbin.org/ip').json()['origin']}")
    except requests.exceptions.RequestException as e:
        print(f"Error occurred during connection: {e}")

class TorHttpRequest(HttpRequest):
    def __init__(self, *args, **kwargs):
        super(TorHttpRequest, self).__init__(*args, **kwargs)
        self.timeout = 30

    def execute(self, http=None, *args, **kwargs):
        session = requests.Session()
        session.proxies = {'http':  'socks5h://localhost:9050',
                           'https': 'socks5h://localhost:9050'}
        adapter = requests.adapters.HTTPAdapter(max_retries=3)
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        response = session.request(self.method,
                                   self.uri,
                                   data=self.body,
                                   headers=self.headers,
                                   timeout=self.timeout)
        return self.postproc(response.status_code,
                             response.content,
                             response.headers)

def get_authenticated_service():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'PATH_TO_YOUR_CLIENT_SECRETS_FILE', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    
    return build(API_SERVICE_NAME, API_VERSION, credentials=creds)

youtube = get_authenticated_service()

def get_next_api_key():
    global current_key_index
    current_key_index = (current_key_index + 1) % len(API_KEYS)
    return API_KEYS[current_key_index]

def check_quota():
    global daily_usage, current_key_index, youtube
    if daily_usage >= DAILY_QUOTA:
        print("Daily quota reached. Switching to the next API key.")
        current_key_index = (current_key_index + 1) % len(API_KEYS)
        youtube = build(API_SERVICE_NAME, API_VERSION, developerKey=API_KEYS[current_key_index], requestBuilder=TorHttpRequest)
        daily_usage = 0

def print_quota_reset_time():
    current_utc = datetime.now(timezone.utc)
    next_reset = current_utc.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
    time_until_reset = next_reset - current_utc
    print(f"Current UTC time: {current_utc}")
    print(f"Next quota reset (UTC): {next_reset}")
    print(f"Time until next quota reset: {time_until_reset}")

def wait_until_quota_reset():
    current_utc = datetime.now(timezone.utc)
    next_reset = current_utc.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
    time_until_reset = (next_reset - current_utc).total_seconds()
    print(f"Waiting for quota reset: {time_until_reset} seconds")
    time.sleep(time_until_reset + 60)

def get_search_queries(artist_name):
    search_queries = [f'"{artist_name}"']
    if " " in artist_name:
        search_queries.append(artist_name.replace(" ", " * "))
    
    artist_name_lower = artist_name.lower()
    special_cases = {
        "artist1": [
            '"Alternate Name 1"',
            '"Alternate Name 2"',
        ],
        "artist2": [
            '"Alternate Name 3"',
            '"Alternate Name 4"',
        ],
    }
    
    if artist_name_lower in special_cases:
        search_queries.extend(special_cases[artist_name_lower])
    
    return search_queries

def api_request(request_func):
    global daily_usage, last_request_time, requests_per_minute

    current_time = datetime.now()
    if (current_time - last_request_time).total_seconds() < 60:
        if requests_per_minute >= MAX_REQUESTS_PER_MINUTE:
            sleep_time = 60 - (current_time - last_request_time).total_seconds() + random.uniform(10, 30)
            print(f"Waiting for {sleep_time:.2f} seconds due to request limit...")
            time.sleep(sleep_time)
            last_request_time = datetime.now()
            requests_per_minute = 0
    else:
        last_request_time = current_time
        requests_per_minute = 0

    requests_per_minute += 1

    try:
        response = request_func.execute()
        daily_usage += 1
        time.sleep(random.uniform(10, 20))
        return response
    except HttpError as e:
        if e.resp.status in [403, 429]:
            print(f"Quota exceeded or too many requests. Waiting...")
            print_quota_reset_time()
            wait_until_quota_reset()
            return api_request(request_func)
        else:
            raise

def get_channel_and_search_videos(artist_name):
    global daily_usage, processed_video_ids
    videos = []
    next_page_token = None

    renew_tor_ip()

    search_queries = get_search_queries(artist_name)
    
    for search_query in search_queries:
        while True:
            attempt = 0
            while attempt < 5:
                try:
                    check_quota()
                    search_response = api_request(youtube.search().list(
                        q=search_query,
                        type='video',
                        part='id,snippet',
                        maxResults=50,
                        pageToken=next_page_token,
                        regionCode='HU',
                        relevanceLanguage='hu'
                    ))

                    for item in search_response.get('items', []):
                        video_id = item['id']['videoId']
                        if video_id not in processed_video_ids:
                            video = {
                                'id': video_id,
                                'title': item['snippet']['title'],
                                'published_at': item['snippet']['publishedAt']
                            }
                            videos.append(video)
                            processed_video_ids.add(video_id)

                    next_page_token = search_response.get('nextPageToken')
                    if not next_page_token:
                        break
                    break
                except HttpError as e:
                    if e.resp.status in [403, 429]:
                        print(f"Quota exceeded or too many requests. Waiting...")
                        exponential_backoff(attempt)
                        attempt += 1
                    else:
                        raise
            if not next_page_token:
                break

    return videos

def process_artist(artist):
    videos = get_channel_and_search_videos(artist)
    yearly_views = defaultdict(int)
    
    for video in videos:
        video_id = video['id']
        try:
            check_quota()
            video_response = api_request(youtube.videos().list(
                part='statistics,snippet',
                id=video_id
            ))
            
            if 'items' in video_response and video_response['items']:
                stats = video_response['items'][0]['statistics']
                published_at = video_response['items'][0]['snippet']['publishedAt']
                year = datetime.strptime(published_at, '%Y-%m-%dT%H:%M:%SZ').year
                views = int(stats.get('viewCount', 0))
                yearly_views[year] += views
        except HttpError as e:
            print(f"Error occurred while fetching video data: {e}")
    
    return dict(yearly_views)

def save_results(results):
    with open('artist_views.json', 'w', encoding='utf-8') as f:
        json.dump(results, f, ensure_ascii=False, indent=4)

def load_results():
    try:
        with open('artist_views.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_to_csv(all_artists_views):
    with open('artist_views.csv', 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        header = ['Artist'] + [str(year) for year in range(2005, datetime.now().year + 1)]
        writer.writerow(header)
        
        for artist, yearly_views in all_artists_views.items():
            row = [artist] + [yearly_views.get(str(year), 0) for year in range(2005, datetime.now().year + 1)]
            writer.writerow(row)

def get_quota_info():
    try:
        response = api_request(youtube.quota().get())
        return response
    except HttpError as e:
        print(f"Error occurred while fetching quota information: {e}")
        return None

def switch_api_key():
    global current_key_index, youtube
    print(f"Switching to the next API key.")
    current_key_index = (current_key_index + 1) % len(API_KEYS)
    youtube = build(API_SERVICE_NAME, API_VERSION, developerKey=API_KEYS[current_key_index], requestBuilder=TorHttpRequest)
    print(f"New API key index: {current_key_index}")

def api_request(request_func):
    global daily_usage, last_request_time, requests_per_minute

    current_time = datetime.now()
    if (current_time - last_request_time).total_seconds() < 60:
        if requests_per_minute >= MAX_REQUESTS_PER_MINUTE:
            sleep_time = 60 - (current_time - last_request_time).total_seconds() + random.uniform(10, 30)
            print(f"Waiting for {sleep_time:.2f} seconds due to request limit...")
            time.sleep(sleep_time)
            last_request_time = datetime.now()
            requests_per_minute = 0
    else:
        last_request_time = current_time
        requests_per_minute = 0

    requests_per_minute += 1

    try:
        response = request_func.execute()
        daily_usage += 1
        time.sleep(random.uniform(10, 20))
        return response
    except HttpError as e:
        print(f"HTTP error: {e.resp.status} - {e.content}")
        if e.resp.status in [403, 429]:
            print(f"Quota exceeded or too many requests. Trying the next API key...")
            switch_api_key()
            return api_request(request_func)
        else:
            raise

def main():
    try:
        test_connection()
        
        print(f"Daily quota limit: {DAILY_QUOTA}")
        print(f"Current used quota: {daily_usage}")

        artists = [
            "Artist1", "Artist2", "Artist3", "Artist4", "Artist5",
            "Artist6", "Artist7", "Artist8", "Artist9", "Artist10"
        ]

        all_artists_views = load_results()

        all_artists_views_lower = {k.lower(): v for k, v in all_artists_views.items()}

        for artist in artists:
            artist_lower = artist.lower()
            if artist_lower not in all_artists_views_lower:
                print(f"Processing: {artist}")
                artist_views = process_artist(artist)
                if artist_views:
                    all_artists_views[artist] = artist_views
                    all_artists_views_lower[artist_lower] = artist_views
                    save_results(all_artists_views)
                wait_time = random.uniform(600, 1200)
                print(f"Waiting for {wait_time:.2f} seconds before the next artist...")
                time.sleep(wait_time)

            print(f"Current used quota: {daily_usage}")

        for artist, yearly_views in all_artists_views.items():
            print(f"\n{artist} yearly aggregated views:")
            for year, views in sorted(yearly_views.items()):
                print(f"{year}: {views:,} views")

        save_to_csv(all_artists_views)

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    main()

The error I'm getting is:

Connection successful. Status code: 404
Current IP: [Tor Exit Node IP]
Daily quota limit: 10000
Current used quota: 0
Processing: Artist1
HTTP error: 403 - The request cannot be completed because you have exceeded your quota.
Quota exceeded or too many requests. Trying the next API key...
Switching to the next API key.
New API key index: 1
HTTP error: 403 - The request cannot be completed because you have exceeded your quota.
Quota exceeded or too many requests. Trying the next API key...
Switching to the next API key.
New API key index: 2
Waiting for 60.83 seconds due to request limit...
An error occurred during program execution: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

[Traceback details omitted for brevity]

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Connection successful. Status code: 404
Current IP: [Different Tor Exit Node IP]
Daily quota limit: 10000
Current used quota: 0
Processing: Artist1
An error occurred during program execution: BaseModel.response() takes 3 positional arguments but 4 were given

[Second run of the script]

Connection successful. Status code: 404
Current IP: [Another Tor Exit Node IP]
Daily quota limit: 10000
Current used quota: 0
Processing: Artist1
Waiting for [X] seconds due to request limit...
[Repeated multiple times with different wait times]

This error message shows that the script is encountering several issues:

  • It's hitting the YouTube API quota limit for all available API keys.

  • There are connection timeout errors, possibly due to Tor network issues.

  • There's an unexpected error with BaseModel.response() method.

  • The script is implementing wait times between requests, but it's still encountering quota issues.

I'm using a script to fetch YouTube statistics for multiple artists, routing requests through Tor for anonymity. However, I'm running into API quota limits and connection issues. Any suggestions on how to optimize this process or alternative approaches would be appreciated.

Any help or guidance would be greatly appreciated. Thanks in advance!


r/pythonhelp • • Jul 30 '24

python assignment

2 Upvotes

i m studying computer science and i am first semester. i need help with python assignment.


r/pythonhelp • • Jul 20 '24

INACTIVE How To Run .Py program

2 Upvotes

i have been trying to run this python program, both on mobile and pc, but I can't figure out what to do. The instructions are not very clear.

could someone could possibly give me step by step instructions on how to run and use this script? https://github.com/rahaaatul/TokySnatcher

please and thank you


r/pythonhelp • • Jun 11 '24

Best options to create/update 100+ excel sheets

2 Upvotes

I created productivity reports for several departments in a hospital. I utilize a dashboard and do it manually once a month for like 30 employees. I am now beong asked to do it for close to 100 and desperately need to automate this process. I can create and export 3 or 4 excel reports that would contain this assortment of data in an unsummarized form. Pretty much the raw data. What would be my best approach for creating or updating these 100+ seperate employee excel productivity reports? Like am I just creating using my already formatted files and coding it to fill specific cells correlating with the month or metric or are there better ways to do this?


r/pythonhelp • • May 19 '24

Problem with doing prython projects

2 Upvotes

Hello I am currently trying to learn python by doing mini projects with youtube tutorials. My problem is, that nothing works in my codes, even tho i did the same exact things that were shown in the tutorial. For example the colors of some words are comletely different or theres no color at all sometimes. I am using python environment.


r/pythonhelp • • Apr 24 '24

Where do build dependencies get installed? Do you ever clean yours up?

2 Upvotes

I am starting to try out a bunch of python programs, and many of them have had me pip install -r requirements.txt, which floods my console with a tonnn of pre-req installs.

I've been a very minimalist person with my PC for years, and hate cluttering my PC with a bunch of software. I have used Windows for most of my life, so a lot of the python stuff I'm doing is a bit foreign.

What can I do to clean up all of these installed dependencies? If there's some that I still use down the line, I can download them again, but I want to at least know where they're going and how I can clean them.


r/pythonhelp • • Apr 21 '24

Pi Pico HID Disable USB Drive unless button is held.

2 Upvotes

I am struggling to get this to work since I'm not that familiar with python and arrays. If I had the buttons singled out I could do it but I want them in this array. I want it so that it has the usb drive disabled unless you hold a button when plugging it in. For testing I prefer that it disables usb on hold boot so that I don't end up locked out of editing it.

main.py below

import time
import board
import storage
from digitalio import DigitalInOut, Direction, Pull
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

led = DigitalInOut(board.LED)
led.direction = Direction.OUTPUT
led.value = True

kbd = Keyboard(usb_hid.devices)
cc = ConsumerControl(usb_hid.devices)
layout = KeyboardLayoutUS(kbd)

# list of pins to use (skipping GP15 on Pico because it's funky)
pins = [
    board.GP1,
    board.GP7,
    board.GP8,
    board.GP2,
    board.GP6,
    board.GP9,
    board.GP3,
    board.GP5,
    board.GP10,
]

MEDIA = 1  # this can be for volume, media player, brightness etc.
KEY = 2
STRING = 3
NEW_LINE = "NEW_LINE"

keymap = {
    (0): (KEY, [Keycode.CONTROL, Keycode.SHIFT, Keycode.ESCAPE]),  # 1 Task Manager
    (1): (KEY, [Keycode.F14, Keycode.F24]),  # 2 Discord
    (2): (KEY, [Keycode.WINDOWS, Keycode.G]),  # 3 Game Bar
    (3): (KEY, [Keycode.CONTROL, Keycode.SHIFT, Keycode.M]),  # Mute Discord
    (4): (KEY, [Keycode.CONTROL, Keycode.SHIFT, Keycode.D]),  # Deafen Discord
    (5): (KEY, [Keycode.F18]),  # 4
    (6): (MEDIA, [ConsumerControlCode.SCAN_PREVIOUS_TRACK]), # Previous
    (7): (MEDIA, [ConsumerControlCode.PLAY_PAUSE]),  # 8 Play/Pause
    (8): (MEDIA, [ConsumerControlCode.SCAN_NEXT_TRACK]),  # 7 # Skip
}
switches = [0, 1, 2, 3, 4, 5, 6, 7, 8]

for i in range(9):
    switches[i] = DigitalInOut(pins[i])
    switches[i].direction = Direction.INPUT
    switches[i].pull = Pull.UP

switch_state = [0, 0, 0, 0, 0, 0, 0, 0, 0]

if not switches[0].value:
    storage.disable_usb_drive()

while True:
    for button in range(9):
        if switch_state[button] == 0:
            if not switches[button].value:
                try:
                    if keymap[button][0] == KEY:
                        kbd.press(*keymap[button][1])
                    elif keymap[button][0] == STRING:
                        for letter in keymap[button][1][0]:
                            layout.write(letter)
                        if keymap[button][1][1] == NEW_LINE:
                            kbd.press(*[Keycode.RETURN])
                            kbd.release(*[Keycode.RETURN])
                    else:
                        cc.send(keymap[button][1][0])
                except ValueError:  # deals w six key limit
                    pass
                switch_state[button] = 1

        if switch_state[button] == 1:
            if switches[button].value:
                try:
                    if keymap[button][0] == KEY:
                        kbd.release(*keymap[button][1])
                except ValueError:
                    pass
                switch_state[button] = 0
    time.sleep(0.01)  # debounce

r/pythonhelp • • Apr 18 '24

Need hel[ with coding robot barista

2 Upvotes

Hello!

I'm new to python and i was coding a robot barista, but every time i awnser "good" it just closes.

Is anyone willing to help me with this problem?

Thank you!

P.S. English is not my first language and i had to translate my code so sorry if the talking in the code sounds a bit weird.

This is my python script:

#Robot barista:

import time

input()

print ("\n")

print("Hello, Welkom to Bob's coffee!")

time.sleep(2)

print("What's your name?")

name = input()

time.sleep(1)

print ("\nHello " + name + "!")

time.sleep(1)

mood = input("How are you doing?\n")

if mood =="good":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="Good":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="Good!":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood =="good!":

print("Oh, that's good to hear!\n")

time.sleep(1)

if mood == "bad":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "Bad":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "Bad!":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if mood == "bad!":

print("Oh, that's not nice to hear")

input ("Why are you doing bad?\n")

print("Hmm... I hope you will be ok soon!\n")

time.sleep(1)

a = input("Would you like something to Eat/Drink?\n")

time.sleep(2)

if a == "No":

print("Ok\nBye!")

time.sleep(1)

quit()

if a == "Yes":

print(" \n" * 100)

print("This is the menu:\n Latte, Black Cofee, Ice Cofee and Appele Cake")

time.sleep(1)

print("What would you like to order?")

input()


r/pythonhelp • • Apr 04 '24

SSO with FastAPI

2 Upvotes

Hello everyone,

I'm currently tackling a project that involves developing an internal tool for logging user actions within our startup. The twist? Our company relies heavily on Windows Single Sign-On (SSO) for authentication.

My goal is to seamlessly incorporate access to the tool for users already authenticated on their workstations, eliminating the need for additional login steps. However, to ensure the accuracy and effectiveness of our logs, I need a method to automatically capture user usernames upon accessing the application.

For the tech stack, I'm working with React (using Vite) for the front end and FastAPI for the backend.

Any insights or suggestions on how to smoothly retrieve usernames in this SSO environment would be greatly appreciated. Thank you for your help!


r/pythonhelp • • Mar 15 '24

Is it possible to find a missing comma in a string

2 Upvotes

To start. I am very new, inexperienced with computers and also have no knowledge of Python except what I have been told.

I have a massive list that a bot checks against, the more commas I add, the linger it runs. I think I am missing one or two and can't find it, it doesn't show up on any sytax sites or applications, I have been zooming in and carefully inspecting all lines or using find, searching for commas and then hitting the down arrow a bunch, going through the whole list. but I seem to be missing one. Is there a way that I can search for missing ones on a list?


r/pythonhelp • • Mar 01 '24

Predictive Analysis

2 Upvotes

Hi I am currently doing a predictive analysis project but I am completely stuck and don’t know where to turn. Nothing seems to be working correctly. If anyone could help me or give me examples of predictive code with solutions it would be greatly appreciated!


r/pythonhelp • • Jan 20 '24

Fictional Coding

2 Upvotes

Hello, I am a comic book writer and I am in need of a few lines of fictional python coding to make the scene a bit more realistic as I am not a programmer. The setup: a hacking group in the "real world" is trying to send a command to a super virus in the "Digital Realm" to erase our cyber hero called Cyberman. The super virus is named "YourDOOM". These are not the real names of the characters as the comic has not been issued yet. The super virus is becoming "sentient" and refuses to run the erase program. So what I need is a few lines of semi-believable code that shows the hacker group trying to send a command to the super virus known as Your Doom to erase our hero Cyberman but the super virus rejects the command, and that is what the hacker group receives back on their screen. Any help would be appreciated!


r/pythonhelp • • Jan 17 '24

Could someone say what is going on in my code

2 Upvotes

Hello,

I come here to be help by people because I can't complete my assignment by my own.

Im French so its normal if they are french word in the program.

The code (on Thonny):

import math  
def volume_tore():  
r = int(input("Entrez le rayon du 'petit cercle' : "))  
R = int(input("Entrez le rayon du 'grand cercle' : "))  
alpha = math.acos(-1)\*(R/r)  
Oi = math.asin(-1)\*(R/r)  
if R >= r > 0:  
S = 4 \* math.pi\*\*2 \* r \* R  
V = 2 \* math.pi\*\*2 \* r\*\*2 \* R  
elif r > R > 0:  
S = 4 \* math.pi \* r \* (R \* (math.pi-alpha) + r \* math.sin(alpha))  
V = math.pi \* r \* \[(math.pi + 20) \* r \* R + (4/3 \* r\*\*2 + 2/3 \* R\*\*2) \* math.cos(Oi)\]  
elif r > R == 0:  
S = 4 \* math.pi \* r\*\*2  
V = 4/3 \* math.pi \* r \*\*3  
return V  

The issue that appear :

Traceback (most recent call last):  
File "<stdin>", line 1, in <module>  
File "C:\\Users\\Eleve\\LibVol.py", line 18, in volume_tore  
V = math.pi \* r \* \[(math.pi + 20) \* r \* R + (4/3 \* r\*\*2 + 2/3 \* R\*\*2) \* math.cos(Oi)\]  
TypeError: can't multiply sequence by non-int of type 'float'  

Im just starting to do some Python so im sorry if theres some errors :)


r/pythonhelp • • Jan 04 '24

Unexpected space added when replacing text with emoticon

2 Upvotes

Whenever I replace a section of a string with a emoticon, I get a random space added a few characters further and if I continue to do those replaces, the character is pushed even further.

The replaces in the dictionary:

"[willpower]" : "πŸ—£οΈ",

"[intellect]" : "πŸ“š",

"[combat]" : "πŸ‘ŠπŸ»",

"[agility]" : "πŸ₯Ύ",

"[wild]" : "❓",

The replace code:

# Process all set replaces

for key in text_replaces:

message = message.replace(key, text_replaces[key])

The text before replacing:

*Revelation* - Choose two skills ([willpower], [intellect], [combat], or [agility]). Until the end of the investigation phase, each investigator gets +1 to...

The results I get after each replace (observe the space in the words "investigation", "phase" and "each"):

*Revelation* - Choose two skills (πŸ—£οΈ, [intellect], [combat], or [agility]). Until the end of the in vestigation phase, each investigator gets +1 to...

*Revelation* - Choose two skills (πŸ—£οΈ, πŸ“š, [combat], or [agility]). Until the end of the investigati on phase, each investigator gets +1 to...

*Revelation* - Choose two skills (πŸ—£οΈ, πŸ“š, πŸ‘ŠπŸ», or [agility]). Until the end of the investigation p hase, each investigator gets +1 to...

*Revelation* - Choose two skills (πŸ—£οΈ, πŸ“š, πŸ‘ŠπŸ», or πŸ₯Ύ). Until the end of the investigation phase, e ach investigator gets +1 to...


r/pythonhelp • • Oct 29 '23

Pygame Character controller

2 Upvotes

Hello - I'm trying to make a simple game character controller and I'm already using ChatGPT... I can't get this event to work. I'd like to have the character movement setup in a way so when the character clicks the left mouse button it stops the movement animation and plays the attack animation. But it freezes on the first frame. here is my code.

https://github.com/MrFlamingMonkeyHead/DungeonCrawler

Any help would be greatly appreciated! thanks!


r/pythonhelp • • Sep 26 '23

Exec and lists, it is not working.

2 Upvotes

I am trying to make a game with Turtle, (yes, I know about Pygame, but I'm too lazy). The game is supposed to be like the Steam game Virtual Circuit Board, but I want to make it myself. In the early stages of making it (AKA right now), I came across an issue of that exec isn't updating the turtle (t).

(YES, I KNOW THAT THIS IS NOTHING LIKE VCB, I AM IN EARLY STAGES)

Any help, both with my problem, and the whole things would be appreciated.

This is my code:

from turtle import Turtle as T, Screen as S, onkey, listen, mainloop
global t

t = T(visible=False)
screen = S()
screen.tracer(False)
t.speed(0)
t.lt(90)
t.color(0,0,1)
global commands
commands = []


def up():
    commands.append(compile('t.fd(10)','','exec'))

def down():
    commands.append(compile('t.lt(180)','','exec')); 
    commands.append(compile('t.fd(10)','','exec')); 
    commands.append(compile('t.rt(180)','','exec'))

def left():
   commands.append(compile('t.lt(90)','','exec')); 
   commands.append(compile('t.fd(10)','','exec')); 
   commands.append(compile('t.rt(90)','','exec'))

def right():
   commands.append(compile('t.rt(90)','','exec')); 
   commands.append(compile('t.fd(10)','','exec')); 
   commands.append(compile('t.lt(90)','','exec'))

def runCommands():
    global commands
    global t
    [exec(command,{'t':t}) for command in commands]
    commands = []


listen(); onkey(up,'Up'); onkey(down,'Down'); onkey(left,'Left'); 
onkey(right,'Right'); onkey(runCommands,'a'); mainloop(); screen.exitonclick()

r/pythonhelp • • Sep 04 '23

micropython, trying to load settings from a file but I have to load it twice in order for the variables to change

2 Upvotes

for example, I load the settings on startup outside my main loop by calling a def function which loads the settings into variables on startup just fine.

def Load_Settings():
global setting1
global setting2
global setting3
with open('settings.txt', 'r') as f:
    lines = f.readlines()        
    setting1= float(lines[0])
    setting2= float(lines[1])
    setting3= float(lines[2])
f.close()

Right after this I call Load_Settings() and everything is loaded on startup from the file.

Then, I'm sending a serial command to write settings to the file and save it, this works fine but when I call Load_Settings(), I actually have to write the data twice for anything to take effect. It's not a big deal, It's just driving me crazy trying to figure out why.

def rs485_recievestring():
  data = uart.read(64)  # Read up to 64 bytes from the serial port
  if data:
      data = data.decode().strip()  # Convert bytes to a string and remove leading/trailing whitespace
      try:
          # Sort Data by the starting letter
          if data.startswith("s"):
              data = data[1:]  # Remove the "s" prefix
              # Split the comma-separated values into a list
              global values
              values = data.split(',')
              if len(values) == 3:
                  s1, s2, s3 = values             
                  with open('settings.txt', 'r') as f:
                      lines = f.readlines()
                      lines[0] = str(s1) + '\n'
                      lines[1] = str(s2) + '\n'
                      lines[2] = str(s3) + '\n'
                  with open('settings.txt', 'w') as f:
                      for line in lines:
                          f.write(line)
                      #Refresh Settings    
                      Load_Settings()
              else:
                  print("Invalid Settings data format")

Any ideas why this would be happening? I'm using a few files and the Load_Settings def is at the top right after my declared variables.


r/pythonhelp • • Aug 01 '23

Use tkinter to choose two files and a directory and then run script

2 Upvotes

Hello I'm back! LOL.

I wrote some code that reads two csv files, does some calculations and then outputs a new csv file. I think I'll be running it myself mostly so this next part is more a luxury than a necessity, BUT...

I'd like to have it where when I run the .py file I get a Tkinter window with some elements. Ideally I'd like one button to choose file 'A' and use the file and location as a variable for later use; then a second button to choose file 'B' and use the file and location as a variable for later use; a third button to choose a location to save the final output csv file, saved as a variable for later use and finally a fourth button to kick off the main script. I wouldn't mind a little popup or message somewhere to confirm that the job was completed.

I was able to get the tkinter window open with a button that when clicked allows me to pick a file but I'm stuck on being able to use that as a variable later. I think I need to do some nesting and functions but I'm not really grasping that right now.

Any tips?


r/pythonhelp • • Jul 13 '23

Beginner - How to increment a 2 player rock, scissors, paper game until one person wins 3 games

2 Upvotes

I am not sure what I am doing wrong here but it stays on 'Round 1' no matter how many rounds you play.

print("Let's play ROCK PAPER SCISSORS! ")

p1score = 0 p2score = 0 p1 = input("Player 1 name: ") p2 = input("Player 2 name: ") counter = 1 while True: r=("R","ROCK", "rock", "Rock", "r") s=("S", "s", "Scissor", "scissor", "SCISSOR") p=("P", "p", "Paper", "paper", "PAPER") print() print() print ("Select your moves!") p1move = input("Player1 move>") p2move = input("Player2 move>") print("Round...", counter,+1)

if p1move in r and p2move in r: print(p1, p2,"Rocks and Rocks... it's a tie!")

elif p1move in r and p2move in p: print(p2, "Wins by wrapping the rock in the paper!" ) p2score += 1

elif p1move in r and p2move in s: print(p1,"Wins by breaking the scissors!! πŸ₯³") p1score += 1

elif p1move in p and p2move in r : print(p1,"Wins by wrapping Rocks with paper πŸ₯³") p1score += 1

elif p1move in p and p2move in p : print("Its a Draw πŸ₯Ί")

elif p1move in p and p2move in s : print(p2,"Win πŸ₯³") p2score += 1

elif p1move in s and p2move in r : print(p2,"Wins πŸ₯³") p2score += 1

elif p1move in s and p2move in p : print(p1,"Wins πŸ₯³") p1score += 1 else: if p1move in s and p2move in s : print("Its a draw again πŸ₯Ί ")

if p1score == 3 or p2score == 3 : print (p1,"has",p1score,"and",p2,"has",p2score)

break

else:

continue

r/pythonhelp • • May 08 '23

How to make markers different shapes according to x value in Seaborn Catplot?

2 Upvotes

I have a catplot with 4 categorical groups along the x axis, and right each grouping is a different colour on the catplot, but they're all circle markers (and I want each grouping to be a different shape of marker for accessibility reasons, e.g. colour vision deficiency). How can I do that?

dataframe = pd.read_csv(r"C:\Users\zoesh\Downloads\CatPlotCompare.csv")

print(dataframe.head())

print(dataframe.isnull().values.any())

isolation = dataframe["isolation"]

mainhouse = dataframe['mainhouse']

classroom = dataframe['classroom']

community = dataframe['community']

g = sns.catplot(data=dataframe,jitter=0, marker="o")

plt.ylabel("Airborne Concentration of SARS-CoV-2 (RNA copies/mΒ³)")

#make the y axis log scale

plt.yscale('log')

#plt.xlabel ("xlabel", fontsize=8)

#g.fig.get_axes()[0].set_yscale('log')

plt.savefig("catplot4", dpi=2000)

#fig.get_axes()[0].set_yscale('log')


r/pythonhelp • • Apr 24 '23

Problem with python packaging: ModuleNotFound: No module named 'NeuralBasics'

2 Upvotes

I'm building and packaging a small python module, and I succesfully uploaded to pypi and downloaded it. However, when I try to import it once installed I get this error:

ModuleNotFoundError: No module named 'NeuralBasics'

This is my file structure:

.
β”œβ”€β”€ MANIFEST.in
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ README.md
β”œβ”€β”€ setup.py
β”œβ”€β”€ src
β”‚   └── NeuralBasics
β”‚       β”œβ”€β”€ example2.jpeg
β”‚       β”œβ”€β”€ example.jpeg
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ network.py
β”‚       β”œβ”€β”€ test.py
β”‚       β”œβ”€β”€ trained_data.txt
β”‚       β”œβ”€β”€ training
β”‚       β”‚   └── MNIST
β”‚       β”‚       β”œβ”€β”€ big
β”‚       β”‚       β”‚   β”œβ”€β”€ train-images.idx3-ubyte
β”‚       β”‚       β”‚   β”œβ”€β”€ train-images-idx3-ubyte.gz
β”‚       β”‚       β”‚   β”œβ”€β”€ train-labels.idx1-ubyte
β”‚       β”‚       β”‚   └── train-labels-idx1-ubyte.gz
β”‚       β”‚       β”œβ”€β”€ info.txt
β”‚       β”‚       └── small
β”‚       β”‚           β”œβ”€β”€ t10k-images-idx3-ubyte
β”‚       β”‚           β”œβ”€β”€ t10k-images-idx3-ubyte.gz
β”‚       β”‚           β”œβ”€β”€ t10k-labels-idx1-ubyte
β”‚       β”‚           └── t10k-labels-idx1-ubyte.gz
β”‚       └── utils.py
└── tests

This is the content in my setup.py file:

from setuptools import setup, find_packages

setup(
    name="NeuralBasics",
    version="1.0.5",
    packages=find_packages(include=['NeuralBasics', 'NeuralBasics.*']),
    description='Neural network basics module. Number detection on images.',
    author='Henry Cook',
    author_email='[email protected]',
    install_requires=['numpy', 'alive_progress', 'Pillow', 'matplotlib', 'idx2numpy']
)

Contents of my __init__.py file:

from network import Network
from utils import process_image, process_mnist, interpret, show

__all__ = Network, process_image, process_mnist, interpret, show

This error occurs on multiple computers, and I'm sure it isn't an error with pypi. Thank you for your help in advance!


r/pythonhelp • • Apr 05 '23

How Should I Be Using β€œawait” for Coroutines

2 Upvotes

Hi all, so I'm playing with some code that originally was a discord bot For ChatGPT. I'm trying to strip it to just work with phrases via the terminal. everything was going ok until I removed the last chunk of discord code that waited for a discord user's input. The specific issues are on lines 119 & 147. I believe that this is my final hurdle to achieve my desired code. I have included my whole code minus the json file called "config.json" that contains my OpenAI key

import sys
import os
import logging
import logging.handlers
import openai
import json
from asgiref.sync import sync_to_async

def get_config() -> dict:
    import os
    # get config.json path
    config_dir = os.getcwd()
    config_name = 'config.json'
    config_path = os.path.join(config_dir, config_name)

    with open(config_path, 'r') as f:
        config = json.load(f)

    return config

config = get_config()
openai.api_key = config['openAI_key']

async def handle_response(message) -> str:
    response = await sync_to_async(openai.Completion.create)(
        model="text-davinci-003",
        prompt=message,
        temperature=0.7,
        max_tokens=2048,
        top_p=1,
        frequency_penalty=0.0,
        presence_penalty=0.0,
    )

    responseMessage = response.choices[0].text

    return responseMessage


class CustomFormatter(logging.Formatter):

    LEVEL_COLORS = [
        (logging.DEBUG, '\x1b[40;1m'),
        (logging.INFO, '\x1b[34;1m'),
        (logging.WARNING, '\x1b[33;1m'),
        (logging.ERROR, '\x1b[31m'),
        (logging.CRITICAL, '\x1b[41m'),
    ]
    FORMATS = {
        level: logging.Formatter(
            f'\x1b[30;1m%(asctime)s\x1b[0m {color}%(levelname)-8s\x1b[0m \x1b[35m%(name)s\x1b[0m -> %(message)s',
            '%Y-%m-%d %H:%M:%S'
        )
        for level, color in LEVEL_COLORS
    }

    def format(self, record):
        formatter = self.FORMATS.get(record.levelno)
        if formatter is None:
            formatter = self.FORMATS[logging.DEBUG]

        # Override the traceback to always print in red
        if record.exc_info:
            text = formatter.formatException(record.exc_info)
            record.exc_text = f'\x1b[31m{text}\x1b[0m'

        output = formatter.format(record)

        # Remove the cache layer
        record.exc_text = None
        return output

def setup_logger(module_name:str) -> logging.Logger:
    # create logger
    library, _, _ = module_name.partition('.py')
    logger = logging.getLogger(library)
    logger.setLevel(logging.INFO)
    # create console handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(CustomFormatter())
    # specify that the log file path is the same as `main.py` file path
    grandparent_dir = os.path.abspath(__file__ + "/../../")
    log_name='chatgpt_twitter_bot.log'
    log_path = os.path.join(grandparent_dir, log_name)
    # create local log handler
    log_handler = logging.handlers.RotatingFileHandler(
        filename=log_path,
        encoding='utf-8',
        maxBytes=32 * 1024 * 1024,  # 32 MiB
        backupCount=2,  # Rotate through 5 files
    )
    log_handler.setFormatter(CustomFormatter())
    # Add handlers to logger
    logger.addHandler(log_handler)
    logger.addHandler(console_handler)

    return logger


logger = setup_logger(__name__)
isPrivate = False

async def send_message(user_message):
    try:
        response = '> **' + user_message + '** - <@' + '> \n\n'
        response = f"{response}{await handle_response(user_message)}"
        await logger.info(
                f"\x1b[33mChatGPT\x1b[0m: {response}")
    except Exception as e:
        await print("> **Error: Something went wrong, please try again later!**")
        logger.exception(f"Error while sending message: {e}")

async def run_bot(user_message):
    logger.info(f'ChatGPT is now running!')
    logger.info(
        f"\x1b[31mPrompt\x1b[0m: {user_message}")
    
    await send_message(user_message)


def check_verion() -> None:
    import pkg_resources

    # init loggger
    logger = setup_logger(__name__)

    # Read the requirements.txt file and add each line to a list
    with open('requirements.txt') as f:
        required = f.read().splitlines()

    # For each library listed in requirements.txt, check if the corresponding version is installed
    for package in required:
        # Use the pkg_resources library to get information about the installed version of the library
        package_name, package_verion = package.split('==')
        installed = pkg_resources.get_distribution(package_name)
        # Extract the library name and version number
        name, version = installed.project_name, installed.version
        # Compare the version number to see if it matches the one in requirements.txt
        if package != f'{name}=={version}':
            logger.error(f'{name} version {version} is installed but does not match the requirements')
            sys.exit();

if __name__ == '__main__': 
    check_verion()
    Prompt = input("Enter Prompt: ")
    run_bot(Prompt)