I'm having trouble with passing a value from one script to another, trying to take it a step at a time but the big picture would be to print the value obj1.get_predval to my Django view and wait for the users' input.
active_learner.obj1.get_predval in my beta.py script doesn't work, it just prints out the initial value which makes sense because it's not running the main.py but I'm not sure how I'd pass the value of obj1.set_predval(machine_prediction) from main.py. It properly outputs the obj1.get_predval in the main.py script.
I'm assuming I have a fundamental misunderstanding, for now, all I'm trying to return is the value of obj1.get_predval in function beta.py, when it gets to the line return value and wait for user input then continue.
main.py script below
obj1 = MachinePred()
def main():
model = load_model('model_new.h5')
DATAFILE = "c_user_model_data100000.csv"
dataset = loadtxt(DATAFILE, delimiter=",")
X_pool, Y = dataset[:, 0:5], dataset[:, 5:]
sc_x, sc_y = StandardScaler(), StandardScaler()
X_pool, Y = sc_x.fit_transform(X_pool), sc_y.fit_transform(Y)
learner = ActiveLearner(
estimator = model,
query_strategy = uncertainty_sampling
)
for i in range(3):
query_idx, query_inst = learner.query(X_pool)
print("The machine queried:\n{}\nat index {}".format(
sc_x.inverse_transform(query_inst),
query_idx
)
)
machine_prediction = learner.predict(X_pool[query_idx])
obj1.set_predval(machine_prediction)
print("predvalue:", (obj1.get_predval()))
ratings = []
cc_factor = ["delay", "speed", "missing_words", "paraphrasing"]
for f in cc_factor:
user_answer = input("How would you rate the quality of {} between [1-5]: ".format(f))
ratings.append(user_answer)
print(ratings, np.array([ratings]).reshape(1,-1))
if __name__ == '__main__':
main()
beta.py
This is the script I'm trying to pass the value to below
import active_learner
print(A is: ", active_learner.obj1.get_predval)
mac.py Simple python script using the get and set methods below.
class MachinePred:
predval = 0 # Default value of the 'x' configuration setting
def __init__(self):
self.predval = 0
def set_predval(self, val):
self.predval = val
def get_predval(self):
return self.predval
So the solution to this was very simple, from my understanding it could be done using generator-based coroutines or splitting it into two functions inside a class and use an OO design. The coroutine method would use"yield" which would force exit the function returning the value then re-enter the function but this would limit your ability to use non-generator based coroutines which I did need to await input from my front end.
Using a class though you could put the active learner model and data in an "init method" then split from the machine_prediction = learner.predict(X_pool[query_idx]) for the first function after returning the values and perform the rest in a second function.
Related
I am using Finnhub api to get some live data. I have 2 codes, one which will login the api every once in a day and second one will give the data every hour.
The first function will give details to the second function based on which it will fetch the data.
Here is my first function
def finnhub_login():
finnhub_client = finnhub.Client(api_key="xxxxxxxxxxxx")
symbols = df['SYMBOLS'].to_list()
return symbols,finnhub_client
I would like to use the output i.e symbols and finnhub client to the second function
Here is the second function
def finnhub_api_call(symbols,finnhub_client):
main_value = 0
for i in symbols:
data = finnhub_client.quote(['symbol'])
main_value += data['dp']
return main_value
schedule.every(1).day.do(finnhub_login)
schedule.every(1).hour.do(finnhub_api_call,symbols,finnhub_client)
while True:
schedule.run_pending()
time.sleep(1)
In the above code, how do I save the return values of 1st function and then use it for the second function ?
you can wrap all of this in a class and use class variables.
You can instantiate your class and use the functions from there. Everytime you run the first function class variables will change. Second function will use the class variables instead of function parameters.
class FinnhubCaller:
def __init__(self):
pass
def finnhub_login(self):
self.client = finnhub.Client(api_key="xxxxxxxxxxxx")
self.symbols = df['SYMBOLS'].to_list()
def finnhub_api_call(self):
main_value = 0
for i in self.symbols:
data = self.client.quote(['symbol'])
main_value += data['dp']
return main_value
caller = FinnhubCaller()
schedule.every(1).day.do(caller.finnhub_login)
schedule.every(1).hour.do(caller.finnhub_api_call)
while True:
schedule.run_pending()
time.sleep(1)
I've never really used classes before, I just simply went the easy way (global variables), and now I would like to make my code right to avoid future complications.
This is my code:
from dearpygui.core import *
class Engine:
def __init__(self,serial,type,profile):
self.serial = serial
self.type = type
self.profile = profile
def apply_selected_file():
res = []
html_name= "example.html"
path= "C:/"
#Function that reads data from a file and saves selected data in a list
res = html_imp(path + '/' + html_name)
#I would like to remove the code below and use a class for each file instead
setvalue(sn1,es[0]) #shows a label with this value
setvalue(type1,res[1]) #shows a label with this value
setvalue(profile1,res[2]) #shows a label with this value
return res
def button():
#This was my initial idea but it doesn't seem to work.
# res = apply_selected_file()
# E = Engine(res[0],res[1],res[2])
I have in mind reading multiple HTML files so using a class would be much easier than declaring variables for each file:
1- Use apply_selected_file to read a file and assign values (s/n,type,profile) to a new class (E1,E2,E3,...,E20,...)
2- Use another function button() to access those stored class values.
I know there are many questions that touch upon this area, but none have clearly answered the problem I'm facing (or perhaps I'm just really thick).
So I'm transferring functional python code to OOP python, and I have some code
class fake_class:
def __init__(self, data_type=None):
if data_type is None:
self.data_type = ""
else:
self.data_type = data_type
def printToLog(x='', *args):
if args:
x = x.format(*args)
else:
x = str(x)
logFile.write(x)
logFile.write('\n')
print(x)
if __name__ == '__main__':
main()
def main(self):
self.printToLog('this is just an example, for some fake code')
f = fake_class('data-xml-435')
# please appreciate that the full code is over 500 lines
# long that has been edited down for the sake of readability
I need the main method to be able to call other methods in the class, but no matter what I do, I cannot manage to allow it to do so. I have made printToLog into a classmethod, I have tried different ways of instantiating the fake_class, calling and all to no avail. The program complains that it doesn't know what printToLog is, what self is or what fake_class is!
So how might I call a method with another method within Python?
if __name__ == '__main__':
main()
does not make any sense with class. You just don't need them.
With that removed, you have to call main explicitly using the object you created.
f = fake_class('data-xml-435')
f.main() # or f.printToLog(with arguments) whichever is exciting you!
Again, printToLog is function of class, so you need a self:
def printToLog(self, x='', *args):
if args:
x = x.format(*args)
else:
x = str(x)
logFile.write(x)
logFile.write('\n')
print(x)
I would like to make a class for taking inputs from the user and then return all these inputs for later process. An example, after taking inputs from the users (filenames) then the program stores the names in list. The program later will load the list and perform the process based on each filename for one process.
More explanations:
User inputs 3 filenames, 3 output filenames, Name of item within file, Json filenames.
I will create a class(Reason I create it so that it looks nice and wont be too messy since it doesnt contain in a function or class) to take these inputs and then return it.
Program reads the input one by one and perform the process in one script.
My code:
class ReturnAllInput():
def __init__(self,Morefilenames, Yourfilename, YourJsonName, Outputname, NameWithin):
self.Morefilenames = Morefilenames
self.Yourfilename = Yourfilename
self.YourJsonName = YourJsonName
self.Outputname = Outputname
self.NameWithin = NameWithin
def allInput():
Morefilenames = []
while True:
a = input("Please enter your Morefilenames " )
if a == "Complete":
break
else:
Morefilenames .append(a)
# user typed complete
print("You entered {} Morefilenames ".format(len(Morefilenames )))
for n in Morefilenames :
print('{}.txt'.format(n))
Yourfilename= input("Yourfilename")
YourJsonName= input("YourJsonName")
Outputname= input("Outputname")
NameWithin= input("NameWithin")
return ReturnAllInput(Morefilenames , Yourfilename, YourJsonName, Outputname, NameWithin)
for l in allinput(): #this is the section I do not know how to change it so that I could loop my return values of Morefilenames)
if __name__ == "__main__":
If my codes arent good enough, please do let me know so that I could improve more. I am still a beginner and would like to learn more. Thank you in advance.
if __name__ == '__main__': is just used when this python file is being used as a script to control the execution, see What does if __name__ == "__main__": do? and would normally be the outer control logic, e.g.:
if __name__ == '__main__':
for l in allinput():
allinput() returns the class, which isn't directly iterable. If you want to iterate over Morefilenames then reference that attribute, e.g.:
if __name__ == '__main__':
for l in allinput().Morefilenames:
print(l)
But you lose reference to you constructed class so it is probably better to separate these calls:
if __name__ == '__main__':
user_inputs = allinput()
for l in user_inputs.Morefilenames:
print(l)
My question is about getter/setter-type functionality in Python. I have a class, Week_Of_Meetings, that takes a blob of data from my Google Calendar and does some calculations on it.
wom = Week_Of_Meetings(google_meetings_blob)
I want to be able to return something like:
wom.total_seconds_in_meetings() # returns 36000
But, I'm not understanding how the getters/setters-type #property decorator can help me do this. In Java, I would use member variables, but you don't interact with them the same way in Python. How can I return calculations without starting with them in the constructor?
Class Week_Of_Meetings:
def __init__(self, google_meetings_blob)
self.google_meetings_blob = google_meetings_blob
def get_meetings_list(self, google_meetings_blob):
meetings_list = []
for meeting_id, meeting in enumerate(self.google_meetings_blob, 1):
summary = self._get_summary(meeting)
start = parse(meeting['start'].get('dateTime', meeting['start'].get('date')))
end = parse(meeting['end'].get('dateTime', meeting['end'].get('date')))
duration = end - start
num_attendees = self._get_num_attendees(meeting.get('attendees'))
m = Meeting(meeting_id, summary, start, end, duration, num_attendees)
meetings_list.append(m)
return meetings_list
def _get_summary(self, meeting):
summary = meeting.get('summary', 'No summary given')
return summary
def _get_num_attendees(self, num_attendees):
if num_attendees == None:
num_attendees = 1 # if invited only self to meeting
else:
num_attendees = len(num_attendees)
return num_attendees
When I add self.total_seconds_in_meetings to the
__init__()
I get "NameError: global name 'total_seconds_in_meetings' is not defined." That makes sense. It hasn't been defined. But I can't define it when it's supposed to be the result of calculations done on the google_meetings_blob. So, I'm confused where the 'total_seconds_in_meetings' goes in the class.
Thank you for the help!
Of course Python has member variables. How would classes work without them? You can set and get any instance data via self, as you are already doing with self.google_meetings_blob in __init__.