ImportError: cannot import name 'BaseSSLError' from 'urllib3.connection' - python

I am trying to use mllfow library to log the variables. The code is very simple and basic. After running my script, I am receiving an error like cannot import name 'BaseSSLError' from 'urllib3.connection'. Please refer below code.
import mlflow
def calculate_nthpower(x, n):
return x**n
if __name__ == '__main__':
# context manager
with mlflow.start_run():
x, n = 2, 5
y = calculate_nthpower(x, n)
mlflow.log_param('x', x)
mlflow.log_param('n', n)
mlflow.log_metric("y", y)

Related

Get filelocation with win32gui and run script while a specified progam is running

I am trying to program something with win32gui and now I need to know how I can get the filelocation of the file I am running in Visual Studio Code, Word or Wordpad. I used win32gui.GetOpenFileName, but it doesn't work anymore after I checked the type of variable I get. My question is: Is it the best way to get the filelocation or is there a better way. If it is the best way does someone know why it's not working anymore?
My Second question is regarding the running of the script. I want to run the script automatically as soon as I start Word, Visual Studio Code or Wordpad. What is the best way to do this?
I tried finding solutions online but at the moment I am lacking inspiration. Thank you for your help.
Update>
I got this far with the code. I want to change it so that I can get the file automatically and I want to start is with Visual Studio Code instead of starting it manuely every time.
import win32gui
import math
e = math.e
maxwidth = 1874
maxheight = 950
x =450
y = 1500 + round(maxwidth/(1+e**(-0.009*(0-57.45))))
#minwidth = 700
#minheight = 505
k = 0
l = 0
def main():
win32gui.EnumWindows(callback, None)
def callback(hwnd, extra):
windowopen = False
name = win32gui.GetWindowText(hwnd)
if name.endswith('Visual Studio Code') and name.startswith('_test.py'):
windowopen = True
print(name)
while windowopen:
j = 0
for i in open('D:\_test.py', 'r'):
j += 1
k = round(maxwidth/(1+e**(-0.009*(j-57.45))))
l = round(maxheight/(1+e**(-0.009*(j-57.45))))
yuse = y - k
win32gui.MoveWindow(hwnd, yuse, x, k, l, True)
print(name)
file = win32gui.GetOpenFileName
print(file)
if __name__ == '__main__':
main()
Update>
I imported os and than used the .path.dirname function to get my file location:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

How do I use a csv data as variables to apply it for a formula?

I'm trying to use data from a csv file ( https://www.kaggle.com/jingbinxu/sample-of-car-data ). I only need the horsepower and weight columns as variables for the equation: ( 1/4 mile et = 6.290 * (weight/hp) ** .33 ), but it won't apply it. I don't know if the storage is working or I shouldn't do it as a class. When I run the program it doesn't show any errors, but it doesn't show results either. Then I got to plot the results, but I don't think it's even calculating and storing results. Any help is appreciated. Thanks in advance.
Here's the current code i have:
import numpy as np
class car_race_analysis():
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename,delimiter= ',', skip_header = 1 )
def race_stats(self,w,h):
#cars in data
cars = np.unique(self.data[:,0])
#storage for output
race_times = []
#for each car
for car in cars:
#mask
mask = self.data[:,0] == car
#get data
w = self.data[mask,12]
h = self.data[mask,18]
#apply formula
qrtr_mile = 6.290 * ( w / h ) ** .33
race_times.append(qrtr_mile)
#new atribute
self.race_times = np.array(race_times)
print(race_times)
def trend_plotter(self):
import matlib.pyplot as plt
#inputs
self.race_stats
cars = np.unique(self.data[:,0])
#plot
plt.plot(cars,self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
filename = 'car_data.csv'
Two problems:
I think you meant matplotlib instead of matlib. Make sure you install it pip3 install matplotlib --user and edit your code accordingly.
Your previous code wasn't working because you weren't instantiating a class or running any methods. The only "work" your program did was to define the class and then set a filename variable.
To solve #2, replace your filename=... line with the code below.
Here's what it does:
It checks to see if the file is being run directly (i.e. from command prompt such as python3 <your_file_name>.py. If this class is being imported and used from a different python file, this code would not be executed. More reading: https://www.geeksforgeeks.org/what-does-the-if-name-main-do/
We instantiate a instance of your class and supply the filename variable since that it was your class' __init__ method expects.
We invoke the trend_plotter method on the instance of the class.
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
Even with those changes, your program will not work because it has other errors. I made a guess at fixing it, which I've pasted below, but I strongly encourage you do diff my changes to understand what I altered to be sure it does what you want.
import numpy as np
import matplotlib.pyplot as plt
class car_race_analysis():
race_times = []
cars = []
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename, delimiter=',', skip_header=1)
def race_stats(self, w, h):
#cars in data
self.cars = np.unique(self.data[:, 0])
# storage for output
self.race_times = []
# for each car
for car in self.cars:
# mask
mask = self.data[:, 0] == car
# get data
w = self.data[mask, 12]
h = self.data[mask, 18]
# apply formula
qrtr_mile = 6.290 * (w / h) ** .33
self.race_times.append(qrtr_mile)
# new atribute
self.race_times = np.array(self.race_times)
def trend_plotter(self):
# inputs
self.race_stats(len(self.cars), len(self.race_times))
# plot
plt.plot(self.cars, self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
plt.show()
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()

how to connect input and function module in main module and can we return list from a function?

I have three modules: GetInput, Main and Converter. In the GetInput file there are all the inputs values and excel data in the form of list. In the Converter file I am using those input values from Getinput file and in the main file I am connecting both these files here. I am doing this so that my code can look more organized.
GetInput.py:
import pandas as pd
import numpy as np
import time
def getInputs():
df = pd.read_excel('input.xlsx')
actual = df['actual'].values.tolist()
schedule = df['schedule'].values.tolist()
freq = df['frequency'].values.tolist()
ACP = df['acp'].values.tolist()
modelInput = {
'actual': actual, 'schedule': schedule, 'freq': freq, 'ACP': ACP,'df' : df
}
return modelInput
Converter.py
import pandas as pd
def fun(modelInput):
underdraw = []
overdraw = []
for i,j, in zip(schedule, actual):
dev = j - i
if dev < 0:
underdraw.append(dev)
else:
underdraw.append(0)
if dev > 0:
overdraw.append(dev)
else:
overdraw.append(0)
df['underdraw'] = pd.Series(underdraw)
df['overdraw'] = pd.Series(overdraw)
df.to_excel('mainfile.xlsx')
Main.py
import pandas as pd
import numpy as np
from convert import *
from GetInputs import *
def fun1():
inpu = getInputs()
con = fun(inpu)
fun1()
This whole program works when I run it in a single module but it throw errors when I try divide my code into separate modules. Basically it throw error in GetInput.py and in Converter.py (df is not defined) file. I know its a very basic thing but I don't know how to make it work. There is no desired output for this program, I am already getting an output when I run it in a single file. I just want to divide my code in this format as I mentioned above: GetIput File, Converter File and Main File.
Keep all the files in same directory or else mention the file paths at the top of main code using os module.
You have misspelled the following in the main code:
from convert import *
from GetInputs import *
It should be:
from Converter import *
from GetInput import *
I have tested this using the following:
MainModule.py
from Converter import *
from GetInputs import *
def fun1():
inpu = getInputs()
con = fun(inpu)
fun1()
Converter.py
import pandas as pd
def fun(modelInput):
print("HIE" + modelInput)
GetInputs.py
def getInputs():
return "modelInput"

text_generator.py "Access is Denied"

I'm having trouble with this code. For some reason whenever I use the test client, I get this message.
import stdio
import sys
from markov_model import MarkovModel
def main():
k = int(sys.argv[1])
T = int(sys.argv[2])
# text from standard input initialized to variable
text = sys.stdin.read()
# slices text and initializes it to kgram
kgram = text[:k]
model = markov_model(text, k)
# model is used to generate random length of text
stdio.writeln(model.gen(kgram, T))
if __name__ == '__main__':
main()
text_generator.py 5 50 < data / bible.txt
Access is denied.

Loading dll just outside class is giving different behavior

I'm using python to load a DLL generated in c++ (working correctly) using the cdll.LoadLibrary(). The issue is that I'm needing to reload the DLL inside the class every time the class is called, otherwise it gives a different behavior.
When I reload the dll inside the class the code evaluate the fitness function for about 4192 times (262 iterations), but when I remove the two lines that reloads the dll, the code runs just 16 times (one iteration), stopping before convergence.
This is my code:
import sys
import os
import pygmo as pg
from ctypes import *
pathname = os.path.dirname(sys.argv[0])
dllPath = os.path.join((os.path.abspath(pathname)), 'optmization_functions.dll')
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
class RosenbrockDLL():
def __init__(self, n):
"""Pass dimensions to constructor."""
self.n = n
def fitness(self, x):
"""
The Rosenbrock function.
sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
"""
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
x2 = (c_double * self.n)(*x)
r = mydll.rosen(c_int(self.n), x2)
return [r]
def get_bounds(self):
return ([-5]*self.n,[10]*self.n)
def pygmo_methods(func=RosenbrockDLL, N_vars=4, N_pop=16, N_gers=1000):
prob = pg.problem(func(n = N_vars))
algo = pg.algorithm(pg.de1220(gen = N_gers))
algo.set_verbosity(0)
archi = pg.archipelago(1, algo=algo, prob=prob, pop_size=N_pop)
archi.evolve(1)
archi.wait()
bestFevals = archi[0].get_population().problem.get_fevals()
print('\tFunction value:', *archi.get_champions_f())
print('\tDesign values:', *archi.get_champions_x())
print('\tFunction evaluations:', bestFevals)
print('\tNumber of generations:', bestFevals//N_pop)
if __name__ == "__main__":
N = 4
pygmo_methods(func=RosenbrockDLL, N_vars=N, N_pop=16, N_gers=1000)
Right now the code is reloading the dll every time the fitness is called, what increases the elapsed time. I would like to load it just once.

Categories

Resources