Newest questions tagged python - Stack Overflow

most recent 30 from

I have an infinite while loop but i don't see why


Regina Briseño

I'm trying to learn how to code really simple neural networks from scratch. However I can't seen to get the training right. Whenever I run my while loop it gets stuck in an infinite loop. Here is my code:

#inputs and targets

w1 = np.random.random_sample(size = 3)

#activation function
def purelin(z):
    return z

def red(i,w1):
    for inp in i:
    n=sum(n) #sumar inputs*weights (caso sin bias)
    return a

#forward propagation
def forw(inputs):
    for i in inputs:
    return outputs

def error(targets, outputs):
    zip_object = zip(targets, outputs)
    for i, j in zip_object:
    return e 

def back(e):
    zip_object2 = zip(w1, e)
    for i, j in zip_object2:
    return w1_

while itera<1000:

I know I still have a lot of work to do but I want to solve this problem so I can tune my code and get results. Thank you!!

How to display the correct amount of images after each collision?



I am trying to display the right amount of balloons (the images) each time a collision is detected. Note the collision works perfectly fine, but I am having trouble figuring out how to display the correct amount of balloons.

The collision is between 7 balloons and a gun. When the balloon is hit by the gun one less balloon is showed up. What should happen is when one of the 7 balloons is hit on the first background, one balloon should disappear, and a new background should show up with the same 7 balloons. Then, on the new background, if a balloon is being hit, the balloon should disappear and go back to the first background. Then on the first background again, should appear 6 balloons this time and when a balloon is hit, one should disappear and then the new background shows up also with 6 balloons. This should go on until all of the balloons are gone.

So the number of balloons should be like 7,7 6,6 5,5 4,4 3,3 2,2 1,1; where the first number in each pair is the first background and the second is the new background.

Here is my code:

import pygame as pg
import random as r
import sys


bg = pg.image.load('bg.jpg')# Background Image #
bg = pg.transform.scale(bg, (688,387))
new_bg = pg.image.load('new_bg.jpg')
new_bg = pg.transform.scale(new_bg, (688,387))

radius = 30
diameter = 2 * radius
num_balloons = 7

bullets_colors_ls = []
iterator = -1

def create_balloons():
    global balloon_list
    global colors

    for i in range(num_balloons):
        while True:
            candidate = r.randint(0, 500)
            if all(abs(candidate-x) >= diameter for x in balloon_list):

def draw_balloons(y):
    for i in range(num_balloons):
        screen.blit(colors[i], (balloon_list[i] , y-50))

def check_collisions(x, y):
    global hit_var
    global hit
    global score
    global scoretext
    global bg_bool
    for i in range(num_balloons):
        gun_rect = gun.get_rect(topleft = (x,y))
        gun_mask = pg.mask.from_surface(gun)

        balloon_rect = colors[i].get_rect(topleft = (balloon_list[i], y-100))
        balloon_mask = pg.mask.from_surface(colors[i])

        offset = (balloon_rect.x - gun_rect.x), (balloon_rect.y - gun_rect.y)
        if gun_mask.overlap(balloon_mask, offset):
            bg_bool = True
            hit_var = i
            print(f'hit balloon: {i}')




# Vars #
x = 0
y = 250
velocity = 5
score = 0

bg_bool = False

clock = pg.time.Clock()

screen = pg.display.set_mode((688 ,387)) # Size of the screen #
caption = pg.display.set_caption("Remember") # Title of the window #

balloon_list = []
b1 = pg.image.load('balloons/1.png').convert_alpha()
b1 = pg.transform.scale(b1, (63,131))
b2 = pg.image.load('balloons/2.png').convert_alpha()
b2 = pg.transform.scale(b2, (63,131))
b3 = pg.image.load('balloons/3.png').convert_alpha()
b3 = pg.transform.scale(b3, (63,131))
b4 = pg.image.load('balloons/4.png').convert_alpha()
b4 = pg.transform.scale(b4, (63,131))
b5 = pg.image.load('balloons/5.png').convert_alpha()
b5 = pg.transform.scale(b5, (63,131))
b6 = pg.image.load('balloons/6.png').convert_alpha()
b6 = pg.transform.scale( b6, (63,131))
b7 = pg.image.load('balloons/7.png').convert_alpha()
b7 = pg.transform.scale(b7, (63,131))
colors = [b1, b2, b3, b4, b5, b6, b7]

gun = pg.image.load('game-gun.png').convert_alpha()
gun = pg.transform.scale(gun, (150,150))


pg.display.flip() # Updating #

running = True # Game loop bool #

while running: # Game loop #
    #Background switching code#
    if bg_bool == False:
        screen.blit(bg, (0, 0))
    elif bg_bool == True:
        screen.blit(new_bg, (0,0))

    for event in pg.event.get():
        if event.type == pg.QUIT:
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False
            if event.key == pg.K_SPACE: 
                check_collisions(x, y)

    keys = pg.key.get_pressed()
    x += keys[pg.K_RIGHT] - keys[pg.K_LEFT] * velocity
    x -= keys[pg.K_LEFT] - keys[pg.K_RIGHT] * velocity

    screen.blit(gun, (x, y))

You can download all of the images here: Download images on REPL

How can I properly show the right amount of balloons each time the background is switched?

Appreciate any help, Thank you

Python Issue while loogin in to ajax website with a checkbox of terms and conditions


faiza rashid

I am getting this issue while loggin in to a ajax website, the issue is while loggin in it requires username, password and checkbox i agree with terms and conditions. I have tried loggin in with ony username and password but it returns an error that you must agree with terms and conditions Can any one help me with this?

from bs4 import BeautifulSoup as bs
import requests
import csv
import urllib.request

URL = ''
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.3'
s = requests.session()

csrf_token = s.get(LOGIN_ROUTE).cookies['__RequestVerificationToken']
print("\ncsrf_token " +csrf_token)

login_payload = {
        'Login.UserName': 'username',
        'Login.Password': 'password', 
        '__RequestVerificationToken': csrf_token

login_req =, headers=HEADERS, data=login_payload)

if login_req.status_code==200:
  print(str(login_req.status_code) + " login successful\n") #if successful, 200 will be returned
  print(str(login_req.status_code) + " login unsuccessful")

cookies = login_req.cookies
soup = bs(login_req.text, 'html.parser')
print("Parse text begins here")

the returned page is :

<form action="/Login/Login" class="form-signin loginForm" data-ajax="true" data-ajax-begin="AjaxBegin()" data-ajax-complete="AjaxComplete()" data-ajax-method="POST" data-ajax-success="Login(data)" id="mainLoginForm" method="post" role="form"><input name="__RequestVerificationToken" type="hidden" value="h3aO76bDCl0QOh7HOjH8XWKcyBPfbTR3E6KkF6jf3hL7gJPUbaLlP60gqrVYAxV6wHagvTQK_Azd1GWp50f08s59rnD87TIn2-zX55atrvY1"/> <div class="col-sm-12 center_align_tablet">
<input autofocus="" class="form-control" data-val="true" data-val-required="The Username field is required." id="username" name="Login.UserName" placeholder="User Name" required="" style="" type="text" value=""/>
<span class="field-validation-valid" data-valmsg-for="Login.UserName" data-valmsg-replace="true" style="color:red"></span>
<input class="form-control" data-val="true" data-val-required="The Password field is required." id="loginPass" name="Login.Password" placeholder="Password" required="" style="margin-top:10px;" type="password"/>
<span class="field-validation-valid" data-valmsg-for="Login.Password" data-valmsg-replace="true" style="color:red"></span>
<span id="LoginErrorMessage"></span>
<p style="font-size:12px; margin-top:10px;">
<div class="checkbox">
<input class="agreeBox" type="checkbox" value=""/>I Agree with the <a class="hyperlink" data-target="#terms_conditions_modal" data-toggle="modal" href="" id="termsPopUp">Terms and Conditions</a> of Acceptable Use
<div class="red" style="color:red;display:none">
                                                                Please Agree With Terms &amp; Conditions
<button class="btn btn-success btn-block login_btn_tablet" type="submit">Sign in</button>
</form> </div>

Run elasticsearch queries in python based on yaml or config file values



I have yaml file ( I can change it to config, xml or whatever works the best), e.g.

    value: "1"
    run: "/files/"
    value: "fatal"
    run: "/files/"

Every time I run query on elasticsearch and if is matched: error_sys = "1", /files/ script should be executed. This applies to second term also, if log_detail = "fatal", then /files/ script should be executed etc. The idea is to set in this yaml file match and action, so I don't need to write 150 queries.

This is what dict looks like:

import yaml
with open('myfile.yaml') as stream:
  config = yaml.safe_load(stream)

{'error_sys': {'value': '1', 'run': '/files/'}, 'log_detail': {'value': 'fatal', 'run': '/files/'}}

I need to put this somehow in Elasticsearch queries:

match_1 = {"query": {"bool": {"filter": {"term": {"error_sys": "1"}}}},"size": 100}
match_2 = {"query": {"bool": {"filter": {"term": {"log_detail": "fatal"}}}},"size": 100}

Something like:

match_all = {"query": {"bool": {"filter": {"term": {"[i[0:] for i in config]": "[VALUE_ELEMENT"}}}},"size": 100}
   # make a search() request to get all docs in the index
    resp =
           index = "logs",
           body = match_all

and finaly to run os.system("sh /files/")

How To Separate Index from userInput and add(+) them as INT in While Loop?



somebody says me to solve this.

condition is:

input any number from user (it can be 4 digit or five or whatever) e.g. '1234' it will be in string what i have to do just separate those number and do addition of those indexes as int

-------------------i have done this----------------------------------------------

usrInput = input("Type a number you want to some: ")

len = len(usrInput)

n = 0

i = 1

while i<=len:
    index = int(usrInput[n]) #1

now if i print(index) it will separate those numbers in separted index

now how can i do addition of them in this while loop i need help!!!!!!!!!

enter image description here