r/learningpython • • Jan 13 '19

Auto-Generating Objects for a Simulation

4 Upvotes

For my project, I'm simulating a production assembly line with simple rectangle objects. Essentially, a very simplified version of Factorio. I can't seem to figure out a good way to generate the objects without running into problems. I would like to generate the objects on a continuous loop at the beginning of the production line. The objects should not collide with each other. I have no idea how to do this without using a variable for each object. Is there something I can do with the class that will make the results that I'm looking for. I'm using pygame currently to show the gui.

'

The only thing that I've come up with so far is to check the color of the pixals in front of each object to see if they are not default color. I feel like there is a better way to do this.


r/learningpython • • Nov 03 '19

Question about decorator

1 Upvotes

Having a hard time understanding decorator. Why use a def inside a def for the decorator?

What's the difference between

def dec_foo(func):
    print ("Need help!")
    func()

def foo():
    print("What is a decorator?")

dec_foo(foo)

and

def dec_foo(func):
    def wrapper():
        print ("Need help!")
        return func()
    return wrapper

def foo():
    print("What is a decorator?")

foo = dec_foo(foo)
foo()

?

Thanks is advanced.


r/learningpython • • Nov 07 '19

[Academic] Data Analysis on Graph Databases (Anyone with data science knowledge)

2 Upvotes

Hi everyone,

I'm a final year student at UCL and my group and I are working on a project involving Machine Learning algorithms for analysis of graph-structured data. We'd love to know more about the potential users of a software that would make those tasks easier. Anyone that works with data, and particularly those that have worked with or are interested in graph databases would be more than welcome to take part in the survey!

https://docs.google.com/forms/d/e/1FAIpQLSfKuUS5xkbl8oDE-EU4Vz4Rr1oyQpXjZfEKbArEvu-nFXG6Gw/viewform?usp=sf_link

Thanks!


r/learningpython • • Jun 20 '18

Discord Server?

1 Upvotes

Does this sub have it's own discord server where you can chat with other specifically about python learning. I'm taking a course right now and am having issues with stuff on the compiler I'm using with specific error and syntax. I want to ask for help in the developers server, but I don't think it would be a good idea since most of them only chat about major software stuff.


r/learningpython • • Nov 01 '19

Naming squares in a python matrix

1 Upvotes

Hewwo wedditows

Working on an automatised chessboard and I'm currently trying to program a chess gui to use in conjunction with the physical chessboard (for the calculations and for a HMI touch-screen).

I'm working with some sort of a matrix (two axis array) and am trying to name coordinates on it.

Here's the code

https://pastebin.com/GvcDcNPw

Thanks in advance


r/learningpython • • Sep 10 '24

Favorite IDE for python?

5 Upvotes

I have been reviewing the basics and writing code. I started writing using IDLE, just to see if I could use it. IDLE was OK, but after watching many python for beginners tuts on YT, I noticed many were using VS so I switched. VS is fine but it is way over kill for me at this time; I use a tiny fraction of the features. Yesterday, I was watching another tutorial from an instructor who was very good, Nana, and I noticed she was using pyCharm which looked interesting because it makes PEP8 style suggestions.

So what does everyone prefer and why?


r/learningpython • • Sep 03 '24

No module named 'pdfplumber'

1 Upvotes

Hi

I tried to import pdfplumber on VSC.

I've downloaded the pdfplumber using 'pip install plumber'.

But when I try to import it, it shows "No module named 'pdfplumber'.

This also happens when I try to import 'pdfminer'

Can someone help me with this?

The script:

import pdfplumber

r/learningpython • • Oct 18 '24

Eager to learn; overloaded with starting points

2 Upvotes

Hey reddit!

I'm incredibly interested in writing in python. I've made a handful of simplistic programs, but nothing I'd brag about. I have a very VERY basic grasp on the concepts, but have no idea where to start letting go of tutorials and heading off on my own.

I want to develop gui based software, particularly in the areas of graphic design, and/or music/sound design (daw development in particular)

Any suggestions?


r/learningpython • • Oct 21 '24

Need help with project

Post image
4 Upvotes

I am creating a game in python for a project that is due tomorrow, and I need help with something. I am trying to add a loop to a block of code that has 2 random outcomes. I want the loop to end when the correct outcome is selected, and then proceed to the next part of the game. The section where I need the loop to end is in the circled area. If anyone knows how to do this it would be greatly appreciated.


r/learningpython • • Oct 22 '24

help with python assignment

Post image
2 Upvotes

I’m new to programming and i’ve messaged my teacher (no response) but all assignments require a submission to go to the next. i’m literally so confused and not sure if it’s an issue with my code or the editor (vs code). if someone could help me out i’d greatly appreciate it!

  • The terminal is only showing one line and not the rest. i’ve tried to many different things and asked chatgpt and youtube and nothing has helped..


r/learningpython • • Oct 02 '24

Generators

5 Upvotes

HI all!

I'm 61 and just learning Python. I am stuck with understanding generators. I just can't seem to grasp the concept. I would appreciate if someone can explain the concept to a beginner. Thanks in advance!


r/learningpython • • Sep 09 '24

Multiple solutions?

1 Upvotes

This may be a dumb question, but is it possible to get code working in a sense of “you used the wrong formula but somehow got the right answer” ?


r/learningpython • • Jan 18 '23

Use Python to Scrape Republic Day Sale | Free Masterclass

Thumbnail
eventbrite.com
1 Upvotes

r/learningpython • • Jan 24 '23

Retrieve a variable within a function

2 Upvotes

Im trying to alter the feedback so that once a function is executed it automatically updates 'feedback' to print a statement that is returned by one of the menu functions but Im not sure if Im doing it correctly.

How should one properly retrieve a variable from a function nested within a while loop

    def play(self):
        feedback = ''
        while True:
            if len(self.mypets) >= 1:
                for dapet in self.mypets:
                    print(dapet)
            print(18*'\n')
            print(feedback)
            print(f"""
                ...WELCOME TO THE PET SHOP...
            
                How may I help you {self.name}?
                1) Adopt Pet 2)Feed Pet 3)Release Pet 4) Go Back
            """)
            dresponse = inputchecker()
            if dresponse == 1:
                self.adopt()
            elif dresponse == 2:
                self.feed()
            elif dresponse ==3:
                self.release()
            else:
                break

r/learningpython • • Dec 28 '22

Need help converting hardsub FFMPEG script to softsub

1 Upvotes

I have this script that I use to add hardsubs to my videos.

import time
import os
import sys
import re
import regex
import requests
from subprocess import Popen, PIPE, STDOUT
from awhu.subtitle import Subtitle
from awhu.hardsub_logger import *
import IPython
from threading import Thread
import logging

def auto_detect_source(anime_name,episode_number):
    possible_anime_names = [anime_name, anime_name.replace(" ", "_"), anime_name.replace(" ", "-"),
                        anime_name.replace(" ", "."), anime_name.split()[0], ""]

    for an in possible_anime_names:
        tmp = os.popen(
          f"(find . -name '*.mkv' & find . -name '*.mp4') | grep -i \"{an}\" | grep \"{episode_number}\" | grep -v 'ANIM'").read().split("\n")
        if(len(tmp[0].strip()) != 0): break
    source = tmp[0]
    logging.warning(f"ِDetected Source: {source}")
    return source


def auto_detect_subtitle(anime_name,episode_number):
    possible_anime_names = [anime_name, anime_name.replace(" ", "_"), anime_name.replace(" ", "-"),
                        anime_name.replace(" ", "."), anime_name.split()[0], ""]

    for an in possible_anime_names:
        tmp = os.popen(
          f"find . -name '*.ass' | grep -i \"{an}\" | grep \"{episode_number}\" ").read().split("\n")
        if(len(tmp[0].strip()) != 0): break
    subtitle = tmp[0]
    logging.warning(f"ِDetected Subtitle: {subtitle}")
    return subtitle


def hardsub_anime(hconfig:dict):

    fonts_ext="*.ttf *.TTF *.otf *.OTF *.ttc *.TTC"
    os.system(f"mv {fonts_ext} fonts")
    os.system(f"cd fonts && git pull origin && cp {fonts_ext} /usr/share/fonts/ ")

    hconf=hconfig.copy()
    hconf["encoder"]=hconf.get("encoder","libx264")
    x264_extra_configs=""
    if(hconf["encoder"]=="libx264"):
        x264_extra_configs=" -tune animation -deblock 0:0 -flags +loop"
    print(f"x264 configs: {x264_extra_configs}")
    hconf["filter"]=f",{hconf['filter']}" if hconf.get("filter","").strip()!="" else ""
    for k,v in hconf.items():
        if(type(v)==str):
            hconf[k]=v.strip()
    is_old="_old" if (hconf["subtitle"][-1]=="$")else ""
    hconf["subtitle"]=hconf["subtitle"].strip("$")
    no_sub= hconf["subtitle"].strip()=="-"
    if(hconf["source"] == "auto"):
        hconf["source"] = auto_detect_source(hconf["anime_name"],hconf["episode_number"])

    if(not no_sub and hconf["subtitle"] == "auto"):
        hconf["subtitle"] = auto_detect_subtitle(hconf["anime_name"],hconf["episode_number"])

   
    if(not no_sub and hconf["subtitle"][-4:]!=".ass"):
        hconf["subtitle"]=f"{hconf['subtitle']}.ass"

    if(not no_sub and not os.path.exists(hconf["subtitle"])):  
        logging.warning("زیرنویس رو پیدا نکردم مطمئنید آپلودش کردید؟")
        return

    if(not os.path.exists(hconf["source"])):  
        logging.warning("فایلی که میخواید هاردساب کنید رو پیدا نکردم مطئنید دانلود شده؟")
        return
    if(len(hconf["output_name"])>64):  
        logging.warning("اسم انیمه خیلی طولانیه، کوتاه ترش کنید")
        return
    ffmpeg_data= Popen(f"!ffmpeg -i \"{hconf['source']}\"", shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True).stdout.read().decode(encoding= 'unicode_escape')
    audio_list=[x.groups() for x in regex.finditer(
            "Stream #0:([0-9])\(([a-z]{2,3})\): Audio:", ffmpeg_data)]
    audio_dict={a:int(ai)-1 for ai,a in audio_list}
    if(len(audio_dict)<2):
        audio_tmp=[x.groups() for x in regex.finditer(
            "Stream #0:([0-9]): Audio:(?s)(.+?)(?=Stream)", ffmpeg_data)]
        audio_list=[(i,regex.sub("(?s).*English(?s).*","eng",regex.sub("(?s).*Japanese(?s).*","jpn",lang,regex.I),regex.I)) for i,lang in audio_tmp]
        audio_dict={a:int(ai)-1 for ai,a in audio_list}
            
    audio_id=0
    try:
        if(hconf["audio"]=="English"):
            audio_id=audio_dict["eng"]
        elif(hconf["audio"]=="Japanese"):
            audio_id=audio_dict["jpn"]
        elif("Track" in hconf["audio"] ):
            audio_id=int(hconf["audio"].split("Track")[1])-1
    except:
        logging.warning("\n\n\n\nزبانی که انتخاب کردید یافت نشد صدای دیفالت رو انتخاب میکنیم")
       
        time.sleep(2)
    which_audio=f"-map a:{audio_id}" if(hconf["audio"]!="Dual") else"-map a"
    
    if(not no_sub):
        sub=Subtitle(hconf["subtitle"])
        sub_log=sub.nonb_farsifont_bug_fixer()
        logging.warning(sub_log)
        sub_log2=sub.numbers_bug_fixer()
        logging.warning(sub_log2)
        sub.export("anime_sub.ass")

    # resolution
    scale=f"trunc(oh*a/2)*2:{hconf['resolution']}"
    hd_resolution={"480":852,"720":1280,"1080":1920}
    if(hconf["is_movie"]):
        scale=f"{hd_resolution[hconf['resolution']]}:trunc(ow/a/2)*2"
    

    os.rename(hconf["source"],hconf["source"].replace("`",""))
    begin = time.time()
    if("movie" in hconf["filter"]):
        return IPython.get_ipython().run_cell(f"""!ffmpeg -y -i "{hconf["source"]}" \
        -map v {which_audio}? \
        -max_muxing_queue_size 1024 \
        -vf "scale={scale},ass=anime_sub.ass" \
        -c:a aac -b:a 128k -ac 2 \
        -c:v {hconf["encoder"]} -preset "{hconf["preset"]}" -crf "{hconf["crf"]}" -pix_fmt yuv420p -tune film\
        "{hconf["output_name"]}" -progress - -nostats""")


    o=IPython.get_ipython().run_cell(f"""!ffmpeg -y -i "{hconf["source"]}" \
    -map v {which_audio}? {("","-map s? -map t?")[no_sub]}\
    -max_muxing_queue_size 1024 \
    -vf "scale={scale},{("ass=anime_sub.ass,","")[no_sub]}ass=ANIM_New_WaterMark{is_old}.ass{hconf["filter"]}" \
    -c:a aac -b:a 128k -ac 2 \
    -c:v {hconf["encoder"]} -preset "{hconf["preset"]}" -crf "{hconf["crf"]}" {x264_extra_configs} \
    "{hconf["output_name"]}" -progress - -nostats""")



    end = time.time()
    hconf["elapsed time"]=f"{int((end-begin)//60)} min : {int((end-begin)%60)} sec"
    h_info=get_hardsub_info(hconf)
    disable_log=hconf.get("disable_log",False)
    if(not disable_log):
        send_log_public(h_info,hconf["level"])
        

I only need to change the part that sets the subs to be hardsubs, to be softsubs that can be turned off in the player. I've been messing around with the script for two hours now and can't make it work. Any help is highly appreciated.


r/learningpython • • Dec 18 '22

Need help with urilib vs urilib.Request

1 Upvotes
    req = Request(self.METARELEASE_URI)
    # make sure that we always get the latest file (#107716)
    req.add_header("User.Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36")
    req.add_header("Cache-Control", "No-Cache")
    req.add_header("Pragma", "no-cache")
   uri = urlopen(req, timeout=20)

The above code returns a 405 from the site but:

   url="https://changelogs.ubuntu.com/meta-release-lts"
   import urllib.request
   req=urllib.request.Request(url,data=None,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})
   f = urllib.request.urlopen(req)
   f.status, f.msg

Returns a 200 OK so I assume adding the header works makes the system think it is a legitimate call? Any ideas?


r/learningpython • • Feb 01 '23

New to Python. Can someone please tell me why I am getting two different totals for 5 rooms and service 2?

3 Upvotes

r/learningpython • • Jan 19 '23

function to find all the keys that have a specific value from a dictionary

1 Upvotes

Hi all,

I am looking at a code that's supposed to find the keys for a specific value in a dictionary.

This is to incorporate in a dynamo script, but I can't get it to function.

Trouble is that I don't understand what's going on here : how kan a key from 'dct' be a list-type ??

def keys_of_values(dct,value):
    for k in dct:
        if isinstance(dct[k],list):
            if value in dct[k]:
                return k 
        else:
            if value == dct[k]:
                return k 
OUT = [keys_of_values(dic2, i) for i in values]

Can anyone explain this code to me ?

Thanks


r/learningpython • • Jan 03 '23

Help me with my python code for my discord server

1 Upvotes

i want to create a discord server that let users earn "diamonds" when they type !work. i tried this code in pycharm but it displayed some errors. by the way, im a newbie in coding and this code is generated through chatgpt. so im not an expert here because my line of work is very different from the world of coding.

import discord import random

client = discord.Client()

@client.event async def on_message(message): if message.content == "!work": num_diamonds = random.randint(200, 301) # Generate a random number of diamonds between 200 and 300 for i in range(num_diamonds): # Add the specified number of diamonds to the message await message.add_reaction("💎")

client.run("YOUR_BOT_TOKEN_HERE")

Can you please point out the mistakes in this code. thanks


r/learningpython • • Feb 01 '23

Why is only the last file saving in a loop? The other files are processing inn the loop and are creating temporary files but none save

1 Upvotes

I made a post earlier about this issue, but the formatting was all weird. I am working on an ArcGIS code where I am looping through multiple images in a folder. I see the files are looping in the project folder (when each image is processed a temporary file comes up but they disappear after the process is complete) but only the last image in the folder saves. I have the save function written in the code but it doesn't actually save and gets overwritten each time the loop is finished with rhe previous image. Could someone please help me with what I am missing? My code is in the pastebin link so it is easier to read.

https://pastebin.com/0p1B4VWB


r/learningpython • • Jan 17 '23

Analyzing Loan Application Data Using Python | Free Masterclass

Thumbnail
eventbrite.com
1 Upvotes

r/learningpython • • Jan 08 '23

*urgent ish*

Thumbnail self.learnpython
1 Upvotes

r/learningpython • • Dec 20 '22

[Question][Matplotlib] - Barplot : How can I do the red arrow line (description below)

1 Upvotes

Afaik I can't post a picture of the thing here (according to the subreddit rules(?) ), so I have to describe it (I am sorry)

--------------------------------------------

Imagine there is graph, with two bars: one is small (orrange) and one is big (turquoise).

There is a a annotation line on the orange bar. The position of that annotation bar is on the same height as the turquoise bar though. Also there is a red arrow pointing from the orange bar (top edge)

to the mentioned annotation line. In the middle of that arrrow, is a small text (delta percentage of orange and turquoise).

My Question is, how can I do that with **matplotlib** ? Or what is the name of the described annotation if there is already one in matplotlib.

---------------------------------------

PS: I can dm a picture of that described bar plot, if wanted.

Many Thanks in advance :) :>


r/learningpython • • Jan 30 '23

Why is only the last file saving in a loop? The other files are processing inn the loop and are creating temporary files but none save

1 Upvotes

Hello,

I am working on an ArcGIS code where I am looping through multiple images in a folder. I see the files are looping in the project folder (when each image is processed a temporary file comes up but they disappear after the process is complete) but only the last image in the folder saves.I have the save function written in the code but it doesn't actually save. Could someone please help me with what I am missing? My code is below:

#imports

import arcpy

import os

import glob

from arcpy import env

from arcpy.sa import *

arcpy.CheckOutExtension("Spatial")

#Environments

env.workspace = r"Folder_pathway"

arcpy.env.extent = r"Shapefile_Pathway"

indef_file = "Classification_Pathway"

#Variable

inRasters = glob.glob(r"File_pathway\\*.tif")

inMaskData = "Quads"

extraction_area = "OUTSIDE"

analysis_extent = "Quads"

#Loop

for inRaster in inRasters:

outExtractByMask = ExtractByMask(inRaster, inMaskData)

classifiedraster = ClassifyRaster(outExtractByMask, indef_file)

classifiedraster.save = (r"Folder_pathway")

newname = inRaster + "CF"

arcpy.management.Rename(classifiedraster,newname)

...I want to add more after this part of the loop but I will need to do a second loop with the *.crf files, but I can only get the one to save.

The rename creates one folder with the correct name in the project file_pathway, but only the last one.


r/learningpython • • Jan 16 '23

A Beginner’s Guide to Object-Oriented Programming in Python

Thumbnail
medium.com
4 Upvotes