def __init__(self): super(Ui_MainWindow, self).__init__() self.userinfo = UserInfo("userinfo.txt") self.figure = Figure() self.stack1 = QWidget() self.stack2 = QWidget() self.stack3 = QWidget() self.init_main_window() self.init_parameter_window() self.init_egram_window() self.Stack = QStackedWidget(self) self.Stack.addWidget(self.stack1) self.Stack.addWidget(self.stack2) self.Stack.addWidget(self.stack3) hbox = QHBoxLayout(self) hbox.addWidget(self.Stack) self.setLayout(hbox) self.setGeometry(300, 50, 750, 400) self.setWindowTitle('Pacemaker DCM') self.show()
def __init__(self, userInfo): if userInfo.__class__ == UserInfo: self.userInfo = userInfo else: self.userInfo = UserInfo(userInfo) self.data = []
def __init__(self, userInfo): if userInfo.__class__ != UserInfo: userInfo = UserInfo(userInfo) self.ids = userInfo.getID() self.foldersData = []
def checkRainbow(self): changed = False if self.globals['rainbow'] == 'rainbow': # check if any moderators are still in the room; count visible users cancel = True num_users = 0 for user_info in self.globals['users'].values(): if user_info.moderator: cancel = False if user_info.visible: num_users += 1 if cancel: self.globals['rainbow'] = None self.resetColors() return index = 0 for user_info in sorted(self.globals['users'].values()): if not user_info.visible: continue color1 = UserInfo.rainbow_for_pos(index, num_users) color2 = UserInfo.rainbow_for_pos(index + 1, num_users) if user_info.player_info.player_color != color1: user_info.player_info.player_color = color1 changed = True if user_info.player_info.team_color != color2: user_info.player_info.team_color = color2 changed = True index += 1 if changed: self.sendPlayerList(0, 0, self.VERB_CHANGE)
def userSignup(): if request.method == 'POST': user = UserInfo(request) result = user.insertUser() if (result == '201'): user_id = user.get_user_id() return jsonify({'response': user_id}), 201 return result, 400 #here the result is not json , not sure how to return the response here (should it be json?)
def printDB(): print("-----------------------------------------------------") keys = db.keys() for key in keys: userJsonFromDB = json.loads(db[key]) userInfo = UserInfo(**userJsonFromDB) userInfo.printUserInfo() print("-----------------------------------------------------")
async def handlePicturePost(message): author = message.author if author.name in db.keys(): userJsonFromDB = json.loads(db[author.name]) userInfo = UserInfo(**userJsonFromDB) if (userInfo.postedToday() == True): await warn_user_daily_post(message.author) await message.delete() else: print("\n" + author.name + " posted a picture\n") userInfo.addPost() userJSON = json.dumps(userInfo.__dict__) db[author.name] = userJSON await changeServerIcon(message) await author.create_dm() await author.dm_channel.send("Great job! See you again tomorrow :smiley:") else: print("\n" + author.name + " posted a picture\n") userInfo = UserInfo(author.name, int(datetime.now().timestamp()), 0, 0, 0, 0, 0) userInfo.addPost() userJSON = json.dumps(userInfo.__dict__) db[author.name] = userJSON await changeServerIcon(message) await author.create_dm() await author.dm_channel.send("Great job! See you again tomorrow :smiley:")
def userLogin(): if request.method == 'POST': user = UserInfo(request) result = user.loginUser() if (result == 'fail'): return jsonify({'user': '******' }), 500 #(is this right?) elif (result == "true"): return jsonify({'response': 'ok'}) else: return jsonify({'response': 'user name or password incorrect'}), 401
def getAllUser(self): userList = list() rows = self.__conn.execute("SELECT * FROM user") for row in rows: nickname, homedir, mail, fullname = row userInfo = UserInfo() userInfo.nickname = nickname userInfo.homedir = homedir userInfo.mail = mail userInfo.fullname = fullname userList.append(userInfo) return userList
def getUser(self, nickname): userList = list() rows = self.__conn.execute("SELECT * FROM user WHERE nickname='" + nickname + "';") for row in rows: nickname, homedir, mail, fullname = row userInfo = UserInfo() userInfo.nickname = nickname userInfo.homedir = homedir userInfo.mail = mail userInfo.fullname = fullname userList.append(userInfo) if len(userList) < 1: return -1 else: return userList[0]
def main(*args, **kwargs): win = visual.Window(fullscr=False, size=(1200, 800), color=(-1, -1, -1)) user_info = UserInfo() ##测试1 practice_1 = Practice_1(user_info, win, max_correct=2, max_total=5) practice_1.process() ##测试2 practice_2 = Practice_2(user_info, win, go_trail_number=3, stop_trail_number=1) practice_2.process() ##正式实验 formal_experiment = Formal_Experiment(user_info, win, go_trail_number=3, stop_trail_number=1) formal_experiment.process() formal_experiment.process() formal_experiment.process() win.close() return True
def RebuildList(): lock = Utmp.Lock() try: entries = [] hashes = {} active = set() for i in xrange(Config.USHM_SIZE): userinfo = UserInfo(i + 1) if userinfo.active == 1: entries.append((i, userinfo.userid)) hash = Utmp.Hash(userinfo.userid) hashes[hash] = hashes.get(hash, []) + [i] active.add(i) if entries == []: Log.info("NO USER! RESET!") Utmp.ResetUtmp(locked=True) else: cnt = len(entries) Log.info("Rebuild Utmp with %d entries" % cnt) entries.sort(key=lambda entry: entry[1]) UtmpHead.SetReadOnly(0) # rebuild list UtmpHead.SetListHead(entries[0][0] + 1) for i in xrange(len(entries)): pos = entries[i][0] next = entries[(i + 1) % cnt][0] prev = entries[(i - 1 + cnt) % cnt][0] UtmpHead.SetListNext(pos, next + 1) UtmpHead.SetListPrev(pos, prev + 1) print pos, "prev", prev, "next", next # rebuild hash for hash in hashes: cnt = len(hashes[hash]) UtmpHead.SetHashHead(hash, hashes[hash][0] + 1) print "hash", hash, "head", hashes[hash][0] for i in xrange(cnt): pos = hashes[hash][i] if i < cnt - 1: next = hashes[hash][i + 1] else: next = -1 UtmpHead.SetNext(pos, next + 1) print "next", pos, next for i in xrange(Config.UTMP_HASHSIZE): if i != 0 and UtmpHead.GetHashHead(i) != 0 and not i in hashes: UtmpHead.SetHashHead(i, 0) print "reset", i # TODO: rebuild free list at hash[0] #if min(active) > 0: # UtmpHead.SetHashHead(0, 1) UtmpHead.SetReadOnly(1) finally: Utmp.Unlock(lock)
def Clear2(uent): userinfo = UserInfo(uent) # Log.debug("clearing user %s uid %d loginid %d" % (userinfo.userid, userinfo.uid, uent)) user = UCache.GetUserByUid(userinfo.uid) UCache.DoAfterLogout(user, userinfo, uent, 0) login = Login.Login(uent) login.hash_remove() login.list_remove() if userinfo.active: UtmpHead.DecNumber() zeroinfo = UserInfo() zeroinfo.SetIndex(uent) zeroinfo.save()
def get_userlist(self, filename): ''' Read the user's id and password from a file ''' with open(filename, 'r') as f: # read data for line in f.readlines(): # remove '\n' and use ' ' split string, to get userid and password userid, password = line.replace('\n', '').split(' ') # store in the dict self.userlist[userid] = password self.userstatus[userid] = UserInfo(userid, '', '', '', STATUS_OFFLINT)
def extract_user_info(self, html): user_info_list = list() # get json reg = re.compile( r'<script>STK && STK\.pageletM && STK\.pageletM\.view\((\{"pid":"pl_user_feedList".+?)\)</script>', re.I) match = reg.search(html) if (match): m = match.group(1) header_json = json.loads(m) if (type(header_json) == types.DictType): soup = BeautifulSoup(header_json['html']) # 获取微博用户列表 user_list = soup.find_all("div", class_="person_detail") if (type(user_list) == types.NoneType): return None for user in user_list: user_info = UserInfo() # 获取用户的微博名称、ID、和博客地址 # 获取微博用户认证类型 p_tag = user.find("p", class_="person_name") self.extract_name_id_url_type(user_info, p_tag) #获取微博用户性别、地区 p_tag = user.find("p", class_="person_addr") self.extract_gender_location(user_info, p_tag) # 获取微博用户关注数、粉丝数和微博数 p_tag = user.find("p", class_="person_num") self.extract_friend_follower_wb_count(user_info, p_tag) # 获取微博用户简介 div_tag = user.find("div", class_="person_info") self.extract_user_description(user_info, div_tag) # 获取用户标签、教育信息、职业信息 p_tag = user.find_all("p", class_="person_label") self.extract_labels(user_info, p_tag) user_info_list.append(user_info) else: print "extract_user_info:get error" return user_info_list
def Clear2(uent): userinfo = UserInfo(uent) Log.debug("clearing user %s uid %d loginid %d" % (userinfo.userid, userinfo.uid, uent)) user = UCache.UCache.GetUserByUid(userinfo.uid) UCache.UCache.DoAfterLogout(user, userinfo, uent, 0) login = Login.Login(uent) login.hash_remove() login.list_remove() if (userinfo.active): UtmpHead.DecNumber() Log.debug("zeroing utmp %d" % uent) zeroinfo = UserInfo() zeroinfo.SetIndex(uent) zeroinfo.save()
def stat(): conn = db.connect_torndb() result = conn.query('select distinct(u.id) from deal_note dn ' 'left join user u on dn.userId = u.id ' 'where dn.iom = %s and dn.createTime > %s', 'Y', '2016-05-01') list = [] for item in result: info = conn.get("select * from user u " "left join user_organization_rel uor on u.id = uor.userId " "left join organization o on o.id = uor.organizationId" " where u.id =%s ", item['id']) count = conn.get('select count(*) as count from deal_note ' 'where userId=%s and createTime > %s', item['id'], '2016-05-01') listItem = UserInfo(info['username'], info['name'], info['email'], count['count']) list.append(listItem) result = sorted(list, key=getCount, reverse=True) id =0 for item in result: id += 1 print id, item.username, item.orgName, item.email, item.count conn.close()
def getUserInfo(self): userinfoprocessor = UserInfo(self.userinfofilename) self.userInfo = userinfoprocessor.readUserInfoFile()
class Ui_MainWindow(QWidget): def __init__(self): super(Ui_MainWindow, self).__init__() self.userinfo = UserInfo("userinfo.txt") self.figure = Figure() self.stack1 = QWidget() self.stack2 = QWidget() self.stack3 = QWidget() self.main_window() self.parameter_window() self.egram_window() self.Stack = QStackedWidget(self) self.Stack.addWidget(self.stack1) self.Stack.addWidget(self.stack2) self.Stack.addWidget(self.stack3) hbox = QHBoxLayout(self) hbox.addWidget(self.Stack) self.setLayout(hbox) self.setGeometry(300, 50, 10, 10) self.setWindowTitle('Pacemaker DCM') self.show() def main_window(self): layout = QFormLayout() layout.setContentsMargins(100, 50, 100, 50) # Textboxes self.t_username, self.t_password = QLineEdit(), QLineEdit() self.t_password.setEchoMode(QLineEdit.Password) layout.addRow("Username:"******"Password:"******"Login"), QPushButton("Register") layout.addRow(b_login, b_register) b_login.clicked.connect(self.login) b_register.clicked.connect(self.register) # Label self.l_message = QLabel(" ") self.l_message.setStyleSheet("font-weight:bold;color:red") layout.addRow(self.l_message) self.stack1.setLayout(layout) def parameter_window(self): layout = QFormLayout() layout.setContentsMargins(100, 50, 100, 50) # Textboxes self.t_pulsewidth, self.t_pulseamplitude, self.t_heartrate, self.t_chambertopace = QLineEdit( ), QLineEdit(), QLineEdit(), QLineEdit() layout.addRow("Pulse Width:", self.t_pulsewidth) layout.addRow("Pulse Amplitude:", self.t_pulseamplitude) layout.addRow("Heart Rate:", self.t_heartrate) layout.addRow("Chamber to Pace:", self.t_chambertopace) # Buttons b_logout, b_update = QPushButton("Logout"), QPushButton("Update") layout.addRow(b_logout, b_update) b_logout.clicked.connect(self.logout) b_update.clicked.connect(self.update) self.stack2.setLayout(layout) def egram_window(self): layout = QFormLayout() layout.setContentsMargins(100, 50, 100, 50) # matplotlib Figure() canvas = FigureCanvas(self.figure) toolbar = NavigationToolbar(canvas, self.stack3) layout.addWidget(canvas) self.stack3.setLayout(layout) # Button functions def login(self): user, password = self.t_username.text(), self.t_password.text() message = self.userinfo.login(user, password) if message == "Login successful.": self.Stack.setCurrentIndex(1) else: self.l_message.setText(message) def register(self): user, password = self.t_username.text(), self.t_password.text() message = self.userinfo.register(user, password) self.l_message.setText(message) def logout(self): self.Stack.setCurrentIndex(0) self.t_username.setText("") self.t_password.setText("") self.l_message.setText("") def update(self): pass
class UserVotesData: '''UserVotesData. Используется для хранения и загрузки данных об оценках пользователя. Может принимать в конструкторе: 1. id пользователя (как число или строку); 2. Объект UserInfo. Имеет методы: getUserInfo() getData() loadData() loadDataFromSite() loadDataFromFolder(folder) loadDataFromTable(sheet)''' eye = 0 fields = ['nameRus', 'nameEng', 'filmId', 'link', 'vote', 'date'] def __init__(self, userInfo): if userInfo.__class__ == UserInfo: self.userInfo = userInfo else: self.userInfo = UserInfo(userInfo) self.data = [] def getData(self): '''Метод getData(). Возвращает данные об оценках пользователя.''' if self.data == []: print 'Данные ещё не загружены' return self.data def getUserInfo(self): '''Метод getUserInfo(). Возвращает информацию о пользователе (класс UserInfo).''' return self.userInfo def __loadDataInterface(self, offline=None, folder=None, isPrint=True): if offline == None: offline = settings.getMode() def getDataFromPage(page): def getDataAboutFilm(divItem): if divItem.find('div', UserVotesData.fields[0]) == None: return None sz = divItem.find('a')['href'].find('film/') + len('film/') film_id = divItem.find('a')['href'][sz:-1] film_link = settings.getMainLink() + 'film/' + str( film_id) + '/' return { UserVotesData.fields[0]: divItem.find('div', UserVotesData.fields[0]).text, UserVotesData.fields[1]: divItem.find('div', UserVotesData.fields[1]).text, UserVotesData.fields[2]: film_id, UserVotesData.fields[3]: film_link, UserVotesData.fields[4]: divItem.find('div', UserVotesData.fields[4]).text if divItem.find('div', UserVotesData.fields[4]).text != '' else str(UserVotesData.eye), UserVotesData.fields[5]: divItem.find('div', UserVotesData.fields[5]).text } userFilms = bs4.BeautifulSoup(page, 'lxml').find_all('div', 'item') return [getDataAboutFilm(film) for film in userFilms] pageNumber = 1 userVotesData = [] if isPrint: print 'Get user data:', self.userInfo.getNick() link = '' files = [] page = '' if offline: all_files = os.listdir(folder) for f in all_files: if 'htm' in f: files.append(f) file_r = open(os.path.join(folder, files[0])) page = file_r.read() file_r.close() else: link = self.userInfo.getLink() + '/votes/list/ord/date/page/' page = settings.getSession().get(link).text numberOfFilms = bs4.BeautifulSoup(page, 'lxml').find_all( 'h2', {'class': 'main_title'})[0].string numberOfFilms = int(numberOfFilms[numberOfFilms.index('(') + 1:numberOfFilms.index(')')]) ts = time.time() t1 = ts while True: page = '' if offline: if pageNumber <= len(files): file_r = open(os.path.join(folder, files[pageNumber - 1])) page = file_r.read() file_r.close() else: page = '' else: page = settings.getSession().get(link + str(pageNumber)).text data = getDataFromPage(page) while True: try: data.remove(None) except: break userVotesData += data pageNumber += 1 t2 = time.time() if isPrint: print 'Load', str( (len(userVotesData) * 100.0) / numberOfFilms) + '%...' print 'Time:', (t2 - t1), 'seconds' t1 = t2 if len(userVotesData) == numberOfFilms: if isPrint: print 'Load done' print 'Time:', (t2 - ts), 'seconds' break self.data = userVotesData return self def loadDataFromFolder(self, folder=None, isPrint=True): '''Метод loadDataFromSite(folder). Загружает оценки пользователя из папки, название которой -- id пользователя. Параметр folder позволяет выбрать папку, в которой находится папка с данными. По умолчанию папка ищется в директории, откуда вызывается программа. Параметр isPrint отвечает за вывод вспомогательной информации о загрузке.''' if folder == None: folder = os.path.join('.', self.userInfo.getID()) return self.__loadDataInterface(offline=True, folder=folder, isPrint=isPrint) def loadDataFromSite(self, isPrint=True): '''Метод loadDataFromSite(). Загружает оценки пользователя с сайта. Параметр isPrint отвечает за вывод вспомогательной информации о загрузке.''' return self.__loadDataInterface(offline=False, isPrint=isPrint) def loadData(self, isPrint=True): '''Метод loadData(). Загружает оценки пользователя в соответствии со значением переменной settings.OFFLINE_MODE. Параметр isPrint отвечает за вывод вспомогательной информации о загрузке.''' if settings.getMode(): return self.loadDataFromFolder(isPrint=isPrint) else: return self.loadDataFromSite(isPrint=isPrint) def loadDataFromTable(self, sheet): '''Метод loadDataFromTable(sheet). Загружает оценки пользователя из .xls-таблицы. Подробнее смотри класс DataVotesTablesLoader.''' row = sheet.row_values(0) usedFields = {} for idx in xrange(len(row)): usedFields[idx] = row[idx] self.data = [] sz = len(settings.getMainLink() + 'film/') + 1 for idx in range(1, sheet.nrows): row = sheet.row_values(idx) dataAboutFilm = {} for jdx in xrange(len(row)): dataAboutFilm[usedFields[jdx]] = row[jdx] dataAboutFilm['filmId'] = dataAboutFilm['link'][sz:-1] self.data += [dataAboutFilm] return self
def getUser(userKey): userJsonFromDB = json.loads(db[userKey]) return UserInfo(**userJsonFromDB)
from UserInfo import UserInfo from UserTopics import UserTopics from UserAsk import UserAsk from AskTopics import AskTopics from UserAnswer import UserAnswer UserInfo(1) # UserTopics(1) # UserAsk(1) # AskTopics(1) # UserAnswer(1)
def InitNewUserInfo(self): userinfo = UserInfo() userinfo.active = 1 userinfo.pid = os.getpid() if ((self.user.HasPerm(User.PERM_CHATCLOAK) or self.user.HasPerm(User.PERM_CLOAK)) and (self.user.HasFlag(User.CLOAK_FLAG))): userinfo.invisible = 1 userinfo.mode = modes.XMPP userinfo.pager = 0 if (self.user.Defined(User.DEF_FRIENDCALL)): userinfo.pager |= User.FRIEND_PAGER if (self.user.HasFlag(User.PAGER_FLAG)): userinfo.pager |= User.ALL_PAGER userinfo.pager |= User.FRIEND_PAGER if (self.user.Defined(User.DEF_FRIENDMSG)): userinfo.pager |= User.FRIENDMSG_PAGER if (self.user.Defined(User.DEF_ALLMSG)): userinfo.pager |= User.ALLMSG_PAGER userinfo.pager |= User.FRIENDMSG_PAGER userinfo.uid = self.uid setattr(userinfo, 'from', self._fromip) userinfo.freshtime = int(time.time()) userinfo.userid = self.username userinfo.realname = 'ANONYMOUS' # XXX: fix later userinfo.username = self.user.userec.username return userinfo
class Ui_MainWindow(QWidget): def __init__(self): super(Ui_MainWindow, self).__init__() self.userinfo = UserInfo("userinfo.txt") self.figure = Figure() self.stack1 = QWidget() self.stack2 = QWidget() self.stack3 = QWidget() self.init_main_window() self.init_parameter_window() self.init_egram_window() self.Stack = QStackedWidget(self) self.Stack.addWidget(self.stack1) self.Stack.addWidget(self.stack2) self.Stack.addWidget(self.stack3) hbox = QHBoxLayout(self) hbox.addWidget(self.Stack) self.setLayout(hbox) self.setGeometry(300, 50, 750, 400) self.setWindowTitle('Pacemaker DCM') self.show() # ---- Init Functions def init_main_window(self): layout = QFormLayout() layout.setContentsMargins(300, 150, 300, 150) # left,top,right,bottom # - Textboxes self.t_username, self.t_password = QLineEdit("test_user"), QLineEdit( "pass") self.t_password.setEchoMode(QLineEdit.Password) layout.addRow("Username:"******"Password:"******"Login"), QPushButton("Register") layout.addRow(b_login, b_register) b_login.clicked.connect(self.login) b_register.clicked.connect(self.register) # - Label self.l_message = QLabel(" ") self.l_message.setStyleSheet("font-weight:bold;color:red") layout.addRow(self.l_message) self.stack1.setLayout(layout) def init_parameter_window(self): layout = QFormLayout() layout.setContentsMargins(300, 150, 300, 150) # left,top,right,bottom # - Parameters # heart rate self.sb_heartrate = QSpinBox() self.sb_heartrate.setRange(30, 175) container = Wrapper((self.sb_heartrate, QLabel(("(bpm)")))) layout.addRow("Heart Rate:", container) # chamber to pulse rbg_chambertopulse = QButtonGroup() self.rb_ctp_A = QRadioButton("A") rbg_chambertopulse.addButton(self.rb_ctp_A) self.rb_ctp_V = QRadioButton("V") rbg_chambertopulse.addButton(self.rb_ctp_V) container = Wrapper((self.rb_ctp_A, self.rb_ctp_V)) layout.addRow("Chamber to Pulse: ", container) # pulse width self.sb_pulsewidth = QDoubleSpinBox() self.sb_pulsewidth.setRange(0.1, 1.9) self.sb_pulsewidth.setDecimals(1) self.sb_pulsewidth.setSingleStep(0.1) container = Wrapper((self.sb_pulsewidth, QLabel(("(msec)")))) layout.addRow("Pulse Width:", container) # pulse amplitude self.sb_pulseamplitude = QDoubleSpinBox() self.sb_pulseamplitude.setRange(0.5, 7.0) self.sb_pulseamplitude.setDecimals(1) self.sb_pulseamplitude.setSingleStep(0.1) container = Wrapper((self.sb_pulseamplitude, QLabel(("(V)")))) layout.addRow("Pulse Amplitude:", container) # chamber to sense rbg_chambertosense = QButtonGroup() self.rb_cts_A = QRadioButton("A") rbg_chambertosense.addButton(self.rb_cts_A) self.rb_cts_V = QRadioButton("V") rbg_chambertosense.addButton(self.rb_cts_V) self.rb_cts_none = QRadioButton("None") rbg_chambertosense.addButton(self.rb_cts_none) container = Wrapper((self.rb_cts_A, self.rb_cts_V, self.rb_cts_none)) layout.addRow("Chamber to Sense: ", container) # ventricular sensitivity self.sb_ventricularsensitivity = QDoubleSpinBox() self.sb_ventricularsensitivity.setRange(1, 10) self.sb_ventricularsensitivity.setDecimals(1) self.sb_ventricularsensitivity.setSingleStep(0.1) container = Wrapper((self.sb_ventricularsensitivity, QLabel(("(mV)")))) layout.addRow("Ventricular Sensitivity: ", container) # atrial sensitivity rbg_atrialsensitivity = QButtonGroup() self.rb_as_25 = QRadioButton("0.25") rbg_atrialsensitivity.addButton(self.rb_as_25) self.rb_as_50 = QRadioButton("0.50") rbg_atrialsensitivity.addButton(self.rb_as_50) self.rb_as_75 = QRadioButton("0.75") rbg_atrialsensitivity.addButton(self.rb_as_75) container = Wrapper( (self.rb_as_25, self.rb_as_50, self.rb_as_75, QLabel("(mV)"))) layout.addRow("Atrial Sensitivity: ", container) # rate adaption rbg_rateadaption = QButtonGroup() self.rb_ra_on = QRadioButton("On") rbg_rateadaption.addButton(self.rb_ra_on) self.rb_ra_off = QRadioButton("Off") rbg_rateadaption.addButton(self.rb_ra_off) container = Wrapper((self.rb_ra_on, self.rb_ra_off)) layout.addRow("Rate Adaption: ", container) # Medium Activity Threshold self.sb_mediumactivitythreshold = QSpinBox() self.sb_mediumactivitythreshold.setRange(0, 500) container = Wrapper((self.sb_mediumactivitythreshold, )) layout.addRow("Medium Activity Threshold: ", container) # High Activity Threshold self.sb_highactivitythreshold = QSpinBox() self.sb_highactivitythreshold.setRange(0, 500) container = Wrapper((self.sb_highactivitythreshold, )) layout.addRow("High Activity Interval: ", container) # Reaction Time self.sb_reactiontime = QSpinBox() self.sb_reactiontime.setRange(10, 50) container = Wrapper((self.sb_reactiontime, QLabel("(s)"))) layout.addRow("Reaction Time: ", container) # Recovery Time self.sb_recoverytime = QSpinBox() self.sb_recoverytime.setRange(2, 16) container = Wrapper((self.sb_recoverytime, QLabel("(min)"))) layout.addRow("Recovery Time: ", container) # hysterisis rbg_hysteris = QButtonGroup() self.rb_h_on = QRadioButton("On") rbg_hysteris.addButton(self.rb_ra_on) self.rb_h_off = QRadioButton("Off") rbg_hysteris.addButton(self.rb_ra_off) container = Wrapper((self.rb_h_on, self.rb_h_off)) layout.addRow("Hysterisis: ", container) # hysterisis interval self.sb_hysterisisinterval = QSpinBox() self.sb_hysterisisinterval.setRange(200, 500) container = Wrapper((self.sb_hysterisisinterval, QLabel(("(msec)")))) layout.addRow("Hysterisis Interval: ", container) # vrp self.sb_vrp = QSpinBox() self.sb_vrp.setRange(150, 500) container = Wrapper((self.sb_vrp, QLabel("(msec)"))) layout.addRow("VRP: ", container) # arp self.sb_arp = QSpinBox() self.sb_arp.setRange(150, 500) container = Wrapper((self.sb_arp, QLabel("(msec)"))) layout.addRow("ARP: ", container) # - Set default parameter values self.param_set_default() # - Buttons b_logout, b_update, b_egram = QPushButton("Logout"), QPushButton( "Update"), QPushButton("Show Electrogram") container = Wrapper((b_logout, b_update, b_egram)) layout.addRow(container) b_logout.clicked.connect(self.logout) b_update.clicked.connect(self.update) b_egram.clicked.connect(self.show_egram) self.rb_ctp_A.clicked.connect(self.check_chamber_pulse) self.rb_ctp_V.clicked.connect(self.check_chamber_pulse) self.rb_cts_A.clicked.connect(self.check_chamber_sense) self.rb_cts_V.clicked.connect(self.check_chamber_sense) self.stack2.setLayout(layout) def param_set_default(self): self.sb_heartrate.setValue(60) self.rb_ctp_V.setChecked(True) self.sb_pulsewidth.setValue(0.4) self.sb_pulseamplitude.setValue(3.5) self.rb_cts_none.setChecked(True) self.sb_ventricularsensitivity.setValue(2.5) self.rb_as_75.setChecked(True) self.rb_ra_off.setChecked(True) self.sb_mediumactivitythreshold.setValue(0) self.sb_highactivitythreshold.setValue(0) self.sb_reactiontime.setValue(10) self.sb_recoverytime.setValue(2) self.rb_h_off.setChecked(True) self.sb_hysterisisinterval.setValue(300) self.sb_vrp.setValue(320) self.sb_arp.setValue(250) def init_egram_window(self): layout = QFormLayout() layout.setContentsMargins(30, 30, 30, 30) # left,top,right,bottom # matplotlib figure self.figure = CustomFigCanvas((0, 175), (-2, 4), 5, 5, 75) layout.addRow(self.figure) # - Buttons back, start = QPushButton("Back"), QPushButton("Start") layout.addRow(back, start) back.clicked.connect(self.back) start.clicked.connect(self.start) self.stack3.setLayout(layout) # ---- Get Functions # Returns a list of parameters if all parameters are within acceptable range # Returns an error message if not def get_parameters(self): # Read values heartrate = int(self.sb_heartrate.value()) chambertopulse = 0 if self.rb_ctp_A.isChecked() else (\ 1 if self.rb_ctp_V.isChecked() else 'P') pulsewidth = int(self.sb_pulsewidth.value() * 10) pulseamplitude = int(self.sb_pulseamplitude.value() * 10) chambertosense = 0 if self.rb_cts_none.isChecked() else (\ 1 if self.rb_cts_V.isChecked() else (\ 2 if self.rb_cts_A.isChecked() else 'S')) ventricularsensitivity = int(self.sb_ventricularsensitivity.value() * 10) atrialsensitivity = 25 if self.rb_cts_A.isChecked() else (\ 50 if self.rb_cts_V.isChecked() else (\ 75 if self.rb_cts_none.isChecked() else '')) rateadaptation = 1 if self.rb_ra_on.isChecked() else (\ 0 if self.rb_ra_off.isChecked() else '') mediumthreshold = self.sb_mediumactivitythreshold.value() highthreshold = self.sb_highactivitythreshold.value() reactiontime = self.sb_reactiontime.value() recoverytime = self.sb_recoverytime.value() hysterisis = 1 if self.rb_h_on.isChecked() else (\ 0 if self.rb_h_off.isChecked() else 'H') hysterisisinterval = self.sb_hysterisisinterval.value() // 2 vrp = self.sb_vrp.value() // 2 arp = self.sb_arp.value() // 2 return [ 22, 85, 0, heartrate, # byte 4 chambertopulse, # byte 5 pulsewidth, # byte 6 mediumthreshold, # byte 7 pulseamplitude, # byte 8 highthreshold, # byte 9 chambertosense, # byte 10 ventricularsensitivity, # byte 11 0, # byte 12 (free) atrialsensitivity, # byte 13 rateadaptation, # byte 14 hysterisis, # byte 15 hysterisisinterval, # byte 16 reactiontime, # byte 17 vrp, # byte 18 recoverytime, # byte 19 arp ] # byte 20 # ---- Button Functions def login(self): user, password = self.t_username.text(), self.t_password.text() if user == '' or password == '': message = "The fields cannot be empty." else: message = self.userinfo.login(user, password) if message == "Login successful.": self.Stack.setCurrentIndex(1) else: self.l_message.setText(message) def register(self): user, password = self.t_username.text(), self.t_password.text() if user == '' or password == '': message = "The fields cannot be empty." else: message = self.userinfo.register(user, password) self.param_set_default() self.l_message.setText(message) def logout(self): self.Stack.setCurrentIndex(0) self.t_username.setText("") self.t_password.setText("") self.l_message.setText("") def update(self): global bpm bpm = int(self.sb_heartrate.value()) par = self.get_parameters() print("Sent:\t", bytearray(par)) serial(bytearray(par)) a = bytearray(par) print([i for i in a]) def show_egram(self): self.Stack.setCurrentIndex(2) def back(self): global stop, start if start: stop = True # kills thread start = False self.t1.join() self.figure.y = self.figure.n * 0.0 self.Stack.setCurrentIndex(1) def start(self): global stop, start if start: print("Cannot start multiple threads.") return stop = False start = True self.t1 = threading.Thread( target=dataSendLoop, daemon=True, args=(self.addData_callback, ) ) # setting daemon to True kills the thread when the main thread exits. self.t1.start() # ensures that pulse and sense are in the same mode at all times def check_chamber_pulse(self): if self.rb_cts_none.isChecked(): return if (self.rb_ctp_A.isChecked()): self.rb_cts_A.setChecked(True) elif (self.rb_ctp_V.isChecked()): self.rb_cts_V.setChecked(True) def check_chamber_sense(self): if (self.rb_cts_A.isChecked()): self.rb_ctp_A.setChecked(True) elif (self.rb_cts_V.isChecked()): self.rb_ctp_V.setChecked(True) # ---- For egram multithreading def addData_callback(self, val): self.figure.add_data(val)
def dump_userinfo(i): userinfo = UserInfo(i) print vars(userinfo)