-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathDecorators.py
287 lines (231 loc) · 6.93 KB
/
Decorators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# -*- coding: utf-8 -*-
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# Decorators.py ---
# --------------------------------
# Copyright (c) 2020
# L. CAPOCCHI ([email protected])
# SPE Lab - SISU Group - University of Corsica
# --------------------------------
# Version 2.0 last modified: 03/15/20
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GENERAL NOTES AND REMARKS:
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GLOBAL VARIABLES AND FUNCTIONS
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
import builtins
import os
import sys
import time
from datetime import datetime
import threading
from tempfile import gettempdir
import time
import cProfile, pstats, io
if builtins.__dict__.get('GUI_FLAG', True):
import wx
if wx.VERSION_STRING < '4.0':
import wx.aui
AuiFloatingFrame = wx.aui.AuiFloatingFrame
else:
import wx.lib.agw.aui.framemanager
AuiFloatingFrame = wx.lib.agw.aui.framemanager.AuiFloatingFrame
from pubsub import pub
from Utilities import getTopLevelWindow
_ = wx.GetTranslation
def cond_decorator(flag, dec):
def decorate(fn):
return dec(fn) if flag else fn
return decorate
class memoize:
# from http://avinashv.net/2008/04/python-decorators-syntactic-sugar/
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
def hotshotit(func):
def wrapper(*args, **kw):
sim_thread = args[0]
prof = sim_thread.prof
### if profiling check-box is checked in the simulationDialog
if prof:
### name of .prof file
label = sim_thread.model.getBlockModel().label
now = datetime.now() # current date and time
date_time = now.strftime('%m-%d-%Y_%H-%M-%S')
prof_name = os.path.join(os.path.realpath(gettempdir()),"%s_%s_%s%s"%(func.__name__, label, date_time ,'.prof'))
### profiling section with cProfile
pr = cProfile.Profile()
pr.enable()
r = func(*args, **kw)
pr.disable()
#Sort the statistics by the cumulative time spent in the function
sortby = 'cumulative'
ps = pstats.Stats(pr).sort_stats(sortby)
ps.dump_stats(prof_name)
else:
r = func(*args, **kw)
return r
return wrapper
def run_in_thread(fn):
''' decorator to execute a method in a specific thread
'''
def run(*k, **kw):
t = threading.Thread(target=fn, args=k, kwargs=kw)
t.start()
return run
def BuzyCursorNotification(f):
""" Decorator which give the buzy cursor for long process
"""
def wrapper(*args):
if builtins.__dict__.get('GUI_FLAG',True):
wait = wx.BusyCursor()
#wx.SafeYield()
r = f(*args)
if builtins.__dict__.get('GUI_FLAG',True):
del wait
return r
return wrapper
# allows arguments for a decorator
decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)
@decorator_with_args
def StatusBarNotification(f, arg):
""" Decorator which give information into status bar for the load and the save diagram operations
"""
def wrapper(*args):
# main window
mainW = getTopLevelWindow()
### find if detachedFrame exists
for win in [w for w in mainW.GetChildren() if w.IsTopLevel()]:
if win.IsActive() and isinstance(win, wx.Frame) and not isinstance(win, wx.aui.AuiFloatingFrame if wx.VERSION_STRING < '4.0' else wx.lib.agw.aui.framemanager.AuiFloatingFrame):
mainW = win
r = f(*args)
if hasattr(mainW, 'statusbar'):
diagram = args[0]
fn = os.path.basename(args[-1])
txt = arg
mainW.statusbar.SetStatusText('%s %sed'%(fn, txt), 0)
mainW.statusbar.SetStatusText(diagram.last_name_saved, 1)
mainW.statusbar.SetStatusText('', 2)
return r
return wrapper
class ThreadWithReturnValue(threading.Thread):
""" https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
"""
def __init__(self, *args, **kwargs):
super(ThreadWithReturnValue, self).__init__(*args, **kwargs)
#self._return = None
self.killed = False
self._log = ""
self._status = ""
pub.subscribe(self.my_listener, "to_progress_diag")
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
self._status = 'alive'
def __run(self):
sys.settrace(self.globaltrace)
self._return = self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, event, arg):
if event == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, event, arg):
if self.killed:
if event == 'line':
raise SystemExit()
return self.localtrace
def my_listener(self, message, arg2=None):
"""
Listener function
"""
self._log = message
if arg2 == 'stop':
self.kill()
elif arg2 is not None:
self._status = arg2
def getStatus(self):
return self._status
def getLog(self):
return self._log
def kill(self):
self.killed = True
# def run(self):
# if self._target is not None:
# try:
# self._return = self._target(*self._args, **self._kwargs)
# except Exception as e:
# self._return = e
# def join(self):
# if not isinstance(self._return, Exception):
# threading.Thread.join(self)
# return self._return
@decorator_with_args
def ProgressNotification(f, arg):
def wrapper(*args):
title = arg
new_path = args[-1]
if isinstance(new_path, str) and os.path.isfile(new_path):
message = _("Loading %s ...")%os.path.basename(new_path)
else:
message = _('Please wait..')
progress_dlg = wx.ProgressDialog(title, message, style=wx.PD_APP_MODAL|wx.PD_CAN_ABORT)
thread = ThreadWithReturnValue(target = f, args = args)
thread.start()
### isAlive is deprecated since python 3.9
while thread.isAlive() if hasattr(thread,'isAlive') else thread.is_alive():
if progress_dlg.WasCancelled() or progress_dlg.WasSkipped():
thread.kill()
else:
wx.MilliSleep(300)
progress_dlg.Pulse(thread.getLog())
wx.SafeYield()
progress_dlg.Destroy()
return thread.join()
return wrapper
def print_timing(func):
def wrapper(*arg):
t1 = time.time()
res = func(*arg)
t2 = time.time()
final_t = (t2-t1)*1000.0
return res
return wrapper
def Pre_Undo(f):
def wrapper(*args):
diagram = args[0]
diagram.Undo()
r = f(*args)
return r
return wrapper
def Post_Undo(f):
def wrapper(*args):
diagram = args[0]
r = f(*args)
diagram.Undo()
return r
return wrapper
def redirectStdout(f):
def wrapper(*args):
stdout = sys.stdout
output = ""
try:
sys.stdout = io.StringIO()
f(*args)
output = sys.stdout.getvalue()
finally:
sys.stdout = stdout
return output
return wrapper