python – When using pygame and pyinstaller I get an error telling me “excpected str, bytes or os.Pathlike object, not BytesIO

I’ve been making a small game in pygame where you click on a rectangle, it disappears with a small animation and then pops up in a new random place on the screen. I used pyinstaller to make the file executable so my friends could try out what I made, but when I made the exe with pyinstaller (file) –onefile –noconsole and then opened it in the same folder as my assets folder, this error pops up.
Any ideas?

enter image description here

enter image description here

join – python – split and get the part of a str before the last occurrence of separator

I am trying to extract certain part of some strings. These strings look like

a = "1_2_3"
b = "1_2_3_4"

I would want to get everything of each string before the last underscore so:


I thought this line should work:


but it gives me the error: AttributeError: ‘str’ object has no attribute ‘joint’

However, apparently, a.split("_")(:-1) is not a str but a list (I checked by type(a.split("_")(:-1))). Does anyone know why this happens and how to solve it?

dnd 3.5e – What is monk off-hand str damage bonus when using unarmed two-weapon fighting

That would seem to be consistent with the ruling you assume in the question.

The source of this confusion is this:

There is no such thing as an off-hand attack for a monk striking unarmed. A monk may thus apply her full Strength bonus on damage rolls for all her unarmed strikes.

It’s not at all clear why this sentence exists or what it really means. The literal meaning of the words—that the monk loses the ability to make offhand attacks with unarmed strikes—makes no sense at all since the sentence prior to this is

A monk’s attacks may be with either fist interchangeably or even from elbows, knees, and feet. This means that a monk may even make unarmed strikes with her hands full.

They are emphasizing here that a monk is good at making more attacks with unarmed strikes—why would they therefore be incapable of doing so? And if we assume that this doesn’t mean they’re incapable of doing so—as the question does—what else could these sentences mean?

The only reasonable explanation that I can imagine is that they were imagining the monk making these attacks as part of a flurry of blows; they seem to never consider the idea that a monk may want to use two-weapon fighting when they have flurry of blows available. The rules for flurry of blows make the same statement about using 1×Str for damage rolls—not ½×, as for an offhand attack, and not 1½×, as for a two-handed attack—and it would be very appropriate and consistent for flurry of blows to specify that none of the attacks made during a flurry of blows are considered offhand.

Unfortunately, that’s not where they put the rule. They put the rule in unarmed strikes, and that causes immense confusion.

Anyway, assuming you don’t buy that a monk’s mastery of unarmed strikes makes them somehow incapable of using them with two-weapon fighting, it makes sense for you to ignore the other “half” of that blurb and apply the ½×Str to damage, too. Otherwise what we’re doing is selectively ignoring the rule we don’t like (“There is no such thing as an off-hand attack for a monk striking unarmed.”) while still taking advantage of the rule we do even though it builds off the rule we’re ignoring (“A monk may thus apply her full Strength bonus on damage rolls for all her unarmed strikes,” emphasis mine), which is inconsistent. If we’re going to ignore it, we should do so consistently.

Of course, if we want to take this beyond the realm of “ruling” and into outright “houserules,” allowing the monk to make offhand unarmed strikes, and still get full Str bonus to damage on them, is entirely reasonable: the monk is a terrible class and it’s a bone we can easily toss them. Won’t fix the problems with the monk class on its own, though, not by a long shot.

python – TypeError: string indices must be integers, not str iterando un json

El json es este, que es la variable y, que esta transformando en json result_set, basicamente con ese for y la lista counter, quiero coger los datos ‘monitorCounter’ y mostrarlos.

[[[“cn=Monitor”, {}]], [[“cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
0,cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
1,cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
2,cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
3,cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
4,cn=Backends,cn=Monitor”, {}]], [[“cn=Backend
5,cn=Backends,cn=Monitor”, {}]], [[“cn=Connections,cn=Monitor”, {}]],
[[“cn=Connection 1016,cn=Connections,cn=Monitor”,
{“monitorConnectionRead”: [“2”], “monitorConnectionGet”: [“2”],
“monitorConnectionOpsReceived”: [“2”],
“monitorConnectionOpsCompleted”: [“1”], “monitorConnectionNumber”:
[“1016”], “monitorConnectionWrite”: [“0”],
“monitorConnectionOpsExecuting”: [“1”], “monitorConnectionOpsPending”:
[“0”]}]], [[“cn=Max File Descriptors,cn=Connections,cn=Monitor”,
{“monitorCounter”: [“1024”]}]],
[[“cn=Total,cn=Connections,cn=Monitor”, {“monitorCounter”:
[“1017”]}]], [[“cn=Current,cn=Connections,cn=Monitor”,
{“monitorCounter”: [“1”]}]], [[“cn=Databases,cn=Monitor”, {}]],
[[“cn=Frontend,cn=Databases,cn=Monitor”, {}]], [[“cn=Database
0,cn=Databases,cn=Monitor”, {}]], [[“cn=Database
1,cn=Databases,cn=Monitor”, {}]], [[“cn=Database
2,cn=Databases,cn=Monitor”, {“olmBDBEntryCache”: [“0”],
“olmBDBIDLCache”: [“0”], “olmBDBDNCache”: [“0”]}]],
[[“cn=Listeners,cn=Monitor”, {}]], [[“cn=Listener
0,cn=Listeners,cn=Monitor”, {}]], [[“cn=Listener
1,cn=Listeners,cn=Monitor”, {}]], [[“cn=Listener
2,cn=Listeners,cn=Monitor”, {}]], [[“cn=Log,cn=Monitor”, {}]],
[[“cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“50”],
“monitorOpCompleted”: [“49”]}]], [[“cn=Bind,cn=Operations,cn=Monitor”,
{“monitorOpInitiated”: [“17”], “monitorOpCompleted”: [“17”]}]],
[[“cn=Unbind,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“16”],
“monitorOpCompleted”: [“16”]}]],
[[“cn=Search,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“17”],
“monitorOpCompleted”: [“16”]}]],
[[“cn=Compare,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“0”],
“monitorOpCompleted”: [“0”]}]],
[[“cn=Modify,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“0”],
“monitorOpCompleted”: [“0”]}]],
[[“cn=Modrdn,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“0”],
“monitorOpCompleted”: [“0”]}]], [[“cn=Add,cn=Operations,cn=Monitor”,
{“monitorOpInitiated”: [“0”], “monitorOpCompleted”: [“0”]}]],
[[“cn=Delete,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“0”],
“monitorOpCompleted”: [“0”]}]],
[[“cn=Abandon,cn=Operations,cn=Monitor”, {“monitorOpInitiated”: [“0”],
“monitorOpCompleted”: [“0”]}]],
[[“cn=Extended,cn=Operations,cn=Monitor”, {“monitorOpInitiated”:
[“0”], “monitorOpCompleted”: [“0”]}]], [[“cn=Overlays,cn=Monitor”,
{}]], [[“cn=Overlay 0,cn=Overlays,cn=Monitor”, {}]],
[[“cn=SASL,cn=Monitor”, {}]], [[“cn=Statistics,cn=Monitor”, {}]],
[[“cn=Bytes,cn=Statistics,cn=Monitor”, {“monitorCounter”:
[“55414”]}]], [[“cn=PDU,cn=Statistics,cn=Monitor”, {“monitorCounter”:
[“928”]}]], [[“cn=Entries,cn=Statistics,cn=Monitor”,
{“monitorCounter”: [“896”]}]],
[[“cn=Referrals,cn=Statistics,cn=Monitor”, {“monitorCounter”:
[“0”]}]], [[“cn=Threads,cn=Monitor”, {}]],
[[“cn=Max,cn=Threads,cn=Monitor”, {}]], [[“cn=Max
Pending,cn=Threads,cn=Monitor”, {}]],
[[“cn=Open,cn=Threads,cn=Monitor”, {}]],
[[“cn=Starting,cn=Threads,cn=Monitor”, {}]],
[[“cn=Active,cn=Threads,cn=Monitor”, {}]],
[[“cn=Pending,cn=Threads,cn=Monitor”, {}]],
[[“cn=Backload,cn=Threads,cn=Monitor”, {}]],
[[“cn=State,cn=Threads,cn=Monitor”, {}]],
[[“cn=Runqueue,cn=Threads,cn=Monitor”, {}]],
[[“cn=Tasklist,cn=Threads,cn=Monitor”, {}]], [[“cn=Time,cn=Monitor”,
{}]], [[“cn=Start,cn=Time,cn=Monitor”, {}]],
[[“cn=Current,cn=Time,cn=Monitor”, {}]],
[[“cn=Uptime,cn=Time,cn=Monitor”, {}]], [[“cn=TLS,cn=Monitor”, {}]],
[[“cn=Waiters,cn=Monitor”, {}]], [[“cn=Read,cn=Waiters,cn=Monitor”,
{“monitorCounter”: [“1”]}]], [[“cn=Write,cn=Waiters,cn=Monitor”,
{“monitorCounter”: [“0”]}]]]

python 3.x – TypeError: __str__ returned non-string (type User)

I’ve Been Trying to Work This Model But In Class Paid Videos I’m getting Error

makemigrations is working , migrations working but when I runserver and opensenter code here the site IT shows me error I tried doing which I marked in code

from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator

# Create your models here.

def Validate(A):
    if post.objects.filter(post.post_type !='Paid'):
        raise ValidationError('If You Want to Set Amount On Your Content You Have to Set Paid Content Type')

class paid_videos(models.Model):
    paid_id = models.AutoField(primary_key=True)
    post_timestamp = models.ForeignKey(post, on_delete=models.CASCADE)
    post_amount = models.PositiveIntegerField(validators = (MaxValueValidator(999),Validate))

    # def __str__(self): <- <- I tried this
    #     return self.post_timestamp #also for other 2 fields 

mysql – Convertir query de SQL en str Python

estoy teniendo un problema. Estoy leyendo unos datos de mi base de datos en MySQL desde python. El problema que tengo es que los datos los obtengo como una tupla.
Y necesito convertir esos datos a un str, para hacer una segunda consulta.

Esta seria mi consulta

consulta = "SELECT id_articulo FROM articulos WHERE tipo_articulo = %s AND talle = %s " 
                   "AND marca = %s AND material = %s"
        sql_cursor.execute(consulta, (tipo, talle, marca, material))
        aux = sql_cursor.fetchall()

El dato que obtengo en aux es una tupla, y despues no puedo usar ese dato para hacer otra consulta en sql por que es una tupla.

¿Alguna forma de pasar ese dato a un str?

Acrescentar um caractere a uma str em python

Tenho uma data de nascimento onde preciso q o programa leia a informação e digite o dia, mes e ano usando pyautogui. Pra função WRITE funcionar, preciso transformar a data, que é um número inteiro, em uma str.
O local onde preciso digitar essas datas, possuem 2 digitos: 01, 02, 03… 14… 30 e 31.
Quando a str possue 2 digitos (de 10 adiante) o programa roda tranquilamente e digita as dezenas sem problemas, porém quando a data se torna com 1 digito, ele imprime somente uma casa e não consigo digitar o 06, por exemplo e digitando apenas 6 nao da.

> > import datetime    
    import pyautogui
> > 
> > data_atual = 
    day = day =
> > str(day)
> > 
> > pyautogui.write(day) # nesse caso imprime 24 pq hj é 24 mas em dias 1,2,3...9 eu tenho problemas.

O pyautogui não imprime numeros inteiros, então existe a necessidade de transformar o numero inteiro em uma str, porém complica em numeros de 1 digito apenas. Uma solução que encontrei pra consertar isso, foi incluir um IF pra todo resultado de 1 a 9:

> if day == '1':
>     pyautogui.write('01')  
elif day == '2':
>     pyautogui.write('02')
elif day == '9':
>     pyautogui.write('09') else:
>     pyautogui.write(day)

gostaria de algo mais simples pra inserir um 0 na sting day quando ela tivesse apenas 1 digito sem ter q usar tantas linhas de comando como no if. A inserção do 0 deve vir na frente pra transformar 1, 2, 3… em 01, 02, 03…

python – Error can’t convert type ‘str’ to numerator/denominator while calculating population standard deviation in pythin

I am trying to calculate the population standard deviation of my data frame in python. I am using the function statistics.pstdev(df) by importing statistics Library. I have exclude all the non float columns from my dataset and it contain only float data columns. But I am getting the following error while executing.

TypeError                                 Traceback (most recent call last)
<ipython-input-118-f8b494b6fd29> in <module>()
      1 import statistics
----> 2 statistics.pstdev(tot2)

5 frames
/usr/lib/python3.6/ in pstdev(data, mu)
    665     """
--> 666     var = pvariance(data, mu)
    667     try:
    668         return var.sqrt()

/usr/lib/python3.6/ in pvariance(data, mu)
    635     if n < 1:
    636         raise StatisticsError('pvariance requires at least one data point')
--> 637     T, ss = _ss(data, mu)
    638     return _convert(ss/n, T)

/usr/lib/python3.6/ in _ss(data, c)
    533     """
    534     if c is None:
--> 535         c = mean(data)
    536     T, total, count = _sum((x-c)**2 for x in data)
    537     # The following sum should mathematically equal zero, but due to rounding

/usr/lib/python3.6/ in mean(data)
    310     if n < 1:
    311         raise StatisticsError('mean requires at least one data point')
--> 312     T, total, count = _sum(data)
    313     assert count == n
    314     return _convert(total/n, T)

/usr/lib/python3.6/ in _sum(data, start)
    146     for typ, values in groupby(data, type):
    147         T = _coerce(T, typ)  # or raise TypeError
--> 148         for n,d in map(_exact_ratio, values):
    149             count += 1
    150             partials(d) = partials_get(d, 0) + n

/usr/lib/python3.6/ in _exact_ratio(x)
    228         return (x, None)
    229     msg = "can't convert type '{}' to numerator/denominator"
--> 230     raise TypeError(msg.format(type(x).__name__))

TypeError: can't convert type 'str' to numerator/denominator

dnd 5e – Dhampir bite attack, does it add both STR and CON?

The Vampiric Bite, from the new Dhampir lineage race, says as follow (emphasis mine):

Vampiric Bite

“Your fanged bite is a natural weapon, which counts as a simple melee weapon with which you are proficient. You add your Constitution modifier to the attack and damage rolls when you attack with your bite. Your bite deals 1d4 piercing damage on a hit. While you are missing half or more of your hit points, you have advantage on attack rolls you make with this bite.”

Normally, a simple melee weapon attack works as follow:

Attack Rolls

To make an Attack roll, roll a d20 and add the appropriate modifiers.

Modifiers to the Roll

Ability Modifier
The ability modifier used for a melee weapon Attack is Strength, and the ability modifier used for a ranged weapon Attack is Dexterity.(…)

Proficiency Bonus
You add your Proficiency Bonus to your Attack roll when you Attack using a weapon with which you have proficiency, as well as when you Attack with a spell.

This translates into rolling 1d20 + STR modifier + Proficiency bonus.

Does it mean that a Vampiric Bite attack adds CON modifier to the above formula (1d20 + STR mod + Proficiency bonus + CON mod)?

Same question for the damage roll:

Damage rolls

When attacking with a weapon, you add your ability modifier—the same modifier used for the Attack roll—to the damage.

Normally for a melee weapon the attack formula is (weapon-damage-die) + STR modifier.
If another modifier is used, instead of the usual one, the wording is different from what we see in the Vampiric Bite. An example is Finesse weapons, which say as follow:


When Making an Attack with a finesse weapon, you use your choice of your Strength or Dexterity modifier for the Attack and Damage Rolls. You must use the same modifier for both rolls.

Is it correct to say that, unlike Finesse weapons, the Vampiric bite does not replace the STR modifier with CON, but rather adds both (making the damage formula 1d4 (weapon-dmg-die) + STR modifier + CON modifier)?

pandas – Python 3 error : ‘value’ must be an instance of str or bytes, not a int

necesito sacar una gráfica usando pandas con matplotlib, igual que esta introducir la descripción de la imagen aquí

Debe incluir los datos Totales, y en el Eje Y debe aparecer la columna “Total”, y en el Eje X la columna “periodo”.

Mi problema viene una vez terminado el código, me indica este error – ‘value’ must be an instance of str or bytes, not a int-.

Adjunto mi código:

import pandas as pd
import matplotlib.pyplot as plt
headers = ('Periodo', 'Total')
tabla_totales = pd.read_csv('ine_mortalidad_espanna.csv', sep=';', names=headers)

x = tabla_totales('Periodo')
y = tabla_totales('Total')

# plot