convert a tuple of tuples into bytes in python - python

I'm making a video game in upbge (which for this aspect is basically python) but to send the info between sockets it needs to be in bytes but i only found a way to do it turning it into a string, (because the list get's created with the game (i have a script that once a new entity appears it get's added to the list in the form of (Player-entity|data) but i want the data to variate between entities and i ran out of symbols to use to split it into lists so i'm trying to send the data as a list to be able to simply check it's components, but as it's a list inside of a list (and sometimes more) the bytearray won't work (at least i can't figure out how to make it work)
I'm unsure of how to summarize the code, but this is the code that I have now to generate that info
import socket
mi_socket = socket.socket()
mi_socket.bind(('127.0.0.1',55555))
mi_socket.listen()
TP = 0 #Total players
AP = 0 #Actual player
PL = ["host"] #Player List
AE = 0 #Actual entity
TE = 0 #Total entities
EL = ["|PlayerEntity$[Data]|"] #Entity list
PI = [] #Player Intel (Player name, Total Players, Player Code) (apartado uno en las comunicaciones)
order = None #Variable reservada para guardar comandos u identificaciones (ej: nombre de la entidad) en las comunicaciones
content = None #Variable reservada para almacenar la información recibida
incoming = 0 #Variable reservada para analizar el mensaje recibido de entrada
def login():
global AP
global TP
global PL
PJ = str(incoming).split("$")[1] #incoming Player
if AP <= TP:
if PJ!=str(PL[int(AP)]): #Nombre jugador que se conecta
AP+=1
login()
pass
else:
identity()
pass
if AP > TP:
PL.append(str("Player" + str(AP))) #Agregar jugador a la lista
TP = int(AP)
def identity(): #identifica de qué se trata la orden para responder en consecuencia, si se trata de entidad anota tmb la entidad en la lista
global TE
global AE
global EL
global AP
global PL
PJ = str(incoming).split("$")[1] # incoming Player
PE = str(incoming).split("$")[2] # incoming entity
if AE <= TE:
# Si nombre de jugador|nombre de objeto no és EL[AE]([1]|[2])
if str(str(PL[AP])+"-"+str(PE)) != str(str(EL[AE]).split("|")[1]).split("$")[0]:
AE+=1
identity()
pass
else:
EL[AE] = "|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|"
if AE > TE:
EL.append("|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|")
TE = int(AE)
def main():
global AP
global AE
global TE
global incoming
conexion, ip = mi_socket.accept()
incoming = conexion.recv(1024)
login()
conexion.send(str("#"+str(PL[AP])+"#"+str(EL[1:TE+1])+"#").encode())
AP=0
AE=0
conexion.close()
while True:
main()

Related

Is there any solution to create a multi option with secondary options menu for whatsapp using twilo and flask?

I trying to make a whatsapp bot which returns a response for specifics messages
#app.route("/sms", methods=['POST'])
def sms_reply():
# Fetch the message
msg = request.form.get('Body').lower()
responded = False
if ("hola" in msg or "buenos" in msg or "buenas" in msg or "info" in msg or "holi" in msg):
reply = "Buenos días bienvenido a Alcanza soy tu asistente virtual, ¿con quien tengo el gusto?"
menu = "Por Favor, selecciona la opcion de tu preferencia: 1 Citas con asesores 2 Informacion de servicios 3 Herramientas de diagnostico 4 Servicio al cliente"
resp = MessagingResponse()
resp.message(reply)
resp.message(menu)
elif ("1" in msg):
reply = "Bienvenido al menu de citas con asesores, por favor selecciona una opcion: 1 Agendar una cita 2 Modificar una existente 3Cancelar una cita 0 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
elif ("2" in msg):
reply = "Bienvenido al menu de informacion de servicios, por favor seleciona un servicio para recibir mas informacion: Finanzas personales 1 Asesoría de inversión 2 Webinars y capacitaciones 3 Alcanza 360 0 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
elif ("3" in msg):
reply = "Bienvenido al menu de herramientas de diagnostico, por favor seleciona la herramienta que necesitas: 1 Cuestionario de diagnóstico financiero 2 Perfil de deuda 3 Perfil de inversión 4 Costo de tu tiempo 5 Pago de tarjeta de crédito 6 Volver al menú principal"
resp = MessagingResponse()
resp.message(reply)
return str(resp)
So I create this function and when I get the input message "1" from whatsapp the code return me a sub menu, the point is that I want to add another if statement into de principal ifs with more options, for example first input== "1" return (sub menu) and first input == "1" and second input == "1" return (option 1 of the sub menu), I tried too many times and different ifs but the code stops working or ignore the sub ifs

CNN in python. Array of images

I was trying to deeply search for a solution online before posting here, but I couldn't find it. My problem arises during the reading of images in a training of a convolutional neural network. Basically, I decided to create a function creating the in values and the out values out of a series of images. I want to read all the images of the set, but not all at the same time, to avoid running out of memory, so I create the next function:
def readImages(strSet = 'Train', nIni = 1, nFin = 20):
if strSet not in ('Train','Test'):
return None
#
# Inicializamos los arrays de salida: las imágenes y las etiquetas.
arrImages = []
arrLabels = []
#
# Recorremos todos y cada uno de los directorios dentro del set elegido
for strDir in os.listdir(data_dir+'/' + strSet + '/'):
# Nombre de la clase que estamos tratando.
strClass = strDir[strDir.find('-')+1:]
# Número y nombre de los ficheros, por si es menor que el número n indicado.
arrNameFiles = os.listdir(data_dir+'/' + strSet + '/'+strDir)
nFiles = len(os.listdir(data_dir+'/' + strSet + '/'+strDir))
#
# Cogemos los ficheros desde el nIni al nFin. De esta forma nos aseguramos los cogemos todos en cada directorio.
#print('nImagesClase(',strSet,',',strClass,'):',nImagesClase(strSet, strClass))
if (nIni == -1):
# Si el valor es -1, cogemos todas las imágenes del directorio.
listChosenFiles = arrNameFiles
#print('Todos: ', len(listChosenFiles))
else:
if (nImagesClase(strSet, strClass)<nFin):
# Si ya hemos dado la vuelta a todos los ficheros del grupo, los cogemos al azar.
listChosenFiles = random.sample(arrNameFiles, min(nFiles, nFin-nIni))
#print('Fin del directorio ',nFin,'>',nImagesClase(strSet,strClass),': ', len(listChosenFiles))
else:
# Si no, seguimos.
listChosenFiles = arrNameFiles[nIni-1:min(nFin,nImagesClase(strSet, strClass))-1]
#print('Seguimos ',nIni,'-',nFin,': ', len(listChosenFiles))
#
for file in listChosenFiles:
# Lectura del fichero.
image = plt.imread(data_dir+'/'+strSet+'/'+strDir+'/'+file)
#print('Original Shape: ',image.shape)
#plt.imshow(image)
image = cv2.resize(image, (crop_width, crop_height), interpolation=cv2.INTER_NEAREST)
#image = image.reshape((image_height,image_width,num_channels))
#print('Al array de imágenes: ',image.shape)
arrImages.append(image)
# Añadimos etiquetas.
arrLabel = np.zeros(n_classes)
arrLabel[array_classes.index(strClass)] = 1
arrLabels.append(arrLabel)
#
# Recogemos los valores de entrada y salida en arrays.
y = np.array(arrLabels)
X = np.array(arrImages, dtype=np.uint8)
# Una vez terminado el recorrido por todas las imágenes, reordenamos los índices para que no vayan las imágenes en secuendias de la misma clase.
arrIndexes = np.arange(X.shape[0])
np.random.shuffle(arrIndexes)
X = X[arrIndexes]
y = y[arrIndexes]
#
return X, y
To test the behavior of this function I just execute the following line.
X, y = readImages(strSet = 'Train', nIni = 1, nFin = 5)
Which is ok, until the moment nIni and nFin reach some values (101-105, for example). In that moment, I receive the following error:
ValueError Traceback (most recent call last)
<ipython-input-125-8a690256a1fc> in <module>
----> 1 X, y = readImages(strSet = 'Train', nIni = 101, nFin = 105)
<ipython-input-123-9e9ebc660c33> in readImages(strSet, nIni, nFin)
50 # Recogemos los valores de entrada y salida en arrays.
51 y = np.array(arrLabels)
---> 52 X = np.array(arrImages, dtype=np.uint8)
53 # Una vez terminado el recorrido por todas las imágenes, reordenamos los índices para que no vayan las imágenes en secuendias de la misma clase.
54 arrIndexes = np.arange(X.shape[0])
ValueError: could not broadcast input array from shape (28,28,3) into shape (28,28)
I put some print traces in the reading of the images, and everyone of the read images has a shape of (28,28,3), so I don't really understand from where do I have this (28,28) shape pointed out in the error trace.
Do you know what could be the problem? Did you face this problem earlier?
Thanks in advance.
Some of your images have single channels. Use cv2.imread instead of plt.imread
image = cv2.imread(data_dir+'/'+strSet+'/'+strDir+'/'+file)

Python Function Exception Error

I've writen a code you'll find below but it doesn't work. I get an indentation error. This is the message I've received from cmd.
Can you tell me where I've done the mistake?
loan = input("indiquer le montant de l'emprunt")
loan = float(loan)
duree = input("indiquer la durée de l'emprunt en mois")
duree = int(duree)
principal = loan / duree
tauxinteret = input("mettre le taux d'intéret")
tauxinteret = float(tauxinteret)
interets = principal * tauxinteret
assurance = input("indiquer le montant des assurances")
assurance = float(assurance)
mensualite = principal + interets + assurance
return mensualite
print("Mr l'esclave, la mensualité à payer s'élève à {} dirhams". format (mensualite)")
calcul_mensualite(mensualite)
Have a look at defining functions in Python (seems like you tried to do that) - after def you need to indent next lines:
def my_function():
print("Hello from a function")
my_function()
And here's the link to the basics:
functions
You seem to have left out the define statement of the method. You will again get an indentation error because you have included a return statement outside of a method. The following code should work fine after removing the return statement.
loan = input("indiquer le montant de l'emprunt")
loan = float(loan)
duree = input("indiquer la durée de l'emprunt en mois")
duree = int(duree)
principal = loan / duree
tauxinteret = input("mettre le taux d'intéret")
tauxinteret = float(tauxinteret)
interets = principal * tauxinteret
assurance = input("indiquer le montant des assurances")
assurance = float(assurance)
mensualite = principal + interets + assurance
print("Mr l'esclave, la mensualité à payer s'élève à {} dirhams". format (mensualite)")
Sorry for you all. there is one missing line in my code:
def calcul_mensualite (loan, principal, duree,tauxinteret, interets, assurance, mensualite):

correct way to implement thread python

I am implement a simple simulator of soccer with python using threads and lock, the app works fine but I have doubts in the way that implement the thread it seems to me that the first team has an advantage because is executing first.
def jugar(Equipo1, Equipo2):
# Busco las probabilidades de encajar por cada equipo
prob_encajar_eq1 = Equipo1.probabilidad_encajar()
prob_encajar_eq2 = Equipo2.probabilidad_encajar()
def jugar_equipo1(defensa_rival):
semaforo.acquire()
if Equipo1.hacer_pases():
Equipo1.shoot(defensa_rival)
semaforo.release()
def jugar_equipo2(defensa_rival):
semaforo.acquire()
if Equipo2.hacer_pases():
Equipo2.shoot(defensa_rival)
semaforo.release()
hilo_equipo1 = threading.Thread(name = 'hilo_eq1', target = jugar_equipo1, args = (prob_encajar_eq2,))
hilo_equipo2 = threading.Thread(name = 'hilo_eq2', target = jugar_equipo2, args = (prob_encajar_eq1,))
hilo_equipo1.start()
hilo_equipo2.start()
hilo_equipo1.join()
hilo_equipo2.join()
to make several attempts both teams, I do a cicle for a few seconds and inside the function jugar() which is the one that does the work with threads but here is were I have the doubts, because every time that jugar is executing the threads are declared again.
if __name__ == '__main__':
cargar_informacion()
eqA = Equipo(equipoA, ranking_eqA)
eqB = Equipo(equipoB, ranking_eqB)
probabilidades = porcenajes_ranking(ranking_eqA)
eqA.cargar_probabilidades(probabilidades)
probabilidades = porcenajes_ranking(ranking_eqB)
eqB.cargar_probabilidades(probabilidades)
starttime=time.time()
tiempo = 0
# creo la barra de progreso
bar = progressbar.ProgressBar(widgets=[
progressbar.Percentage(),
progressbar.Bar(),
], max_value=100).start()
# hacemos que el juego tarde aproximadamente 10seg en simularse.
while tiempo < 10:
time.sleep(0.3 - ((time.time() - starttime) % 0.3))
jugar(eqA,eqB)
tiempo = time.time() - starttime
bar += 2.8
bar.finish() # Para que finalice la barra de progreso
resultados_finales(eqA, eqB) # Mostramos el resultado final del partido.

How to use Python re module to replace \n with nothing in a single file

Regards to all.
I'm developing a Image compression system using Python Image Library. The basic workflow is:
Read all images of a certain directory with : find /opt/images -name *.jpg > /opt/rs/images.txt
Read this file and storage the result in a Python list
Iterate the list, create a Image object and passing like a argument to
the compress function
and, copy the resulting image on a certain directory which is buit
depending of the name of the image.
A example:
/opt/buzon/17_499999_1_00000000_00000999_1.jpg
This is the real name of the image:
The final result is:
17_499999.jpg
The ouput directory is: /opt/ftp
and should be storaged on this way:
1- first partition
00000000 - second partition
00000999 - third partition
1- this flag if to decide if we have to compress this image or not (1 is False, 0 is True)
For that reason the final path of the image is:
/opt/ftp/1/00000000/00000999/17_499999.jpg for the original copy
/opt/ftp/1/00000000/00000999/17_499999_tumb.jpg
Now, Where is the problem. When I read the file where I storage the result of the find command, each line of the file has the \n character.
How I can replace with regular expressions this?
The completed source code is this. Any suggests is welcome.
import Image, os ,sys, re, subprocess, shlex
import ConfigParser
from symbol import except_clause
CONFIG_FILE = "/opt/scripts/config.txt"
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
entry_dir = config.get('directories', 'entry_dir')
out_dir = config.get('directories', 'out_dir')
def resize(img, box, fit, out):
'''Downsample the image.
#param img: Un objeto de la clase Imagen
#param box: tuple(x, y) - El recuadro de la imagen resultante
#param fix: boolean - el corte de la imagen para llenar el rectangulo
#param out: objeto de tipo fichero - guarda la imagen hacia la salida estandar
'''
# prepara la imagen con un factor de 2, 4, 8 y el algoritmo mas rapido
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
# Aqui se calcula el rectangulo optimo para la imagen
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = y2/2-box[1]*wRatio/2
y2 = y2/2+box[1]*wRatio/2
else:
x1 = x2/2-box[0]*hRatio/2
x2 = x2/2+box[0]*hRatio/2
# Este metodo es para manipular rectangulos de una determinada imagen
# definido por 4 valores que representan las coordenadas: izquierda,
# arriba, derecha y abajo
img = img.crop((x1,y1,x2,y2))
# Le damos el nuevo tamanno a la imagen con el algoritmo de mejor calidad(ANTI-ALIAS)
img.thumbnail(box, Image.ANTIALIAS)
return img
def removeFiles(directory):
"""
Funcion para borrar las imagenes luego de ser procesadas
"""
for f in os.listdir(directory):
path = os.path.abspath(f)
if re.match("*.jpg", path):
try:
print "Erasing %s ..." % (path)
os.remove(path)
except os.error:
pass
def case_partition(img):
"""
#desc: Esta funcion es la que realmente guarda la imagen en la
particion 0
#param: imagen a guardar
#output_dir: Directorio a guardar las imagenes
"""
nombre_imagen = img
nombre_import = os.path.splitext(nombre_imagen)
temp = nombre_import[0]
nombre_real = temp.split('_')
if nombre_real[4] == 0:
ouput_file = nombre_real[0] + nombre_real[1] + ".jpg"
output_dir = out_dir + "/%d/%d/%d/" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file)
else:
print "Esta imagen sera comprimida"
img = resize(img, 200, 200, 200) ## FIXME Definir el tamano de la imagen
# Salvamos la imagen hacia un objeto de tipo file
# con la calidad en 75% en JPEG y el nombre definido por los especialistas
# Este nombre no esta definido......
# FIXME
output_file = nombre_real[0] + nombre_path[1] + "_.jpg"
output_dir = out_dir + "/%d/%d" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(out)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
if __name__ == "__main__":
find = "find %s -name *.jpg > /opt/scripts/images.txt" % entry_dir
args = shlex.split(find)
p = subprocess.Popen(args)
f = open('/opt/scripts/images.txt', "r")
images = []
for line in f:
images.append(line)
f.close()
for i in images:
img = Image.open(filename) # Here is the error when I try to open a file
case_partition(img) # with the format '/opt/buzon/15_498_3_00000000_00000000_1.jpg\n'
# and the \n character is which I want to replace with nothing
removeFiles(entry_dir) #
#
Regards
Assuming s is the string with the carriage return, you may use s.strip("\n") to remove carriage returns at the corners of the string. No need for regular expressions there.
I guess the relevant code lines are these:
for line in f:
images.append(line)
to remove the \n, you can simply call strip() on the string:
for line in f:
images.append(line.strip())
there are many ways to do that without using regexp
simpliest and correct one is use images.append(line.rstrip("\n")), also you can use images.append(line[:-1])
Also you can use glob() module instead call 'find' command through shell. It will return result as python list without having to use the files. ex: images=glob.glob("*.jpg"). http://docs.python.org/library/glob.html?highlight=glob

Categories