/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about all topics related to learning python.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

879,809 Subscribers

1

how to record a video from a webcam, with sound, from within python?

I am writing a python program for windows in which I want the user be able to quickly take a video from within the python app using the internal camera and microphone and then save the resulting video as an mp4, or similar.

The software needs to run on windows (specifically a surface tablet).

Obviously i googled first and found many, many tutorials on how to record video, but most of them without sound. Also all of them had the problem that the resulting video was badly synched and was timewarping around.

So far I tried CV2 and ffmpeg.

The latter via commandline and a separate ffmpeg.exe binary. This works in general, but has the same problem as all the CV2 solutions: audio and video are hardly in sync and the video speed is janky all over the video.

is there a better solution? Is this really this hard, or am i missing something here?

So far my code is this: (selecting cameras[1] and audio[0] is only specific to my test machine right now, this would later be dynamic...)

import subprocess
import re
import time

list_devices = ['../ffmpeg.exe', '-list_devices', 'true', '-f', 'dshow', '-i', 'dummy']

result = subprocess.run(
    list_devices, # Arguments
    capture_output = True, # Python >= 3.7 only
    text = True # Python >= 3.7 only
)

cameras = re.findall("\"(.*)\" \(video\)", result.stderr)
audios = re.findall("\"(.*)\" \(audio\)", result.stderr)

cam = cameras[1]
audio = audios[0]


record = ['../ffmpeg.exe', '-f', 'dshow', '-i', f"video={cam}:audio={audio}", '-vf', 'format=yuv420p', 'output.mp4']
recorder = subprocess.Popen(record, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, stdin=subprocess.PIPE)

time.sleep(30)

recorder.stdin.write('q')  # Simulate user pressing q key
recorder.communicate()
recorder.wait()

print('done')
0 Comments
2024/12/17
22:52 UTC

1

Really need some advice

Hey everyone . Almost 2 month ago I started pt penetrating online course .

First , network fundamentals went great got 96 in the test. Then , Linux fundamentals again went great 98 in the test.

Now Python..I feel like a stupid who can’t think properly . Learned about if, else, elife, list, and set . I understand the logic of everything I really do. And The basic behind it and what everything does.

But when it comes to combine those things ? Like when I need to solve some exercise? I’m stupid as hell I swear it’s like my mind is going blank and I don’t even know where to start. Like I put the first input and then BOOM . Don’t know where to go and what to write . Keep forgetting things , even the small ones who can help me with exercises

I can sit hours on reading the same things, I can practice and practice but still nothing when it comes to combining . I had up until now like 5 exercises, one I managed to solve alone , the rest i got frustrated and watch the teacher solve it . Something’s i say “yep we learned it why I didn’t think about it “ Sometimes “how the hell i should have known ?” And then after some times I’m like “yep I should have known” and you get the point.

What can I do ? I don’t want to give up but also I don’t want to keep study and get too deep in the course when I can’t solve exercises and when I keep forgetting those things .

Thanks and sorry for the long rant I’m frustrated as hell

1 Comment
2024/12/17
22:48 UTC

1

unittest word diff on strings

from unittest import TestCase

class TestSomething(TestCase):
    def test_something(self):
        self.assertMultiLineEqual('one two three', 'one three three')

produces the error message

AssertionError: 'one two three' != 'one three three'
- one two three
?      ^^
+ one three three
?      ^^^^

But I would find it more useful to see mismatches inline, like git --word-diff=color shows.

How can I use unittest and other libraries to do something like that?

1 Comment
2024/12/17
21:19 UTC

2

I am trying to get a option to put in a answer in my code that gives a diffrent output based on which if else statement is true. Why wont it work?

I'm beginner in coding and was practicing by myself. below is the code i wrote.

    print("the result of the operation is", sum)

    input_answer=input ("give the correct answer to see if you are worthy: ")

    magic=1000000000
    skill_level=0
    sum= magic*skill_level
    print(sum)

    if sum< 1:
        print("you are not worthy")
    else:
        print("You are worthy")
26 Comments
2024/12/17
21:08 UTC

0

I need help finding a python IDE

I had been using replit for school

but now replit is limited so I've been having problems with the IDE

Please could you tell me a python IDE which dosen't needs to be downloaded on the computer(because it's banned) so i need a IDE which allows me to create loads of python files and save them which also runs online instead of having to download it

14 Comments
2024/12/17
20:39 UTC

5

User and Password Interface Pt. 2

This is a continuation of a post I made earlier. I think I have a better grasp of while loops and if/else statements, but there are still a few kinks in my code.

The code is:

  1. print(‘Welcome to the USG Ishimura.’)
  2. user = input(‘Please enter your user ID: ‘)
  3. print(‘Welcome, ‘ , user)
  4. while True:
  5.   x = input(‘Please enter your passcode: ‘)
  6.   if x == ‘987413’:
  7.     if user == ‘Isaac Clarke’:
  8.       print(‘Access granted.’)
  9.        break
  10.   else:
  11.    print(‘Access denied. Please try again.’)
  12.  if x == ‘987319’:
  13.   if user == ‘Zachary Hammond’:
  14.       print(‘Access granted.’)
  15.        break
  16.  else:
  17.    print(‘Access denied. Please try again.’)
  18.  if x == ‘987665’:
  19.    if user == ‘Kendra Daniels’:
  20.      print(‘Access granted.’)
  21.      break
  22.  else:
  23.    print(‘Access denied. Please try again.’)

Everything’s working the way that I want it to, but when I put in Zachary Hammond or Kendra Daniels’ username and passcode, the terminal will print out ‘Access denied. Please try again.’ as well as ‘Access granted.’ Basically, both the if and the else statement are printing out at the same time. How can I correct this so only the if or the else statement will print out at once?

3 Comments
2024/12/17
20:33 UTC

2

Struggling with parsing a list.

I'm accessing a smart energy monitoring plug for monthly usage. The output I get is a single element list like this.

json_str is ['"== Emeter ==\\n== For year 2024 ==\\nMonth, usage (kWh)\\n11, 11.72\\n12, 21.292\\n"']

I just need to extract the number after nXX, where XX will be 01 through 12 for the different months. In this case I need the 11.72 and the 21.292, so I can add them and get my total usage.

5 Comments
2024/12/17
20:30 UTC

2

Learning Python best way

Hi guys! Im in love with python and so far i take p4e and the python crash course from coursera, i want to expand my little knowledge way more, i saw in Udemy a couple of courses "100 days of code" "python for data science and machine learning" and "python bootcamp from zero to hero" all 3 for arounf 68$ dollars, im more of a guy that learns by typing and messing with the program, you guys think those 3 udemy programs would be good or should i invest somewhere else?

2 Comments
2024/12/17
19:31 UTC

1

I have a Intro to Programming Python exam soon.

It will be a semester 1 exam and I'm stressing pretty hard on it, although it will be open note. Any good study guides or resources online to help me prepare?

Are these Quizlet sets useful resources? https://quizlet.com/188060105/intro-to-python-final-exam-flash-cards/

https://quizlet.com/398381641/introduction-to-programming-final-exam-review-python-flash-cards/

4 Comments
2024/12/17
19:07 UTC

6

Why does this happen?

EDIT: Sorry if I wasn’t clear but this isn’t my code. I am supposed to figure out what is wrong with the one provided

I am doing exercises for my Programming Fundamentals class and these codes are intended to check whether a string contains any lowercase letters, but something is wrong.

Here is the code:

def any_lowercase3(s):
for c in s:
flag=c.islower()
return flag

I understand that it is wrong because this will only check the last letter of the string and return that, but I don't understand why.

This class is my first experience in Python and coding as a whole since the HTML MySpace days so I am struggling a bit.

5 Comments
2024/12/17
18:07 UTC

3

[Reinforcement Learning] Policy iteration and value iteration taking a while to converge

Hi, I'm studying reinforcement learning, closely following the textbook by Sutton and Barto (more so the tutorial videos by Mutual Information here).

I've tried to implement the simple example (from here) of an agent in a 4x4 gridworld. The agent can move within the grid (up/down/left/right) and two of the opposite diagonal squares are terminal states. Each step accrues reward -1, so the goal is to reach a terminal state as quickly as possible. My code that gets this done is below.

import numpy as np


# 16 different states arranged in a 4x4 square grid
# Two opposite corners are terminal states
# The reward for every transition is always -1 (we want to minimize the number of steps)

class GridWorld:

    '''
    The states of the grid are enumerated as:
    [[ 0,  1,  2,  3],
     [ 4,  5,  6,  7],
     [ 8,  9, 10, 11],
     [12, 13, 14, 15]]
    The agent has 4 potential actions:
    - 0: up
    - 1: right
    - 2: down
    - 3: left
    unless the action would move the agent off the grid, in which case the agent remains in place.
    The agent receives a reward of -1 at each time step until it reaches a terminal state.
    There are two terminal states in the grid - states 0 and 15.
    '''
    def __init__(self, size=4):
        self.size = size
        self.n_states = size * size
        self.n_actions = 4
        # initialize a random policy - choose uniformly at random from the 4 actions in all states
        self.policy = np.ones(shape=[self.n_states, self.n_actions]) / self.n_actions  # self.policy[s, a] = π(a | s)
        self.gamma = 1  # discount factor - no discounting
    
    def state_transition(self, s: int, a: int) -> tuple[int, int]:
        '''
        Given the current state s and action a, return the next state s' and reward r.
        Samples from p(s', r | s, a).
        '''
        x, y = (s // self.size, s % self.size)
        if s == 0 or s == 15:
            return s, 0
        if a == 0:
            x = max(0, x - 1)
        elif a == 1:
            y = min(self.size - 1, y + 1)
        elif a == 2:
            x = min(self.size - 1, x + 1)
        elif a == 3:
            y = max(0, y - 1)
        s_prime = x * self.size + y
        return s_prime, -1
    
    def environment_model(self, s_new: int, r: int, s: int, a: int):
        # Deterministic environment
        # Returns the value of p(s', r | s, a).
        if self.state_transition(s, a) == (s_new, r):
            return 1
        else:
            return 0
    
    def policy_evaluation(self, num_sweeps: int = 0) -> np.ndarray:
        '''
        Apply the Bellman equations for V and Q to estimate the value function at the current policy self.policy.
        
        ### Arguments
        #### Optional
        - `num_sweeps` (int, default = 0): number of iterations to run the policy evaluation for. If 0, run until convergence.
        
        ### Returns
        - `np.ndarray`: estimated value function V, where `V[s]` = V(s)
        '''

        # initialize the state value function randomly
        self.V = np.random.random(self.n_states)  # self.V[s] = V(s), the state value function
        self.Q = np.random.random(size=[self.n_states, self.n_actions])  # self.Q[s, a] = Q(s, a), the state-action value function
        self.V[0] = self.V[15] = 0  # set the value of the terminal states to 0
        self.Q[0, :] = self.Q[15, :] = 0  # set the value of the terminal states to 0

        sweep = 0
        V_new = np.zeros(self.n_states)
        Q_new = np.zeros([self.n_states, self.n_actions])
        while True:
            for s in range(self.n_states):
                if s == 0 or s == 15:
                    pass  # terminal states always have V(s) = 0
                else:
                    V_new[s] = sum(self.policy[s, a] * \
                        sum(self.environment_model(s_prime, -1, s, a) * (-1 + self.gamma * self.V[s_prime]) \
                            for s_prime in range(self.n_states)) \
                        for a in range(self.n_actions))
                    
                    for a in range(self.n_actions):
                        Q_new[s, a] = sum(self.environment_model(s_prime, -1, s, a) * (
                            -1 + self.gamma * sum(self.policy[s_prime, a_prime] * self.Q[s_prime, a_prime] \
                                for a_prime in range(self.n_actions))) \
                            for s_prime in range(self.n_states))
            sweep += 1
            if (np.allclose(self.V, V_new) and np.allclose(self.Q, Q_new)) or sweep == num_sweeps:
                self.V = V_new
                self.Q = Q_new
                break
            else:
                self.V = V_new
                self.Q = Q_new
    
    def policy_improvement(self):
        '''
        Update the policy to be greedy with respect to q(s, a).
        The new policy is deterministic rather than stochastic.
        '''
        new_policy = np.zeros_like(self.policy)
        for s in range(self.n_states):
            a_opt = np.argmax(self.Q[s, :])
            new_policy[s, a_opt] = 1
        self.policy = new_policy
    
    def policy_iteration(self):
        '''
        Perform policy iteration to find the optimal policy.
        '''
        i = 0
        new_policy = self.policy
        while True:
            self.policy_evaluation()  # until convergence
            self.policy_improvement()
            if (self.policy == new_policy).all():
                break
            else:
                new_policy = self.policy
            i += 1
        print(f'Converged after {i} iterations.')

    def value_iteration(self):
        '''
        Perform value iteration to find the optimal policy.
        '''
        i = 0
        new_policy = self.policy
        while True:
            self.policy_evaluation(num_sweeps=1)
            self.policy_improvement()
            if (self.policy == new_policy).all():
                break
            else:
                new_policy = self.policy
            i += 1
        print(f'Converged after {i} iterations.')

Both policy iteration and value iteration converge to the optimal solution. However, it takes a long time.

grid = GridWorld()
grid.value_iteration()  # or use: grid.policy_iteration()
print(grid.policy)

I would think for this very simple situation, it should be a lot faster.

Policy iteration takes about 200 iterations (a few seconds). Value iteration takes about 10,000 iterations (around a minute).

Have I done something to make this code really inefficient? I'm not doing anything fancy here. Thanks for any advice!

0 Comments
2024/12/17
18:02 UTC

1

why is my code for 21 game not working (the main problem is in try and except statement according to me)

import random

startup = random.randint(1,3)
print("My number is ", startup)
check = startup + 3

nexnum = int(input("Enter your number \n- "))
def check_round():
  while nexnum > check:
    print("Your number is too high\n Please try again")
    nexnum = int(input("-"))
while nexnum or startup >= 21:
  try:
    nexnum = int (nexnum)
    check_round()
  except:
    print("Please enter a whole number")
    nexnum = int(input("-"))
    continue
  func1 = nexnum + 3
  func2 = nexnum - 1
  startup = random.randint(func2, func1)
  nexnum = int(input("Enter your next number\n-"))
  continue
7 Comments
2024/12/17
17:29 UTC

3

How to learn what to write ?

Hi guys! I'm not exactly new to programming, but here's the thing. I don't really know what to write when it comes to writing programm on command. Like i wanna learn for "matura" exam which in poland is like big exam from like 5 years of school. And when i get the task for example : Count how many numbers from the file numbers.txt have more zeros than ones in their binary representation my mind goes blank and don't know what to write??? I know statements like for if else and like many more, but when it comes to task i don't really know how to use them. Can anyone tell me how to just learn ? Like how to use them in task etc.

2 Comments
2024/12/17
17:06 UTC

0

Moving to previous inputs

What if i wanted to make an input move to one in a previous part of my code. Like you go north (loop/input one) then (loop/input 2) you go south and go back to (input/loop one). Would there be some way to do that?

3 Comments
2024/12/17
16:35 UTC

0

Is using Selenium for automation bad for your RAM in the long run?

Hello, an extreme noob here starting out with Selenium. I've read online that it causes memory leaks longer you use it. Just wondering is it true and how can I avoid it. Also, if let's say there was an actual memory leak, will it restore after you restart your computer?

9 Comments
2024/12/17
16:26 UTC

2

Coding a game

Me and my friend are making a little space shooter games for our end of semester school project. We are using codeHS. Although, our game ends after we score once. It just freezes.

This is our code: import tkinter as tk import random

Constants

WIDTH = 600 HEIGHT = 800 PLAYER_WIDTH = 50 PLAYER_HEIGHT = 50 ENEMY_WIDTH = 50 ENEMY_HEIGHT = 50 BULLET_WIDTH = 5 BULLET_HEIGHT = 10 PLAYER_SPEED = 20 BULLET_SPEED = 15 ENEMY_SPEED = 5 POWERUP_WIDTH = 20 POWERUP_HEIGHT = 20 POWERUP_SPEED = 3

class ShootingGame: def init(self, root): self.root = root self.root.resizable(False, False) # Added this line self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="black") self.canvas.pack() self.powerups = [] self.power_active = False self.power_timer = 0 self.power_type = None

    # Player setup with adjusted position
    self.player = self.canvas.create_rectangle(
        WIDTH // 2 - PLAYER_WIDTH // 2,  # X start
        HEIGHT - PLAYER_HEIGHT - 20,      # Y start - moved higher up
        WIDTH // 2 + PLAYER_WIDTH // 2,   # X end
        HEIGHT - 20,                      # Y end
        fill="yellow",
        outline="white",
        width=3
    )

    # Debug print for player coordinates
    player_coords = self.canvas.coords(self.player)
    print(f"Player coordinates: {player_coords}")

    # List for bullets and enemies
    self.bullets = []
    self.enemies = []

    # Score
    self.score = 0
    self.score_text = self.canvas.create_text(
        10, 10, anchor="nw", text=f"Score: {self.score}",
        fill="white", font=("Arial", 16)
    )

    # Controls
    self.root.bind("<Left>", self.move_left)
    self.root.bind("<Right>", self.move_right)
    self.root.bind("<space>", self.shoot_bullet)

    # Start game loop
    self.running = True
    self.update_game()

def move_left(self, event):
    if self.canvas.coords(self.player)[0] > 0:
        self.canvas.move(self.player, -PLAYER_SPEED, 0)

def move_right(self, event):
    if self.canvas.coords(self.player)[2] < WIDTH:
        self.canvas.move(self.player, PLAYER_SPEED, 0)

def shoot_bullet(self, event):
    x1, y1, x2, y2 = self.canvas.coords(self.player)
    bullet = self.canvas.create_rectangle(
        (x1 + x2) // 2 - BULLET_WIDTH // 2,
        y1 - BULLET_HEIGHT,
        (x1 + x2) // 2 + BULLET_WIDTH // 2,
        y1,
        fill="white"
    )
    self.bullets.append(bullet)

def spawn_enemy(self):
    x = random.randint(0, WIDTH - ENEMY_WIDTH)
    enemy = self.canvas.create_rectangle(
        x, 0, x + ENEMY_WIDTH, ENEMY_HEIGHT, fill="red"
    )
    self.enemies.append(enemy)

def update_bullets(self):
    for bullet in self.bullets[:]:
        self.canvas.move(bullet, 0, -BULLET_SPEED)
        if self.canvas.coords(bullet)[1] < 0:
            self.canvas.delete(bullet)
            self.bullets.remove(bullet)

def update_enemies(self):
    for enemy in self.enemies[:]:
        self.canvas.move(enemy, 0, ENEMY_SPEED)
        if self.canvas.coords(enemy)[3] >= HEIGHT:
            self.running = False
            self.canvas.create_text(
                WIDTH // 2,
                HEIGHT // 2,
                text="GAME OVER",
                fill="white",
                font=("Arial", 40)
            )
        for bullet in self.bullets[:]:
            if self.check_collision(enemy, bullet):
                self.canvas.delete(enemy)
                self.canvas.delete(bullet)
                self.enemies.remove(enemy)
                self.bullets.remove(bullet)
                self.score += 1
                self.canvas.itemconfig(self.score_text, text=f"Score: {self.score}")

def check_collision(self, enemy, bullet):
    e_coords = self.canvas.coords(enemy)
    b_coords = self.canvas.coords(bullet)
    return not (
        e_coords[2] < b_coords[0]
        or e_coords[0] > b_coords[2]
        or e_coords[3] < b_coords[1]
        or e_coords[1] > b_coords[3]
    )

def update_game(self):
    if not self.running:
        return

    if random.randint(1, 50) == 1:
        self.spawn_enemy()

    self.update_bullets()
    self.update_enemies()

    self.root.after(50, self.update_game)
   
    # Different power-up types and their colors
    self.powerup_types = {
        "double_shot": "blue",
        "speed_boost": "green",
        "shield": "purple"
    }

def spawn_powerup(self):
    x = random.randint(0, WIDTH - POWERUP_WIDTH)
    power_type = random.choice(list(self.powerup_types.keys()))
    color = self.powerup_types[power_type]

    powerup = self.canvas.create_oval(
        x, 0,
        x + POWERUP_WIDTH, POWERUP_HEIGHT,
        fill=color,
        outline="white"
    )
    self.powerups.append({"item": powerup, "type": power_type})

def update_powerups(self):
    for powerup in self.powerups[:]:
        self.canvas.move(powerup["item"], 0, POWERUP_SPEED)

        # Check if powerup is off screen
        if self.canvas.coords(powerup["item"])[3] >= HEIGHT:
            self.canvas.delete(powerup["item"])
            self.powerups.remove(powerup)
            continue
       
        # Check collision with player
        if self.check_collision_with_player(powerup["item"]):
            self.activate_powerup(powerup["type"])
            self.canvas.delete(powerup["item"])
            self.powerups.remove(powerup)
            def check_collision_with_player(self, item):
    p_coords = self.canvas.coords(self.player)
    i_coords = self.canvas.coords(item)
    return not (
        i_coords[2] < p_coords[0]
        or i_coords[0] > p_coords[2]
        or i_coords[3] < p_coords[1]
        or i_coords[1] > p_coords[3]
    )

def activate_powerup(self, power_type):
    self.power_active = True
    self.power_type = power_type
    self.power_timer = 100  # Power-up lasts for 100 game ticks

    if power_type == "speed_boost":
        global PLAYER_SPEED
        PLAYER_SPEED *= 2

def update_power_status(self):
    if self.power_active:
        self.power_timer -= 1
        if self.power_timer <= 0:
            self.deactivate_powerup()

if name == "main": root = tk.Tk() root.title("Shooting Game") game = ShootingGame(root) root.mainloop()

Any tips?

2 Comments
2024/12/17
15:51 UTC

1

Sending an email on behalf of a shared account (In Outlook)

I am trying to send an email on behalf of a shared account in outlook.

Using win32com, I am able to read the emails in the shared account, but not send an email from it (It would be on behalf of). As from what I understand, the shared account is not something you can log into, but an owner has granted access for people to use it.

when doing

outlook = win32.Dispatch('outlook.application')
for account in outlook.Session.Accounts:
  print(account.DisplayName)

outlookInbox = outlook.GetNamespace("MAPI")
for folder in outlookInbox:
  print(folder.name)

I get just my account in the accounts, and my account and the shared folders in the inbox

This leads me to believe that in order for me to send an email from a shared account, I need to log in, but, there is no password for me to log into it.

I have also tried using

mail.SendUsingAccount = "email@account"
mail.Sender = "email@account"
mail._oleobj_.Invoke(*(64209, 0, 8, 0, "email@account"))

But none of them seem to work.

0 Comments
2024/12/17
15:50 UTC

1

Plotting a grid of boxes like an excel sheet?

I'm trying to find a library that can help me to plot some cells as red boxes in a grid style. I.E if i had data showing a cell should be colored at (3,5) it would fill in a cell box at 3,5 and be listed as 3,5 when moused over or listed out.

I've tried numpy to do

data = np.zeroes((rows,columns))

and then insert a 1 at the row or column where I have a cell to be shaded.

When i plot this with imshow I get a box cenetered at the correct poin but mousing over it extends from the point to halfway to the next. Is there an easy way to color in a cell similar to how an excel cell would be colored if I was flling in say A:2

1 Comment
2024/12/17
15:38 UTC

1

Windows service identifies correct registry key path, but doesn't retrieve the stored values.

Hi, I'm making a Windows service, one of it's functions is to retrieve the stored values from the registry.

The standalone python script works as intended, but when I try running it as a Windows service, it doesn't retrieve the stored values from the registry

    # Default control targets
    self.control_list = ["none", "none", "none", "none"]
    # Stored control targets
    self.settings = QSettings("CompanyName", "ProductName")
    self.load_volume_targets()

    logging.info(self.settings.fileName())

def load_volume_targets(self):
    saved_targets = self.settings.value("currentlySavedVolumeTargets", [])
    if isinstance(saved_targets, list) and len(saved_targets) == 1:
        targets = saved_targets[0].split(", ")
        self.control_list = targets
        logging.info("Saved control targets loaded:", self.control_list)

The service log file logs: logging.info(self.settings.fileName())

\HKEY_CURRENT_USER\Software\CompanyName\ProductName

The standalone script finds and prints out the saved values correctly:

Saved control targets loaded: ['Master', 'None', 'None', 'None']
\HKEY_CURRENT_USER\Software\CompanyName\ProductName

The code is the same for the standalone script and the service, both of them are in a class.

How can I debug why can't the service retrieve the values from the registry?

2 Comments
2024/12/17
15:37 UTC

0

OpenAI API - Continuous 500 Error

I continue to receive this error when I supply image files (.png) to OpenAI for analysis. Everything I've found online looks like it's a transient error but I have never got it to work.

Any ideas? Is this truly a bug?

Code:

def analyze_image(image_path):
    try:
        # Open the image file
        with open(image_path, "rb") as image_file:
            image_data = image_file.read()

        # Send the image and prompt to GPT-4 Vision
        response = openai.ChatCompletion.create(
            model="gpt-4-vision-preview",
            messages=[
                {"role": "system", "content": "Prompt."},
                {"role": "user", "content": "Prompt."},
                {"role": "user", "content": {"type": "image_url", "image_url": "data:image/png;base64," + base64.b64encode(image_data).decode()}}
            ],
            max_tokens=10000
        )

        # Return the GPT-4 Vision response
        return response.choices[0].message.content

    except Exception as e:
        return f"Error processing {image_path}: {str(e)}"

# Loop through all PNG files in the folder
if __name__ == "__main__":
    import base64

    print("Starting analysis of images...\n")

    # Check if the folder exists
    if not os.path.exists(image_folder):
        print("The specified folder does not exist. Please check the path.")
        exit()

    # Iterate over all PNG files in the folder
    for filename in os.listdir(image_folder):
        if filename.lower().endswith(".png"):
            image_path = os.path.join(image_folder, filename)
            print(f"Analyzing image: {filename}")
            result = analyze_property_condition(image_path)
            print(f"Result for {filename}:")
            print(result)
            print("-" * 50)

    print("\nImage analysis completed.")

Error:

Error processing C:\Users\Downloads\Images\screenshot 2024-12-17 01-16-36-11.png: The server had an error processing your request. Sorry about that! You can retry your request, or contact us through our help center at help.openai.com if you keep seeing this error. (Please include the request ID req_b488781814317423cbf3955b65d7088b in your email.) {
  "error": {
    "message": "The server had an error processing your request. Sorry about that! You can retry your request, or contact us through our help center at help.openai.com if you keep seeing this error. (Please include the request ID req_b488781814317423cbf3955b65d7088b in your email.)",
    "type": "server_error",
    "param": null,
    "code": null
  }
} 500 {'error': {'message': 'The server had an error processing your request. Sorry about that! You can retry your request, or contact us through our help center at help.openai.com if you keep seeing this error. (Please include the request ID req_b488781814317423cbf3955b65d7088b in your email.)', 'type': 'server_error', 'param': None, 'code': None}} {'Date': 'Tue, 17 Dec 2024 15:21:22 GMT', 'Content-Type': 'application/json', 'Content-Length': '369', 'Connection': 'keep-alive', 'access-control-expose-headers': 'X-Request-ID', 'openai-processing-ms': '540', 'x-ratelimit-limit-requests': '500000', 'x-ratelimit-limit-tokens': '300000', 'x-ratelimit-remaining-requests': '499999', 'x-ratelimit-remaining-tokens': '299455', 'x-ratelimit-reset-requests': '0s', 'x-ratelimit-reset-tokens': '108ms', 'x-request-id': 'req_b488781814317423cbf3955b65d7088b', 'strict-transport-security': 'max-age=31536000; includeSubDomains; preload', 'CF-Cache-Status': 'DYNAMIC', 'X-Content-Type-Options': 'nosniff', 'Server': 'cloudflare', 'CF-RAY': '8f37e6f879b29011-BOS', 'alt-svc': 'h3=":443"; ma=86400'}
2 Comments
2024/12/17
15:34 UTC

4

How to set up python on a new Mac?

I got the new Mac mini m4 and I want to get a better understanding of how to setup python correctly.

I want to install python with as minimal bloatware as possible, and preferably finally understanding things like virtual environments. But I will be using python for big coding projects. Based on this, what is the best approach?

Previously I have coded on an older Mac using things like Spyder, and jupyternotebook. It all felt like a huge mess, I never used python in the terminal. I never got comfortable with pip and I never knew if I had to use pip to install packages, since most packages seem to be preinstalled when using Spyder or jupyternotebook.

I started to look up some YouTube tutorials and online, but many sources suggest different setups like rye or home-brew...

21 Comments
2024/12/17
15:10 UTC

2

What is the problem with "pip install -e"?

When I run python from the terminal, everything works correctly with the package installed in editable mode using -e. However, for some reason, in a .py file within PyCharm, it shows "unresolved reference" errors. If I install the package without -e, the issue disappears, and everything works fine.

I have followed everything the AI suggested, but the "unresolved reference" error still appears.

5 Comments
2024/12/17
15:06 UTC

3

What to learn in python

I want to learn python for AI independently, since I'm majoring in a different thing, if possible do you know what are the general topics to focus on in advance, I learned many other programming languages, so its not about learning python but what to do and focus in it that relates to AI. Thanks in advance!

2 Comments
2024/12/17
15:06 UTC

2

Job runner that does not serialize/pickle python code?

I've used both Celery and RQ in the past but now I'm wondering if there is a piece of software that will allow me to consume much simpler values from a queue, like a string, and use the value as argument in a function on the task runner side.

I suspect I have to write this myself using asyncio but I want to check with the community first.

I'm picturing an asyncio process on the job runner side that consumes these string values and for each string it runs a function. The goal is simply to minimize the complexity of data I'm passing between the producer and the consumer, so it's easily validated.

4 Comments
2024/12/17
14:59 UTC

1

Unit testing using pytest in bottle framework

I am trying to write unit tests that would test my bottle app. The problem is that I get KeyError wsgi.input which probablly means I am trying to avoid the bottle enviornment and that I need to mock the request? I am mocking the db engine and then in my test method I am trying to call the controller method and asserting them

Any idea how can I mock the request, anyone done this before?

0 Comments
2024/12/17
14:56 UTC

1

please help: multi task download

I'v been working on this code for days, trying to download okx crypto market candle data. The server has some limits:

1, rate limit: 40 requests max / 2 seconds.

2, pagination: for each symbol, could only download 1440 candles at most, and have to use pagination since each request has 300 candles max limit.

This code can deal with pagination correctly in fetch(). And I tried to make multi thread download as fast as possible while meeting rate limit, in fetchall().

I guess the problem is: using pagination, each symbol's one request turned into several requests, thus sabotaged my effort of meeting rate limit? Now I got many '429, {"msg":"Too Many Requests","code":"50011"}' error for many symbols, but not all.

I tried lowering max_requests value from 40 to 20 or 25, it can improve, but no guaranty that it will have no error, considering in a different environment or different time. I want a reasonable/scientific solution.

I also tried give it more tries if a symbol fetch got 429, but maybe more tries means sabotage rate limit even more?

Could anybody please help me fix this?

code is here

3 Comments
2024/12/17
14:50 UTC

1

Setting up dev env

Hi, I’m a seasoned programmer but haven’t work with python. I’m trying to set up an open source project on my machine and running into issues with the dev environment. I was able to get it working with venv but it added an entire directory into the project. Without that directory, I couldn’t access any of the dependencies (flask, etc) despite using pip to add those.

I could git ignore the venv directory and move on but it seemed like a hackey solution.

Is there a common approach for setting up a dev env for python? In JavaScript you use either yarn or npm install dependencies then start a dev server and it works. It seems like there are more steps to getting things up and running with python. Are there any tried and true approaches for developing apps with python? It seems like python has a wider array of options for that and thus the answer is “it depends” rather than “install this thing.”

Googling produce a lot of options so I’m bringing the question here in the hopes of getting more clarity.

I want code for an existing python app using a local development environment. How would you recommend I get development environment set up?

3 Comments
2024/12/17
14:42 UTC

0

Does Mark Lutz love spam?

I have a Learning Python book and all I see is the word spam used in almost all the programming example snippets. Does the author love spam so much?

6 Comments
2024/12/17
14:13 UTC

0

Extracting data from a website

Hi everyone, I am very new to Python and data extraction. I am trying to get data from the addresses. If you click on the address, it gives the detail about that specific address. But I am trying to get excel file that have the address and the property characteristics. I was wondering if it is possible to use Python to get that excel file?

https://gis.vgsi.com/WesterlyRI/Sales.aspx!<

5 Comments
2024/12/17
13:23 UTC

1

Having a hard time with cron-job.org API

I want to create a cron job on cron-job.org through their API using python.

As a result, I get 404.

I don't know exactly what is not found

Here's full code:

from datetime import datetime
import requests, json

# Cron-job.org API URL
api_url = "https://cron-job.org/api/1.0/user/cronjobs"
# api_url = "https://api.cron-job.org/jobs"

# Your cron-job.org API key
api_key = "*******************************************"

# Cron job details
command_url = f"https://httpbin.org/json"

# Extract hour and minute
try:
    hour = 10
    minute = 30

    # Prepare cron job schedule (cron-job.org takes time in hour and minute, not the standard cron format)
    schedule = {
    "minute": minute,
    "hour": hour,
    "mdays": ["*"],  # Every day of the month
    "months": ["*"], # Every month
    "wdays": ["*"],  # Every day of the week
    "enabled": True,
    "url": command_url
    }

    # Create headers with API key for authentication
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"}

    # Make the API request to create the cron job
    response = requests.put(api_url, headers=headers, data=json.dumps(
    schedule))

    # Check if the cron job was created successfully
    if response.status_code == 201:
        print("Cron job created successfully.")
    else:
        print(f"Failed to create cron job: {response}")
        print(response.text)
except Exception as e:
    print(f'Errrrrrror: {e}')
5 Comments
2024/12/17
12:16 UTC

Back To Top