pygame 'module' object not callable - python-3.x

So I just started using python and pygame to start building a poker program, and I downloaded a bunch of images for the cards. I started making a test program for the images:
import pygame
pygame.init()
screen = pygame.display.set_mode((1200, 675)) #Sets the screen to a 16:9 ratio display
pygame.display.set_caption('Poker Program') #Used to set the window name as whatever's in the brackets
feltGreen = (0,200,0) #What is used for the color (r,g,b)(the higher the number, the lighter the colour)
screen.fill(feltGreen)
pygame.display.update() #Updates the screen
twoc = pygame.image("2_of_clubs.png")
twod = pygame.image("2_of_diamonds.png")
twoh = pygame.image("2_of_hearts.png")
twos = pygame.image("2_of_spades.png")
threec = pygame.image("3_of_clubs.png")
threed = pygame.image("3_of_diamonds.png")
threeh = pygame.image("3_of_hearts.png")
threes = pygame.image("3_of_spades.png")
For the first while, it works perfectly. But then I get this:
Traceback (most recent call last):
File "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py", line 15, in <module>
twoc = pygame.image("2_of_clubs.png")
TypeError: 'module' object is not callable
I've tried everything, but it still says that. Is there anything I can do to make it work?
PS The folder where I store the cards is in the scripts folder of Python35.
Update: I've replaced all the pygame.image with pygame.image.load, but now I get this instead:
Traceback (most recent call last):
File "C:/Users/Z & Z Azam/Desktop/New folder (2)/Python Stuff/PycharmProjects/ProjectGambler/Graphics-Cards.py", line 15, in <module>
twoc = pygame.image.load("2_of_clubs.png") #Lines 15-66 bring all the cards into the program
pygame.error: Couldn't open 2_of_clubs.png

The problem is that pygame.image is not actually a function - it's a module (hence the text of the error). To load an image, use the function pygame.image.load(filename).

pygame.image is not a function so is not callable. You probably want to use pygame.image.load() instead.
Source: http://www.pygame.org/docs/ref/image.html
Edit:
You're probably getting the new error because python can't find the file. You should use the absolute path of the file. E.g. pygame.image.load('C:\\pictures\\2_of_clubs.png').
Ps. you don't need to list all those modules in your question. It's making the question unnecessarily long.

Related

Define fonts for re-use in python fpdf

I´m building PDF document in python with fpdf. Fonts are set in the following way:
pdf.set_font('arial', 'B', 20)
However, this seems a bit unclear if I have to change the font several times (for headings, sub headings, regular text and so on). So I was trying to define fonts upfront in the following form:
heading = ["arial", "B", 20]
sub_heading = ["arial", "B", 15]
And then use the defined fonts later:
pdf.set_font(heading)
Unfortunately this results in the following error:
Traceback (most recent call last):
File "C:\Users\me\PycharmProjects\pythonProject\project\main.py", line 112, in <module>
pdf.set_font(heading)
File "C:\Users\me\PycharmProjects\pythonProject\project\venv\lib\site-packages\fpdf\fpdf.py", line 567, in set_font
family=family.lower()
AttributeError: 'list' object has no attribute 'lower'
So I was wondering, is there any other way to achieve this?
Try to use this:
pdf.set_font(*heading)

Pydub Split on silence error: UnboundLocalError: local variable 'start_ii' referenced before assignment

I try to get a python code running with the pydub library that should split an audio file on silent parts. The code is pretty short but still I get errors that I can't understand. Thanks a lot for your help:
Complete error message:
Traceback (most recent call last):
File "app.py", line 7, in <module>
chunks = split_on_silence(sound,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pydub/silence.py", line 134, in split_on_silence
chunks.append(audio_segment[max(start_min, start_ii - keep_silence):
UnboundLocalError: local variable 'start_ii' referenced before assignment
Code:
from os import path
from pydub import AudioSegment
from pydub.silence import split_on_silence
sound = AudioSegment.from_mp3("test5.mp3")
chunks = split_on_silence(sound,
# must be silent for at least half a second
min_silence_len=500,
# consider it silent if quieter than -16 dBFS
silence_thresh=-16
)
for i, chunk in enumerate(chunks):
chunk.export("chunk{0}.wav".format(i), format="wav")
You need to adjust your silence_thresh argument. You can start by assigning it the value you get when you call sound.dBFS, then adjust the value till it works or you.

Trouble obtaining data from multiple *.root files...but no problems using only one

I am using pythong version 3.6.5 and have a jagged TTree with a multi-dimensional structure. This data is spread over more than 1000 files, all with the same identical TTree structure.
suppose I have two files though and I'll call them
fname1.root
fname2.root
The following code has no problem opening either of these by itself:
import uproot as upr
import awkward
import boost_histogram as bh
import math
import matplotlib.pyplot as plt
#
# define a plotting program
# def plotter(h)
#
# preparing the file location for files
pth = '/fullpathName/'
fname1 = 'File755.root'
fname2 = 'File756.root'
fileList = [pth+fname1, pth+fname2]
#
# print out the path and filename that I've made to show the user
for file in fileList:
print(file)
print('\n')
#
# Let's make a histogram This one has 50 bins, starts at zero and ends at 1000.0
# It will be a histogram of Jet pT's.
jhist = bh.histogram(bh.axis.regular(50,0.0,1000.0))
#
#show what you've just done
print(jhist)
#
# does not work, only fills first file!
for chunk in upr.iterate(fileList,"bTag_AntiKt4EMTopoJets",["jet_pt"]):
jhist.fill(chunk[b"jet_pt"][:, :2].flatten()*0.001)
#
#
# what does my histogram look like?
ptHist = plt.bar(jhist.axes[0].centers, jhist.view(), width=jhist.axes[0].widths)
plt.show()
As I said, the above code works if I put only ONE file in 'fileList'.
The naive thing to do doesn't work.
If I create a 'list' of files using
files = [pth+fname1 , pth+fname2]
and re-run that code. I get the following error...which is very much the same error I have been getting all along.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 48, in <module>
File "/home/huffman/.local/lib/python3.6/site-packages/uproot/tree.py", line 116, in iterate
for tree, branchesinterp, globalentrystart, thispath, thisfile in _iterate(path, treepath, branches, awkward, localsource, xrootdsource, httpsource, **options):
File "/home/huffman/.local/lib/python3.6/site-packages/uproot/tree.py", line 163, in _iterate
file = uproot.rootio.open(path, localsource=localsource, xrootdsource=xrootdsource, httpsource=httpsource, **options)
File "/home/huffman/.local/lib/python3.6/site-packages/uproot/rootio.py", line 54, in open
return ROOTDirectory.read(openfcn(path), **options)
File "/home/huffman/.local/lib/python3.6/site-packages/uproot/rootio.py", line 51, in <lambda>
openfcn = lambda path: MemmapSource(path, **kwargs)
File "/home/huffman/.local/lib/python3.6/site-packages/uproot/source/memmap.py", line 21, in __init__
self._source = numpy.memmap(self.path, dtype=numpy.uint8, mode="r")
File "/cvmfs/sft.cern.ch/lcg/views/LCG_94python3/x86_64-slc6-gcc8-opt/lib/python3.6/site-packages/numpy/core/memmap.py", line 264, in __new__
mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start)
OSError: [Errno 12] Cannot allocate memory
Lazy arrays are just an interface for convenience—i.e. you can transform it with one function call, rather than iterating in an explicit loop over chunks. Internally, lazy arrays contain an implicit loop over chunks, so if you're running out of memory one way, you would be the other way.
Your problem is not closing files (they're memory-mapped, so "closing" didn't have a clear meaning—they're a view into memory that the operating system is allocating for itself, anyway)—your problem is with deleting arrays. That's the only thing that can use up all the memory on your computer.
There are a few things you can do here: one is to
for chunk in uproot.iterate(files, "bTag_AntiKt4EMTopoJets", ["jet_pt", "jet_eta"]):
# fill with chunk[b"jet_pt"] and chunk[b"jet_eta"], which correspond
# to the same sets of events, one-to-one.
to explicitly loop over the chunks ("explicit" because you see and control the loop here, and because you have to specify which branches you want to load into the dict chunk). You can control the size of the chunks with entrysteps. The other is to
cache = uproot.ArrayCache("1 GB")
events = uproot.lazyarrays(files, "bTag_AntiKt4EMTopoJets", cache=cache)
to keep the loop implicit. The ArrayCache will throw out chunks of arrays, so that they have to be loaded again, if it gets to the 1 GB limit. If you make that limit too small, it won't be able to hold one chunk, but if you make it too large, you'll run out of memory.
By the way, although you're reporting a memory issue, there's another major performance issue with your code: you're looking over events in Python. Instead of
events.jet_pt[i][:2]*0.001
to get the jet pT for event i, do
events.jet_pt[:, :2]*0.001
for the jet pT of all events as a single array. You might then need to .flatten() that array to fit the histogram's fill method.

PyPDF2, why am I getting an index error? List index out of range

I'm following along in Al Sweigart's book 'Automate the Boring Stuff' and I'm at a loss with an index error I'm getting. I'm working with PyPDF2 tring to open an encrypted PDF document. I know the book is from 2015 so I went to the PyPDF2.PdfFileReader docs to see if I'm missing anything and everything seems to be the same, at least from what I can tell. So I'm not sure what's wrong here.
My Code
import PyPDF2
reader = PyPDF2.PdfFileReader('encrypted.pdf')
reader.isEncrypted # is True
reader.pages[0]
gives:
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
pdfReader.getPage(0)
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1176, in getPage
self._flatten()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1505, in _flatten
catalog = self.trailer["/Root"].getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/generic.py", line 516, in __getitem__
return dict.__getitem__(self, key).getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/generic.py", line 178, in getObject
return self.pdf.getObject(self).getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1617, in getObject
raise utils.PdfReadError("file has not been decrypted")
PyPDF2.utils.PdfReadError: file has not been decrypted
pdfReader.decrypt('rosebud')
1
pageObj = reader.getPage(0)
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
pageObj = pdfReader.getPage(0)
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py",line 1177, in getPage
return self.flattenedPages[pageNumber]
IndexError: list index out of range
Before asking my question, I did some searching on Google and found this link with a "proposed fix". However, I'm to new at this to see what the fix is. I can't make heads or tails out of this.
I figured it out. The issue is caused by running 'pdfReader.getPage(0)' before you decrypt the file in the IDLE shell. If you take that line out, or start over without using that line after getting the error it will work as it should.
Same error I got. I was working on console and before decrypt I used reader.getPage(0).
Don't use getPage(#) / pages[#] before decrypt.
use code like below:
reader = PyPDF2.PdfFileReader("file.pdf")
# reader.pages[0] # do not use this before decrypt
if reader.isEncrypted:
reader.decrypt('')
reader.pages[0]

select random item (and not pick this one for the next random pick up) from list created from a file

I'm trying to build a program that will pick a random items (just once for each) from a list, that was imported from a file.
NB: I put only one item for a line in my file (no space, no coma, nothing else than a simple word)
I have a code like that for now:
file = open('file.txt', 'r')
myList = file.readlines()
myList[0]
rand_item = random.choice(myList)
print (rand_item)
I am just at the beginning of my program, so I'm just testing every new step that i make. Here, I'd like to display a random item from my list (itsefl imported from a file).
I have this message when I try to run my program:
Traceback (most recent call last):
File "C:/Users/Julien/Desktop/test final.py", line 16, in <module>
rand_item = random.choice(listEmployee)
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'

Resources