Make model function to stop counting - django

In a django app i have a model function that counting the progress of an event between date time fields. Is it possible to stop the progress after reaching 100. For example:
models.py
start_appointment = models.DateTimeField(default=timezone.now, blank=True)
end_appointment = models.DateTimeField(default=timezone.now, blank=True)
model function
def get_progress(self):
if (self.status) == 'New' or (self.status) == 'Finished':
now = timezone.now()
progress = ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100
if progress > 100.0:
...
return progress
Thank you

Simply use the Python min() function. That will return your progress calculation or 100 if the progress calculation is larger.
def get_progress(self):
if (self.status) == 'New' or (self.status) == 'Finished':
now = timezone.now()
progress = min(((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100, 100)
return progress

def get_progress(self):
return ((timezone.now() - self.start_appointment) / ((self.end_appointment - now) + (now - self.start_appointment)))*100
def other_process():
while self.get_progress() < 100:
Do stuff here...
return progress
This will return the progress once it the appointment is over. Maybe you will want to return True or something instead to assert the appointment is complete

Related

Open and close of the first 1 min bar

I know it's a long shot to ask here, but I am looking for a way to determine if the first 1 minute candle is red, meaning that the bar closes below the open.
To do this I simply need the open value and close value of the first one minute bar, but I haven't found a way to get the close.
Getting the open is fairly straight forward:
def openValue = open(period = AggregationPeriod.DAY);
Getting the Range of the first bar is fairly straightforward as well since we define a range (1 min) and return the high/low of that range.
If anybody can help, I would really appreciate it.
Thanks!
Ok, someone helped me figure it out.
def x = barNumber(); //bar
def RTH = getTime() >= RegularTradingStart(getYYYYMMDD()) and
getTime() <= RegularTradingEnd(getYYYYMMDD());
def TodaysOpen = if RTH and !RTH[1]
then open
else TodaysOpen[1];
def OpenX = if RTH and !RTH[1]
then x
else double.nan;
def YesterdaysClose = if !RTH and RTH[1]
then close[1]
else YesterdaysClose[1];
def CloseX = if !RTH and RTH[1]
then x
else double.nan;
def HighToday = if RTH and !RTH[1]
then high
else if RTH and high > HighToday[1]
then high
else HighToday[1];
def HighX = if high == HighToday
then x
else double.nan;
def LowToday = if RTH and !RTH[1]
then low
else if RTH and low < LowToday[1]
then low
else LowToday[1];
def LowX = if low == LowToday
then x
else double.nan;
plot OpenToday = if barNumber() >= HighestAll(OpenX)
then HighestAll(if isNaN(close[-1])
then TodaysOpen
else double.nan)
else double.nan;
OpenToday.SetStyle(Curve.Long_Dash);
def firstbarclose = if RTH and !RTH[1]
then close
else firstbarclose[1];
plot CloseBar = if barNumber() >= HighestAll(OpenX)
then HighestAll(if isNaN(close[-1])
then firstbarclose
else double.nan)
else double.nan;
closebar.SetStyle(Curve.Long_Dash);

Why are two objects being created in my sqlalchemy init? [duplicate]

This question already has answers here:
Why does running the Flask dev server run itself twice?
(7 answers)
Closed 5 years ago.
This is my Model:
class Category(db.Model):
__tablename__='category'
id = db.Column(db.Integer,primary_key=True)
items = db.relationship('Item',backref='category',lazy='dynamic')
name = db.Column(db.String(80))
order = db.Column(db.Integer)
private = db.Column(db.Boolean)
color = db.Column(db.String(80),unique=False)
def __init__(self,name,order=None,private=None):
r = lambda: random.randint(0, 255)
color = (r(), r(), r())
color = ('#%02X%02X%02X' % color)
count = db.session.query(Category).count()
print count
self.name = name
self.color = color
self.order = count+1
self.private = 1
def __repr__(self):
return '<Category %r>' % self.name
and I create the tables here:
def initialize_tables():
db.create_all()
c = Category(name="uncategorized")
db.session.add(c)
db.session.commit()
if __name__ == '__main__':
initialize_tables()
app.run(debug=True)
This creates two categories in my database named 'uncategorized'. Why is this happening?
That's because you're using app.run with debug=True:
If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
The way the reloader works is by starting itself again in a subprocess, so if __name__ == '__main__' (and hence initialize_tables) runs twice.

Tkinter button doesn't respond (has no mouse over effect)

I'm writing a game that has info that is communicated from client to server and from server to client. One specific (non-playing) client is the monitor, which only displays the game board and players. This works fine, the only thing that doesn't work is the quit button on the GUI. A minor thing, but I would like it to work. :) Plus I think that there might be something pretty wrong with the code, even though it works.
I tried all kind of different commands (sys.exit, quit...) and nothing fixed it.
There's no error message, nothing happens with the button at all. No mouse over effect, nothing if I click it. Relevant code (I removed matrix and server logic because I think it's irrelevant - if it isn't I'll post it):
class Main():
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
# Has to be counted up by server class
rounds = 0
# Has to be communicated by server class. If numberwin == numberrobots,
# game is won
numberwin = 0
numberrobots = 2
def draw(self):
if hasattr(self, 'info'):
self.info.destroy()
if hasattr(self, 'quit'):
self.quit.destroy()
print "Main should draw this matrix %s" % self.matrix
[...] lots of matrix stuff [...]
# Pop-Up if game was won
# TODO: Make GUI quittable
if self.numberwin == self.numberrobots:
self.top = Toplevel()
self.msg = Message(self.top, text="This game was won!")
self.msg.pack(side=LEFT)
self.quittop = Button(
self.top, text="Yay", command=self.frame.destroy)
self.quittop.pack(side=BOTTOM)
# TODO: Quit GUI
self.quit = Button(self.frame, text="Quit", command=self.frame.destroy)
self.quit.pack(side=BOTTOM)
# Information on the game
self.info = Label(
self.frame, text="Rounds played: {}, Numbers of robots in win condition: {}".format(self.rounds, self.numberwin))
self.info.pack(side=TOP)
def canvasCreator(self, numberrows, numbercolumns):
# Game board
self.canvas = Canvas(
self.frame, width=numbercolumns * 100 + 10, height=numberrows * 100 + 10)
self.canvas.pack()
class Agent(Protocol, basic.LineReceiver):
master = Tk()
main = Main(master)
# So first matrix is treated differently from later matrixes
flagFirstMatrix = 1
def connectionMade(self):
msg = dumps({"type": "monitor"})
self.sendLine(msg)
print "Sent message:", msg
def dataReceived(self, data):
# Decode the json dump
print "Data received: %s" % data
data = loads(data)
self.main.matrix = np.matrix(data["positions"])
self.main.goals = np.matrix(data["goals"])
self.main.next_move_by_agent = data["next_move"]
self.main.rounds = data["rounds"]
self.main.numberwin = data["win_states"]
if self.flagFirstMatrix == 1:
self.main.numberrows, self.main.numbercolumns = self.main.matrix.shape
self.main.canvasCreator(
self.main.numberrows, self.main.numbercolumns)
self.main.canvas.pack()
self.flagFirstMatrix = 0
self.main.canvas.delete(ALL)
self.main.draw()
self.master.update_idletasks()
self.master.update()
First there is no indentation for class Agent, second for the quit button's "call back" self.frame.destroy is never defined so it doesn't do anything. If you meant tkinter destroy method try self.frame.destroy() or try explicitly defining it. You can also try calling either fram.pack_forget() or fram.grid_forget()
Add master.mainloop() to your last line in terms of the entire lines of code

Tkinter forgetting to finish the function

I am again asking a question on this progressbar project; although this should just be a clarification question.
My code causes for a progressbar to be created to track the creation of a file. The user selects the type of file they want to create and then hits "go" which causes for the file to begin changing and for the progressbar to appear. Progressbar works great. File writing/manipulation works great.
Problem: When the user selects several files to manipulate, despite the progressbars being created correctly, they do NOT update correctly. At first I thought that clicking on a button multiple times causes for tkinter to forget the root.after() function it was doing previously but after playing with a (much simpler) sample code I realized that this is not the case.
Question: How do I make sure tkinter doesn't stop implementing the first function even when the same function is restarted with different parameters?
Below are parts of my code to describe what I am doing.
progbarlock = False # start with the prograssbar marked as not occupied
class guibuild:
def __init__(self):
self.root = root
guibuild.progbarlock = False
global theframe
theframe = Frame(root)
job_name = e.get()
label = Label(theframe,text = job_name).pack(side=LEFT,padx =2)
self.progbar = Meter(theframe) #makes the progressbar object
self.progbar.set(0.0) #sets the initial value to 0
self.progbar.pack(side=LEFT)
self.counter = 0
self.i = float(0) #i is the value set to the progressbar
def stop_progbar(self):
self.progbar.stop()
def begin(self):
self.interval()
self.Status_bar()
theframe.pack(anchor="s")
def interval(self):
if guibuild.progbarlock == False:
guibuild.progbarlock = True
def update(self):
the_file = open('running_file.json')
data = json.load(the_file)
curr = data["current_line"]
total = data["total_lines"]
if self.i == 1.0:
self.stop_progbar
rint "100% - process is done"
self.root.after_cancel(self.interval)
elif curr == self.counter:
self.root.after(5000, self.interval)
elif curr == self.counter+1:
self.i += 1.0/total
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter += 1
self.stop_progbar
self.root.after(5000, self.interval)
elif curr > self.counter+1:
self.i += 1.0/total*(curr-self.counter)
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter = curr
self.stop_progbar
self.root.after(5000, self.interval)
else:
print "something is wrong - running.json is not available"
self.root.after(5000, self.interval)
guibuild.progbarlock = False
def start_process():
makeRequest() #this is defined much earlier in the code and includes all the file creation and manipulation
guibuild().begin()
button4 = Button(root,text="GO", command = start_process).pack()
NOTE:makeRequest() depends entirely on user input and the user input changes each time "go" is pressed.

Denormalising field in django

I'm finding it difficult to denormalise a field in a django model. I have:
class AnswerSet(models.Model):
title = models.CharField(max_length=255)
num_answers = models.PositiveIntegerField(editable=False, default=0)
answers = models.ManyToManyField(Answer, through='AnswerSetAnswer')
...
class AnswerSetAnswer(models.Model):
answer = models.ForeignKey(Answer)
answer_set = models.ForeignKey(AnswerSet)
...
I want num_answers to contain a count of the number of answers in the set.
If 5 answers are initially associated with the AnswerSet "Food" and I edit one so it becomes associated with the AnswerSet "Colours", how can I recalculate the number of answers in the AnswerSet with "Food"? All the signals only seem to send the new data so I can't just override the save method.
I've tried using the m2m_changed signal, but it never gets called when I edit relationships through the admin form.
Here's my code anyway:
def update_answer_set_num_answers(sender, **kwargs):
"""
Updates the num_answers field to reflect the number of answers
associated with this AnswerSet
"""
instance = kwargs.get('instance', False)
print "no instance" # never gets here
if not instance:
return
action = kwargs.get('action')
print "action: ", action
if (action != 'pre_remove' and action != 'pre_add' and action != 'clear'):
return
reverse = kwargs.get('reverse')
if reverse:
answer_set = instance.answer_set
else:
answer_set = instance.answer_set
num_answers = AnswerSetAnswer.objects.filter(answer_set=answer_set.id).count()
if (action == 'pre_remove'):
num_answers -= int(kwargs.get('pk_set'))
elif (action == 'pre_add'):
num_answers += int(kwargs.get('pk_set'))
elif (action == 'clear'):
num_answers = 0
answer_set.num_answers = num_answers
print 'n a: ', answer_set.num_answers
answer_set.save()
m2m_changed.connect(update_answer_set_num_answers, \
AnswerSet.answers.through, weak=False)
Do you really need to denormalise this? You can calculate it with a simple aggregate:
from django.db.models import Count
answersets = AnswerSet.objects.all().annotate(num_answers=Count('answers')