Posts

Showing posts with the label python

Why does my pong game freeze after the ball hits the bottom and it doesn't display the “Game Over” screen?

Why does my pong game freeze after the ball hits the bottom and it doesn't display the “Game Over” screen? I am a high school student and also a python enthusiast. I am trying to make a pong game in python and most of it worked but I am trying to make the program wait 3 seconds before the ball starts moving and when the ball hits the bottom the program just freezes and it doesn't display the "Game Over" screen. Would anyone be able to help me with this? Here is the code I am working on. from tkinter import * import random import time class Ball: def __init__(self, canvas, color, size, paddle): self.canvas = canvas self.paddle = paddle self.id = canvas.create_oval(15, 15, size, size, fill=color) self.canvas.move(self.id, 245, 100) self.xspeed = random.randrange(-3,3) self.yspeed = -1 self.hit_bottom = False self.score = 0 def draw(self): self.canvas.move(self.id, self.xspeed,...

Structuring main method

Structuring main method I have a python script that will do 3 things, check to see if a file exists in a directory, copy specific files from one directory to another, and execute another python script. Right now if I run the script it runs through all 3 functions, regardless of if the file exists in the test directory. What I want it to do is check to see if the file exists. If it does, copy it, and once it's copied execute the other script. I am having trouble figuring out a simple way to link them all together. Here is my script. import os import os.path from os import path import shutil def check_file(): file_exists = False for deploy_file in os.listdir("C:test1test.txt"): if deploy_file.startswith("test"): file_exists = True else: exit(1) print file_exists def copy_file(): src = "C:test1" dst = "C:test2" files = [i for i in os.listdir(src) if i.startswith("test") an...

Pandas Convert float column containing nan values to int for merge operation

Pandas Convert float column containing nan values to int for merge operation Attempt #1 s["order_id"].apply(lambda x: int(x) if pd.notnull(x) else np.nan) Attempt #2 def to_int(x): if(pd.notnull(x)): return int(x) Attempt #3 s["order_id"] = s.loc[pd.notnull(s["order_id"]),"order_id].astype(int) All of these return a series where the values are still formatted as floats. I'm wondering if I could use the update function or take advantage of reindexing. Leveraging Indexing solution attempt: null = np.nan data = {"time":{"0":1528971021539,"1":1529289904697,"2":1529572773525,"3":1529892602301,"4":1530082881098,"5":1530069453264,"6":1528985491630,"7":1529236762719,"8":1529475504491,"9":1529814085541,"10":1529906568681,"11":1530160346468,"12":1529833559160,"13":1530051985183,"14":153024...

How to check version of python modules?

How to check version of python modules? I just installed the python modules: construct and statlib with setuptools like this: construct statlib setuptools # Install setuptools to be able to download the following sudo apt-get install python-setuptools # Install statlib for lightweight statistical tools sudo easy_install statlib # Install construct for packing/unpacking binary data sudo easy_install construct I want to be able to (programmatically) check their versions. Is there an equivalent to python --version I can run from the command line? python --version My python version is 2.7.3 . 2.7.3 possible duplicate of Checking python module version at runtime – Ciro Santilli 新疆改造中心 六四事件 法轮功 Apr 6 '14 at 15:09 Also: stackoverflow.com/questions/3524168/… – user2314737 Dec ...

Combinations without duplicates of all elements in Python

Combinations without duplicates of all elements in Python To clarify the picture, if i have a string: 'pac' I would want to get the list of every permutation of it, in this example: ['p', 'a', 'c', 'pa', 'pc', 'pac'] Just like i would type any of it in some search engine like the one on Ebay and it would pop up "pac" as a suggestion. Code bellow is what i achieved thus far, but it's obviously not working as it should. 'Names' is just a list with multiple names, for instance: ['pac', 'greg', 'witch'] letters = {} for name in names: temp = letter = temp2 = for let in name: let = let.lower() temp.append(let) letter.append(let) for i in range(0, len(name)): for j in range(1, len(name) - i): print(i, j, end=' ') to_add = letter[i] + temp[j] ...

Python/Django: Populating Model Form Fields with values from Imported JSON file

Python/Django: Populating Model Form Fields with values from Imported JSON file I have a model form that saves all form field inputs to the backend database as one entry. I also have a JSON file that contains multiple JSON objects whose fields corresponds to the model form field. This JSON file is being uploaded via FileField in the model. Ultimately, I want to be able to upload a JSON file with the multiple JSON objects into my model form and populate the fields with the corresponding values from the uploaded JSON file. Each JSON object will be a single entry to my database and they can have null values for at least one field. Ideally, I would like to be able to choose which JSON object (from the uploaded JSON file) gets loaded to my model form fields to eventually be saved in my database. How would I go about implementing this? docs.python.org/3/tutorial/… – Ignacio Vazquez-Abrams Jun 29 at 23:50 ...

Django2.0; still cannot get how redirect works

Django2.0; still cannot get how redirect works I'm new to Django and I still don't get how redirect works. For now, I use this way to redirect. return HttpResponseRedirect(reverse_lazy('main:index')) and this way works. And now I'm creating another page, and what I want to do is to redirect to the same page after I submit the form data. view.py is like this def add_comment(request, pk): entry = Entry.objects.get(id=pk) if request.method != 'POST': form = CommentForm() else: form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.save() return redirect('add_comment', pk=entry.id) return render(request, 'main/add_comment.html', {'form': form, 'entry': entry, 'comments': comments}) urls.py is like this path('add_comment/<int:pk>', views.add_com...

Fit data within two function bounds

Fit data within two function bounds I have a set of data which, according to a theory, is bounded within two bounds. The upper bound is : f(x)=1/x (x<0.5) The lower bound is : f(x)=1+1/(2x)(x<0.5) The data I got is close to one of these two bounds. I’m trying to find a function to describe these data. But if I use normal fitting method, the fitted curve can be outside of these two bounds. How can I force my fitted curve between these two bounds by using scipy.curve_fit? I'm trying to use Pade approximant to do the fitting, the code I'm using is following: def pfuncp_3_1(x, a0, a1, a2, a3, b1): p1 = ((a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1)-1-1/(2*x)<0)*2.0 p2 = ((a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1)-1/x>0)*2.0 return (a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1) + p1 + p2 def ffuncp_3_1(x, a0, a1, a2, a3, b1): return (a0+a1*x+a2*x**2+a3*x**3)*(1+b1*x)**(-1) def data_fitter(pfunc, ffunc, fit_x, fit_y, new_x): popt, pcov = opt.curve_fit(pfunc, fit_x,...

It takes so much time to define an Adam optimizer in TensorFlow

It takes so much time to define an Adam optimizer in TensorFlow I use Adam optimizer to train a network, but I don't know why it takes so much time to just define the trainer. In TensorFlow, what does Adam optimizer do when we define it? Here is how I define the trainer. mse_loss = tf.reduce_sum(tf.squared_difference(generated_images, FD_placeholder)) / (batch_size * width * height) print(gen_variables) print(mse_loss) g_trainer = tf.train.AdamOptimizer(learning_rate=lr) print("aaaaa") g_trainer = g_trainer.minimize(mse_loss, var_list=gen_variables) print("aaaaa") lr is a placeholder for learning rate, it has type tf.float32, and shape=[ ]. generated_images and FD_placeholder have a shape (batch_size,64,64,1). I use batch_size = 2. width and height are equal to 64 gen_variables has shape (91,1,1) and dtype=tf.float32. Here is the output for these few lines of code. [<tf.Variable 'generator_model/g_w1:0' shape=(91, 1, 1) dtype=float32_ref>] Tensor(...

BS4/Python3 can't open other href while scrapping on google

BS4/Python3 can't open other href while scrapping on google My job is with a startup and they're calling some businesses but they're buying the contacts. So I had the idea to scrape them from Google, like some hotels, etc... I can already get the link that opens the Googlemaps with lots of companies but can't take the information inside this link because the program crashes. import json from bs4 import BeautifulSoup as bs from collections import namedtuple from pprint import pprint from requests import get import requests def remove_escape(s): return ' '.join(s.split()) def get_jobs(url): vagas = get(url, headers=headers) vagas_page = bs(vagas.text, 'html.parser') boxes = vagas_page.find_all('div', {'class': 'idQ6DBVUh1_8- ptqfrjbX76M'}) for box in boxes: titulo = box.find('span', {'class': 'ellip'}).text ...

How to assign a unique ID to detect repeated rows in a pandas dataframe?

How to assign a unique ID to detect repeated rows in a pandas dataframe? I am working with a large pandas dataframe, with several columns pretty much like this: A B C D John Tom 0 1 Homer Bart 2 3 Tom Maggie 1 4 Lisa John 5 0 Homer Bart 2 3 Lisa John 5 0 Homer Bart 2 3 Homer Bart 2 3 Tom Maggie 1 4 How can I assign an unique id to each repeated row? For example: A B C D new_id John Tom 0 1.2 1 Homer Bart 2 3.0 2 Tom Maggie 1 4.2 3 Lisa John 5 0 4 Homer Bart 2 3 5 Lisa John 5 0 4 Homer Bart 2 3.0 2 Homer Bart 2 3.0 2 Tom Maggie 1 4.1 6 I know that I can use duplicate to detect the duplicated rows, however I can not visualize were are reapeting those rows. I tried to: duplicate df.assign(id=(df.columns).astype('category').c...

Python : Taberror

Python : Taberror I have one Estonian script, but It gives me error: Sorry: TabError: inconsistent use of tabs and spaces in indentation (function sheet1.py, line 8) [Finished in 0.2s with exit code 1] and code is: import sys import datetime end = False while end == False: def contin01(): print("Kas soovid jätkata?") exit = input("Vali [1] - JAH // Vali [2] - EI: ") if exit[0] == "1": print("********* Beginning of Line ********* ") elif exit[0] == "2": sys.exit() def sina(): nimi = input("Kirjuta enda nimi: ") def guest_name(): Guest_Name = input("Sisesta kliendi nimi: ") def guest_arrival(): Arrival = input("Sisesta kliendi saabumiskuupäev: ") def guest_dep(): Departure = input("Sisesta kliendi lahkumiskuupäev: ") def room(): Room_number = input("Sisesta kliendi toa number ") def special(): req = input("Kirjuta kliendi eri...

Python not reading from file

Python not reading from file I am trying to loop over the lines of a text file which is verifiably non-empty and I am running into problems with my script. In my attempt to debug what I wrote, I figured I would make sure my script is properly reading from the file, so I am currently trying to print every line in it. At first I tried using the usual way of doing this in Python i.e.: with open('file.txt') as fo: for line in fo: print line but my script is not printing anything. I then tried storing all of the lines in a list like so: with open('file.txt') as fo: flines = fo.readlines() print flines and yet my program still outputs an empty list (i.e. ). I have also tried making sure that my file pointer is pointing to the beginning of the file using fo.seek(0) before attempting to read from it, yet that also does not work. fo.seek(0) I have spent some time reading solutions to similar questions posted on here, but so far nothing I have tried has worked....