Locateonscreen True then do ..... or with pixelmatch? - pyautogui

I have a def that looks for a pixel match color if this is true it looks for an image
can i replace this with locateonscreen? becorse the image position change over time
this is my def and it works but i want to use locateonscreen instead of match color for the yellowbell i changed this to the code below can this work?
i = 0
#while pyautogui.pixelMatchesColor(YellowBellX , YellowBellY , (YellowR,YellowG,YellowB), tolerance = 20) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
while pyautogui.locateOnScreen("YellowBell.png",region=(19,116,900,60), confidence=0.8) == True and pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (NoOrdersAviableBannerR ,NoOrdersAviableBannerG ,NoOrdersAviableBannerB ), tolerance = 20) == False:
if pyautogui.pixelMatchesColor(firstTaskX , firstTaskY , (blueR,blueG,blueB), tolerance = 20) == True:
break

Related

ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 256])

import time
model_path = "/content/drive/My Drive/Generating-Webpages-from-Screenshots-master/models/"
batch_count = len(dataloader)
start = time.time()
for epoch in range(epochs):
#s = 0
for i , (images , captions , lengths) in enumerate(dataloader):
images = Variable(images.cuda())
captions = Variable(captions.cuda())
#lenghts is a list of caption length in descending order
#The collate_fn function does padding to the captions that are short in length
#so we need to pad our targets too so as to compute the loss
targets = nn.utils.rnn.pack_padded_sequence(input = captions, lengths = lengths, batch_first = True)[0]
#Clearing out buffers
E.zero_grad()
D.zero_grad()
features = E(images)
output = D(features , captions , lengths)
loss = criterion(output , targets)
loss.backward()
optimizer.step()
#s = s + 1
if epoch % log_step == 0 and i == 0:
print("Epoch : {} || Loss : {} || Perplexity : {}".format(epoch , loss.item()
, np.exp(loss.item())))
#Uncomment this to use checkpointing
#if (epoch + 1) % save_after_epochs == 0 and i == 0:
#print("Saving Models")
#torch.save(E.state_dict , os.path.join(model_path , 'encoder-{}'.format(epoch + 1)))
#torch.save(D.state_dict , os.path.join(model_path , 'decoder-{}'.format(epoch + 1)))
print("Done Training!")
print("Time : {}".format(time.time() - start))
I can't say for sure what is going on, because I don't know the definition of D, but if it is a neural network that uses batch normalization, the likely problem is that you need to use a batch size larger than 1.

How to print the results of an input variable inside a function

here is my code, the input variable is map1 where the user is promoted to enter a filepath, I want to print('map saved to', map1) after the user inputs the location, but I am getting the error NameError: name 'map1' is not defined. The variable is defined and is assigned a value when the user puts an input. Why won't it print?
def question2(two):
map1 = input('where do you want to save the map? please enter filepath with image type e.g C:/map.jpg: ')
fig, ax = plt.subplots(figsize = (15,12))
filtered_buildings.plot(ax = ax, color = 'red', edgecolor = 'black',)
Highway.plot(ax = ax, color = 'black')
Tunnel.plot(ax = ax, color = 'green', alpha = 0.5, edgecolor = 'black',)
Tunnel_buffer.plot(ax = ax, facecolor='none', edgecolor = 'black',)
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
plt.title('Filtered Buildings')
plt.savefig(fname=map1, dpi=300)
if __name__ == '__main__':
do_again = 'start_string'
while not do_again in ['yes', 'y', 'Yes', 'No', 'n', 'no']:
do_again = input("Would you like to save the final map? (y/n)? ").lower()
if do_again == 'yes' or do_again == 'y' or do_again == 'Yes':
print('Saving Map...')
print('map saved to', map1)
question2()
The print statements
print('Saving Map...')
print('map saved to', map1)
Should be directly after the plt.savefig(fname=map1, dpi=300) and before if __name__ == '__main__':
Correct code is:
def question2():
map1 = input('where do you want to save the map? please enter filepath with image type e.g C:/map.jpg: ')
fig, ax = plt.subplots(figsize = (15,12))
filtered_buildings.plot(ax = ax, color = 'red', edgecolor = 'black',)
Highway.plot(ax = ax, color = 'black')
Tunnel.plot(ax = ax, color = 'green', alpha = 0.5, edgecolor = 'black',)
Tunnel_buffer.plot(ax = ax, facecolor='none', edgecolor = 'black',)
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
plt.title('Filtered Buildings')
plt.savefig(fname=map1, dpi=300)
print('Saving Map...')
print('map saved to', map1)
if __name__ == '__main__':
do_again = 'start_string'
while not do_again in ['yes', 'y', 'Yes', 'No', 'n', 'no']:
do_again = input("Would you like to save the final map? (y/n)? ").lower()
if do_again == 'yes' or do_again == 'y' or do_again == 'Yes':
question2()

Shifting tensor over dimension

Lets say I have a tensor of A of shape [batch_size X length X 1024]
I want to do the following :
for the i element in the batch i want to shift the (embedding 1024) of all 'length' elements embedding by their position .
for example the vector A[0 , 0 , : ] should stay the same, and A[0 , 1 , :] should be shifted (or rolled) by 1 , and A[0 , 15 , :] should be shifted by 15.
this is for all the elements in the batch.
so far i did it with for loops, but its not efficient
below is my code with for loops :
x = # [batchsize , length , 1024]
new_embedding = []
llist = []
batch_size = x.shape[0]
seq_len = x.shape[1]
for sample in range(batch_size):
for token in range(seq_len):
orig = x[sample , token , : ]
new_embedding.append(torch.roll(orig , token , 0))
llist.append(torch.stack(new_embedding , 0))
new_embedding = []
x = torch.stack(llist , 0)

Using Pynput listener to pause and continue a script

So I've got this:
from pynput.keyboard import Key, Controller, Listener
keyboard = Controller()
import random
import time
def mainfunction():
key1 = input("type first key to be repeated: ")
key2 = input("second.. : ")
key3 = input("last .. : ")
x = 0
while x < 10000:
keyboard.press(key1)
keyboard.release(key1)
time.sleep((random.randint(1, 8))/10)
keyboard.press(key2)
keyboard.release(key2)
time.sleep((random.randint(1, 8))/10)
keyboard.press(key3)
keyboard.release(key3)
time.sleep((random.randint(1, 8))/10)
x = x + 1
mainfunction()
and I want it to pause and continue on the double press of some arbitrary letter but have no clue how to go about it using pynput.listener.
from pynput.keyboard import Key, Controller, Listener
keyboard = Controller()
from threading import Thread
import random
import time
def listen(key):
global keyletter
global key4
keydata = str(key)
try:
if keydata.replace("'", "") == str(key4):
keyletter = keydata.replace("'", "")
except:
#at Programstart key4 is not defined jet and would lead to an Error
pass
def mainThread():
global keyletter
global key4
key1 = input("type first key to be repeated: ")
key2 = input("second.. : ")
key3 = input("last.. : ")
key4 = input("interrupt.. ")
bool_interrupt = False
x = 0
while x < 10000:
if keyletter == str(key4):
if bool_interrupt == False:
bool_interrupt = True
time.sleep(0.5)
keyletter = ""
else:
bool_interrupt = False
time.sleep(0.5)
keyletter = ""
if bool_interrupt == False:
keyboard.press(key1)
keyboard.release(key1)
time.sleep((random.randint(1, 8))/10)
keyboard.press(key2)
keyboard.release(key2)
time.sleep((random.randint(1, 8))/10)
keyboard.press(key3)
keyboard.release(key3)
time.sleep((random.randint(1, 8))/10)
x = x + 1
def listenerThread():
global keyletter
keyletter = ""
with Listener(on_press=listen) as l:
l.join()
myThread1 = Thread(target=mainThread)
myThread2 = Thread(target=listenerThread)
myThread1.start()
myThread2.start()
This might be overcomplicated, but it works.
i use a second Thread, since the Listener stops the Code until Input.
This way, the mainThread loops, while the listenerThread waits for an Input.

PyGame surface locked during blit [duplicate]

I am trying to draw text to a screen in a space above a bunch of rects that are all in the 2d array square. When i try and draw text to the screen it says that "Surfaces must not be locked during blit."
I have tried unlocking, it makes no difference.
import sys, time, random, pygame
from pygame import *
from time import time,sleep
pygame.init()
global isDragging, inDrag, rightDrag, lastDrag, inDragRight, mouseX,mouseY, borderHeight
isDragging = False
isAuto = False
inDrag= False
inDragRight = False
isFilling = False
done = False
lastDrag = None
rightDrag = None
tickTime = 300
font = pygame.font.SysFont(None, 12,False,False)
dragDelay = 2
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
PINK = ( 255, 150, 200)
BLUE = ( 0, 0, 255)
RED = GREEN
width, height, margin = 100, 100, 1
noWidth, noHeight = 6,6
speed = [2, 2]
borderHeight = 50
size = (width*noWidth,height*noHeight + borderHeight)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PieStone")
clock = pygame.time.Clock()
pixArray = pygame.PixelArray(screen)
font = pygame.font.SysFont("monospace", 15)
word = font.render("test", 1, (0, 0, 0))
class Null:
pass
square = [[Null() for i in range(noHeight)]for i in range(noWidth)]
for d1 in range(noWidth):
for d2 in range(noHeight):
square[d1][d2].man = False
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK
square[d1][d2].margin = 1
a = 1
i = 1
def text(word,size,pos1,pos2,pos3):
word = font.render(str(word),size,(pos1,pos2,pos3))
return word
def colide(obj,mouseX,mouseY):
if obj.collidepoint(mouseX,mouseY) == 1:
return True
else:
return False
def click(mouseX,mouseY):
#rint("left")
global inDrag,lastDrag
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("square",d1,d2,"has been clicked")
try:
if square[d1][d2] != lastDrag:
inDrag = True
lastDrag = square[d1][d2]
else:
inDrag = False
except UnboundLocalError:
print("error")
lastDrag = square[d1][d2]
#print(inDrag)
if square[d1][d2].margin == 0 and inDrag:
square[d1][d2].margin = 1
square[d1][d2].visits = square[d1][d2].visits + 1
elif square[d1][d2].margin == 1 and inDrag:
square[d1][d2].margin = 0
square[d1][d2].visits = square[d1][d2].visits + 1
break
'''if square[d1][d2].visits >= 5 and square[d1][d2].colour == BLACK:
square[d1][d2].visits = 0
square[d1][d2].colour = RED
elif square[d1][d2].visits >= 5 and square[d1][d2].colour == RED:
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK'''
def rightClick(mouseX,mouseY):
#print("right")
global inDragRight, lastRight
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("colide")
try:
if square[d1][d2] != lastRight:
inDragRight = True
lastRight = square[d1][d2]
else:
inDragRight = False
except:
print("error")
lastRight = square[d1][d2]
#print(inDragRight)
if square[d1][d2].colour == RED and inDragRight:
square[d1][d2].colour = BLACK
#print("black")
elif square[d1][d2].colour == BLACK and inDragRight:
square[d1][d2].colour = RED
#print("red")
break
while not done:
screen.blit(word, (0, 0))
(mouseX,mouseY) = pygame.mouse.get_pos()
#print(str(mouseX)+",",mouseY)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
#print(mouseX,mouseY)
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
elif pygame.mouse.get_pressed()[1] == 1:
isAuto = True
#print(pygame.mouse.get_pressed())
elif event.type == pygame.MOUSEBUTTONUP:
#print("up")
isDragging = False
isFilling = False
lastDrag = None
lastRight = False
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
if isAuto:
rnd1 = random.randint(0,1)
if rnd1 == 1:
isDragging = True
isFilling = False
else:
isDragging = False
isFilling = True
(mouseX,mouseY) = (random.randint(0,width*noWidth),random.randint(0,height*noHeight)+borderHeight)
#print(mouseX,mouseY)
if isDragging:
click(mouseX,mouseY)
if isFilling:
rightClick(mouseX,mouseY)
screen.fill(WHITE)
# --- Game logic should go here
i = 0
for d1 in range(noWidth):
if noHeight % 2 == 0:
'''if i == 0:
i = 1
else:
i = 0'''
for d2 in range(noHeight):
#if i % a == 0:
try:
if i == 0:
pass
elif i == 1:
pass
except AttributeError:
print("AttributeError")
square[d1][d2].margin = random.randint(0,1)
#print(square[d1][d2].visits)
square[d1][d2].rect = pygame.draw.rect(screen, square[d1][d2].colour, [(d1*width), ((d2*height)+borderHeight),width,(height)],square[d1][d2].margin)
#print("d1*width:",d1*width,"d2*height:",d2*height,"d1*width+width:",d1*width+width,"d2*height+height:",d2*height+height)
pygame.display.flip()
clock.tick(tickTime)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
You're using a PixelArray:
pixArray = pygame.PixelArray(screen)
But using a PixelArray locks your Surface, as stated in the documentation:
During its lifetime, the PixelArray locks the surface, thus you explicitly have to delete it once its not used anymore and the surface should perform operations in the same scope.
Just remove the line, since you're not using it anyway.