How can I implement dynamic wait in it? - dynamic

class getPageObj:
#staticmethod
def getIDByLabel(driver, form_type, label_name):
#driver = webdriver.Chrome(executable_path="D:\\chromedriver.exe")
if label_name.find("[") == -1:
xpath_exp = "//label[text()='"+label_name+"'][1]"
else:
label_sub_str = label_name[:label_name.find("[")]
label_indx_str = label_name[label_name.find("["):label_name.find("]") + 1]
xpath_exp = "//label[text()='" + label_sub_str + "']"+label_indx_str
if len(driver.find_elements_by_xpath(xpath_exp)) > 0:
if form_type == "Form":
id=getPageObj()
attr_id = id.getAttrValueByXPath(driver, xpath_exp, "for")
return attr_id
else:
id=getPageObj()
attr_id = id.getAttrValueByXPath(driver, xpath_exp, "for")
return attr_id

Related

I'm making a code and my question is about the fsolve of scipy.optimize, I get to the value of the function, but it returns a false root

class ConstanteEquilibrio:
def __init__(self, lista_componentes, lista_coeficientes, T, P, mols_i):
self.lista_componentes = lista_componentes
self.lista_coeficientes = lista_coeficientes
self.T = T
self.P = P
self.mols_i = mols_i
return
def Calcula(self):
somatorio_G = 0.0
somatorio_H = 0.0
somatorio_A = 0.0
somatorio_B = 0.0
somatorio_C = 0.0
somatorio_D = 0.0
somatorio_E = 0.0
R = 8.314
Tref = 298.15
nomes = []
Tc_mix = []
Pc_mix = []
w_mix = []
dados_compostos = pd.read_excel("DadosCompostosPadrao.xlsx")
for i in range(0, len(self.lista_componentes)):
G_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'G0 (298)'].values[0]
H_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'H0 (298)'].values[0]
A_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'a'].values[0]
B_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'b'].values[0]
C_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'c'].values[0]
D_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'd'].values[0]
E_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'e'].values[0]
nome_i = dados_compostos.loc[dados_compostos['Composto'] == self.lista_componentes[i], 'Nome'].values[0]
nomes.append(nome_i)
dados_composto_i = ChemicalConstantsPackage.constants_from_IDs([nome_i])
Tc_mix.append(dados_composto_i.Tcs[0])
Pc_mix.append(dados_composto_i.Pcs[0])
w_mix.append(dados_composto_i.omegas[0])
somatorio_G = somatorio_G + self.lista_coeficientes[i] * G_i
somatorio_H = somatorio_H + self.lista_coeficientes[i] * H_i
somatorio_A = somatorio_A + self.lista_coeficientes[i] * A_i
somatorio_B = somatorio_B + self.lista_coeficientes[i] * B_i
somatorio_C = somatorio_C + self.lista_coeficientes[i] * C_i
somatorio_D = somatorio_D + self.lista_coeficientes[i] * D_i
somatorio_E = somatorio_E + self.lista_coeficientes[i] * E_i
K298 = np.exp(-somatorio_G*1000 / (R * Tref))
lnK_K298 = (-somatorio_H*1000/R + somatorio_A*Tref + somatorio_B*(Tref**2)/2 + somatorio_C*(Tref**3)/3 - somatorio_D/Tref + somatorio_E*(Tref**4)/4)*(1/self.T - 1/Tref) + somatorio_A*np.log(self.T/Tref) + somatorio_B*(self.T-Tref)/2 + somatorio_C*(self.T**2-Tref**2)/6 + somatorio_D*((1/self.T**2)-(1/Tref**2))/2 - somatorio_E*(self.T**3-Tref**3)/12
K_T = K298 * np.exp(lnK_K298)
def CalculaE(e):
y_componentes = []
FO = 0.0
n_total = sum(self.mols_i) + e * sum(self.lista_coeficientes)
for i in range(0, len(self.lista_componentes)):
y_i = (self.mols_i[i] + self.lista_coeficientes[i] * e)/n_total
y_componentes.append(y_i)
for j in range(0, len(self.lista_componentes)):
FO = FO + (self.P * y_componentes[j])**(self.lista_coeficientes[j])
#print(FO)
return FO - K_T
e_reacao = fsolve(CalculaE, 0.5)
e_reacao = e_reacao[0]
#print(e_reacao)
n_componentes = []
y_componentes = []
for j in range(0, len(self.lista_componentes)):
n_i = (self.mols_i[j] + self.lista_coeficientes[j] * e_reacao)
n_componentes.append(n_i)
n_total = sum(n_componentes)
for w in range(0, len(self.lista_componentes)):
y_i = n_componentes[w] / n_total
print(f'{self.lista_componentes[w]} : {y_i * 100:.3f} %')
return K298, K_T
However, when I print in e_reacao I arrive at the value of K_T, which is 14,128, (theoretically it reached the zero of the function) only for some reason when I replace the value in the final expression:
K_T = (e_reacao / (1 + e_reacao))**2 / ((1 - e_reacao)/(1 + e_reacao)) I don't get the value of 14.128 because the value of e_reaction of the last interaction is 0.8592 but it was supposed to be , approximately 0.9663. Does anyone have an idea what it could be? Something wrong I'm doing in the code. Thanks in advance.

Pi Pico Micropython Loop seems to get stuck

I am using a Pico as part of my dissertation along with an Arduino Due for a low cost fully autonomous UAV.
Anyway to the point, the code was working before I added the GPS part but now even if I take it out the ultrasonics won't work correctly. only shows the left sensor and doesn't continue on to the GPS.
I was also trying to use the multithreader with no joy :(
Any help or suggestions would be great.
Its a bit messy I know not quite got round to polishing it.
from machine import Pin
import utime, _thread, machine
import os
from rp2 import PIO, StateMachine, asm_pio
#print sys info
print(os.uname())
led_onboard = machine.Pin(25, machine.Pin.OUT)
led_onboard.value(0) # onboard LED OFF for 0.5 sec
utime.sleep(0.5)
led_onboard.value(1)
uart = machine.UART(0, baudrate=9600)
ser = machine.UART(1, baudrate=9600)
print(uart)
print(ser)
baton = _thread.allocate_lock()
rcvChar = b""
trigger = Pin(3, Pin.OUT) #left
echo = Pin(2, Pin.IN)
trigger2 = Pin(6, Pin.OUT) #right
echo2 = Pin(7, Pin.IN)
trigger4 = Pin(9, Pin.OUT) #backward
echo4 = Pin(8, Pin.IN)
def decode(coord):
#Converts DDDMM.MMMMM > DD deg MM.MMMMM min
x = coord.split(".")
head = x[0]
tail = x[1]
deg = head[0:-2]
min = head[-2:]
return deg + " deg " + min + "." + tail + " min"
def ultraleft():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
Ldistance = (timepassed * 0.0343) / 2
utime.sleep(0.1)
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
Ldistance2 = (timepassed * 0.0343) / 2
newLdist = (Ldistance + Ldistance2) / 2
if newLdist > 120:
newLdist = 120
elif newLdist <= 100:
print("Distance Left less than 100")
return True
print("The distance Left from object is ",newLdist,"cm")
def ultraright():
trigger2.low()
utime.sleep_us(2)
trigger2.high()
utime.sleep_us(5)
trigger2.low()
while echo2.value() == 0:
signaloff2 = utime.ticks_us()
while echo2.value() == 1:
signalon2 = utime.ticks_us()
timepassed2 = signalon2 - signaloff2
Rdistance = (timepassed2 * 0.0343) / 2
utime.sleep(0.1)
trigger2.low()
utime.sleep_us(2)
trigger2.high()
utime.sleep_us(5)
trigger2.low()
while echo2.value() == 0:
signaloff2 = utime.ticks_us()
while echo2.value() == 1:
signalon2 = utime.ticks_us()
timepassed2 = signalon2 - signaloff2
Rdistance2 = (timepassed2 * 0.0343) / 2
newRdist = (Rdistance + Rdistance2) / 2
if newRdist > 120:
newRdist = 120
elif newRdist <= 100:
print("Distance Right less than 100")
return True
print("The distance Right from object is ",newRdist,"cm")
def ultradwn():
trigger4.low()
utime.sleep_us(2)
trigger4.high()
utime.sleep_us(5)
trigger4.low()
while echo4.value() == 0:
signaloff4 = utime.ticks_us()
while echo4.value() == 1:
signalon4 = utime.ticks_us()
timepassed4 = signalon4 - signaloff4
Ddistance = (timepassed4 * 0.0343) / 2
utime.sleep(0.1)
trigger4.low()
utime.sleep_us(2)
trigger4.high()
utime.sleep_us(5)
trigger4.low()
while echo4.value() == 0:
signaloff4 = utime.ticks_us()
while echo4.value() == 1:
signalon4 = utime.ticks_us()
timepassed4 = signalon4 - signaloff4
Ddistance2 = (timepassed4 * 0.0343) / 2
newDdist = (Ddistance + Ddistance2) / 2
if newDdist > 120:
newDdist = 120
elif newDdist >20 :
print("Distance Down is greater than 20")
x = 1
#uart.write("D20")
#uart.write("\n")
#print("Sent TO Height")
return True
elif newDdist <12 :
print("Distance Down is less than 12")
x = 2
#uart.write("D12")
#uart.write("\n")
#print("Sent Landed")
return True
print("The distance Down from object is ",newDdist,"cm")
def gps():
while True:
#baton.acquire()
rcvChar = ser.readline()
gps_data =rcvChar.decode("ASCII")
data = gps_data
if (data[0:6] == "$GPRMC"):
sdata = data.split(",")
if (sdata[2] == 'V'):
print("no satellite data available")
print ("---Parsing GPRMC---")
time = sdata[1][0:2] + ":" + sdata[1][2:4] + ":" + sdata[1][4:6]
lat = decode(sdata[3]) #latitude
dirLat = sdata[4] #latitude direction N/S
lon = decode(sdata[5]) #longitute
dirLon = sdata[6] #longitude direction E/W
speed = sdata[7] #Speed in knots
trCourse = sdata[8] #True course
date = sdata[9][0:2] + "/" + sdata[9][2:4] + "/" + sdata[9][4:6]#date
print ("time : %s, latitude : %s(%s), longitude : %s(%s), speed : %s, True Course : %s, Date : %s" % (time,lat,dirLat,lon,dirLon,speed,trCourse,date))
#baton.acquire()
#_thread.start_new_thread(gps(), ())
while True:
x = 0
#baton.acquire()
ultraleft()
utime.sleep(0.1)
ultraright()
utime.sleep(0.1)
ultradwn()
utime.sleep(0.1)
if ultraleft():
uart.write("LO")
uart.write("\n")
print("Sent Left")
utime.sleep(1)
if ultraright():
uart.write("RO")
uart.write("\n")
print("Sent Right")
uart.sendbreak()
utime.sleep(1)
if ultradwn():
if x == 1:
uart.write("D20")
uart.write("\n")
print("Sent TO Height")
utime.sleep(1)
if x == 2:
uart.write("D12")
uart.write("\n")
print("Sent Landed")
utime.sleep(1)
utime.sleep(1)
gps()
#baton.release()

Why is setting the expiry time ineffective in Redis

Now i use redispipeline to set key to redis ,and set key timeout.After running codes and timeout,and the keys are still in redis?It seemed doesn't work.Is there sth wrong with my code.
X[1] is dict,such as dict["a"]=b dict["c"]=d
redis_pool = redis.ConnectionPool(host = redis_ip, port = redis_port, decode_responses = False)
redis_connection = redis.StrictRedis(connection_pool = redis_pool)
redis_pipeline = redis_connection.pipeline(transaction = False)
sync_count = 0
for x in iterator:
key = suffix + x[0]
#value = str(x['tagid'])+"\t"+x['tag_name']
value = x[1]
redis_pipeline.hmset(key, value)
redis_pipeline.expire(key,60)
sync_count += 1
if (sync_count % 100 == 0):
result = redis_pipeline.execute()
print (result)
time.sleep(0.001)
break
if sync_count == 10000:
break
redis_pipeline.execute()

My tensorflow code does not work good -bank analysis

I'm studding tensorflow and I wrote some code but it does not work good.
the data was downloaded from uci:http://archive.ics.uci.edu/ml/datasets/Bank+Marketing
I want to find the client who will subscribe a term deposit,but the result matched is 0.
I use 3 layers neural network and sigmod for output.
My code is like this,please help me.
hidden_layer1 = 200
hidden_layer2 = 200
x = tf.placeholder(tf.float32,[None,16])
y = tf.placeholder(tf.float32,[None,1])
Weights_L1 = tf.Variable(tf.random_normal([16,hidden_layer1]))
biases_L1 = tf.Variable(tf.random_normal([1,hidden_layer1]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1=tf.nn.relu(Wx_plus_b_L1)
Weights_L2 = tf.Variable( tf.random_normal([hidden_layer1,1]))
biases_L2 = tf.Variable( tf.random_normal([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
pred = tf.nn.sigmoid(Wx_plus_b_L2)
loss = tf.reduce_mean(tf.square(y-pred))
learning_rate=0.05
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
pred_correct = tf.equal(y,pred)
accuracy = tf.reduce_mean(tf.cast(pred_correct,tf.float32))
batch_num = 0
with tf.Session() as ss:
ss.run(tf.global_variables_initializer())
for step in range(500):
ss.run(train_step,feed_dict={x:bank_train_x,y:bank_train_y})
if step%100==0:
batch_num = batch_num +1
acc1 = ss.run(accuracy,feed_dict={x:bank_train_x,y:bank_train_y})
print("train acc"+ str(step) + ", " + str(acc1) +" , batch_num:" + str(batch_num))
#print(ss.run(learning_rate,feed_dict={global_:step}))
p = ss.run(pred,feed_dict={x:bank_train_x,y:bank_train_y})
acc2 = ss.run(accuracy,feed_dict={x:bank_test_x,y:bank_test_y})
print("test acc" + str(acc2))
def calc(pred,y):
l = y.shape[0]
a = 0
b=0
c=0
d=0
for i in range(l):
if (p[i] >0.5 and y[i] == 0):
a = a +1
elif (p[i] >0.5 and y[i] == 1):
b = b+1
elif (p[i] <0.5 and y[i] == 0):
c = c+1
elif (p[i] <0.5 and y[i] == 1):
d = d +1
print(a,b,c,d)
calc(p,bank_train_y)
#the result is 169 0 34959 4629

No module named 'Models', python 3.5.2

Got this Arkanoid clone code from internet however even after installing pygame binary still doesn' t want to work ("ImportError: No module named 'Models'"). I am using Spyder Python 3.5 and i cloned all repo from there https://github.com/Killavus/PyGame-Arkanoid
import pygame
import sys
import math
import random
from pygame.locals import *
import GameModule
from GameModule.Models import *
from GameModule.Constants import *
class Game:
def playSound( self, fileName ):
sound = pygame.mixer.Sound(fileName)
sound.play()
def __init__(self):
pygame.init()
pygame.mixer.init(11025)
self.actualState = states["START"]
self.display = pygame.display.set_mode( gfx["screen"] )
pygame.display.set_caption( "Arkanoid v" + version )
# 4 basic objects, which define the game
## Painter - drawing actual situation on screen
## Mapper - loading the map
## Status - holding stance of the game: points, lifes, actual powerups etc
## Objects - holding actual game's objects: balls, bricks, pad etc
self.objects = GameModule.Objects()
self.mapper = GameModule.Mapper( self.objects )
self.status = Status()
self.painter = GameModule.Painter( self.display, self.objects, self.status )
self.lastState = None
self.fps = pygame.time.Clock()
self.newLevel()
def loop(self):
self.fps.tick( gfx["framerate"] )
for event in pygame.event.get():
self.handleGlobalEvents( event )
self.handleEvents( event )
self.handleKeyboard()
self.updateState()
if self.actualState != states["GAMEOVER"]:
self.painter.draw()
else:
self.display.fill( (0,0,0) )
bigFont = pygame.font.SysFont( "sans-serif", 32 )
gameOver = bigFont.render( "GAME OVER!", True, (255,255,255) )
smallFont = pygame.font.SysFont( "sans-serif", 18 )
points = smallFont.render( "Punktow: " + str(self.status.points), True, (255,255,255) )
self.display.blit( gameOver, (gfx["screen"][0]/2 - gameOver.get_size()[0]/2, gfx["screen"][1]/2 - gameOver.get_size()[1]/2) )
self.display.blit( points, (gfx["screen"][0]/2 - points.get_size()[0]/2, gfx["screen"][1]/2 - gameOver.get_size()[1]/2 - 40) )
pygame.display.update()
def handleEvents( self, event ):
if self.actualState != states["PAUSE"]:
if event.type == KEYDOWN:
if event.key == K_p:
self.lastState = self.actualState
self.actualState = states["PAUSE"]
self.painter.paused = True
else:
if event.type == KEYDOWN:
if event.key == K_p:
self.actualState = self.lastState
self.painter.paused = False
if self.actualState == states["START"]:
if event.type == KEYDOWN:
if event.key == K_SPACE:
self.actualState = states["PROGRESS"]
(self.objects.balls())[0].speedChange( int( math.copysign( 5., float(self.objects.pad().lastMove) ) ), -5 )
def handleGlobalEvents( self, event ):
if event.type == QUIT:
sys.exit()
def handleKeyboard(self):
pressed = pygame.key.get_pressed()
if self.actualState == states["PROGRESS"] or self.actualState == states["START"]:
if pressed[K_LEFT]:
if self.objects.pad().move(-10) and self.actualState == states["START"]:
(self.objects.balls())[0].move(-10,0)
if pressed[K_RIGHT]:
if self.objects.pad().move(10) and self.actualState == states["START"]:
(self.objects.balls())[0].move(10,0)
def updateState(self):
if self.actualState == states["PAUSE"]:
return
if self.actualState == states["PROGRESS"]:
self.objects.updatePowerups()
for ball in self.objects.balls():
speed = ball.speed()
ball.move( speed[0], speed[1] )
if ball.collideWithWall():
pos = ball.pos()
if pos[0] == 0 or pos[0] >= gfx["screen"][0] - ball.image.get_size()[0] - 1:
ball.xInvert()
if pos[1] == 0:
ball.yInvert()
if pos[1] >= gfx["screen"][1] - ball.image.get_size()[1] - 1:
self.status.lives -= 1
self.actualState = states["START"]
self.playSound( "Resources/snd/chord.wav" )
while len(self.objects.balls()) != 1:
self.objects.removeBall((self.objects.balls())[0])
for powerup in self.objects.powerups():
self.objects.deletePowerup(powerup)
self.objects.balls()[0].reset()
self.objects.pad().reset()
for obj in self.objects.grid():
if ball.collision(obj):
self.status.points += 100
if obj.realx <= ball.position[0] and obj.realx + gfx["grid"][0] >= ball.position[0]:
ball.yInvert()
if obj.realy <= ball.position[1] and obj.realy + gfx["grid"][1] >= ball.position[1]:
ball.xInvert()
self.handleBrickCollision(obj)
if ball.collision(self.objects.pad()):
ball.yInvert()
if self.objects.pad().position[1] <= ball.position[1] and self.objects.pad().position[1] + gfx["grid"][1] >= ball.position[1]:
ball.xInvert()
for powerup in self.objects.powerups():
pad = self.objects.pad()
if powerup.collision(pad):
self.objects.deletePowerup(powerup)
self.generatePowerup()
if powerup.y == gfx["screen"][1] - 1 - powerup.image.get_size()[1]:
self.objects.deletePowerup(powerup)
if self.status.lives == 0:
self.actualState = states["GAMEOVER"]
if self.objects.grid() == []:
self.status.level += 1
if len(levels) == self.status.level:
self.actualStatus = states["GAMEOVER"]
else:
self.newLevel()
for modifier in self.status.modifiers:
modifier[1] -= 1
if modifier[1] == 0:
if modifier[0] == "big_pad":
self.objects.pad().setWidth(3)
del modifier
def generatePowerup(self):
r = random.randint(1,3)
# 3 possible powerups:
# 1 - +1 life
# 2 - for 30 sec the pad is larger
# 3 - additional ball
print (r)
if r == 1:
self.status.lives += 1
elif r == 2:
self.status.modifiers.append( [ "big_pad", gfx["framerate"] * 30 ] )
self.objects.pad().setWidth(5)
elif r == 3:
ball = Ball()
ball.position[0] = self.objects.pad().position[0] + (gfx["grid"][0]*self.objects.pad().gridWidth/2)
ball.speedChange( int( math.copysign( 5., float(self.objects.pad().lastMove) ) ), -5 )
self.objects.addBall(ball)
def handleBrickCollision(self,obj):
brickType = obj.getType()
if brickType == "simple":
self.objects.setGrid( obj.x, obj.y, None )
rand = random.randint( 0, 9 )
if rand == 9: # 1/10 chance for powerup
self.objects.spawnPowerup( obj.x, obj.y )
elif brickType == "solid":
self.objects.setGrid( obj.x, obj.y, SimpleBrick(obj.x,obj.y) )
elif brickType == "ghost":
newType = random.randint( 0, 1 )
if newType == 0:
self.objects.setGrid( obj.x, obj.y, SimpleBrick(obj.x,obj.y) )
elif newType == 1:
self.objects.setGrid( obj.x, obj.y, SolidBrick(obj.x,obj.y) )
self.playSound( "Resources/snd/ding.wav" )
def newLevel(self):
self.playSound( "Resources/snd/tada.wav" )
self.mapper.load( self.status.level )
self.objects.pad().reset()
while len(self.objects.balls()) != 1:
self.objects.removeBall((self.objects.balls())[0])
self.objects.balls()[0].reset()
self.actualState = states["START"]
class Status:
def __init__(self):
self.level = 0
self.points = 0
self.lives = startState["lives"]
self.modifiers = []
game = Game()
while True:
game.loop()