def show_(vars, force_avg=False): ''' show variable weights from results, calculates median or mean depending on distribution, user can force average ''' results = struct() for label, _set in vars.items(): normal = stats.shapiro( _set)[1] if len(_set) < 5000 else stats.normaltest(_set)[1] value = np.average(_set) if normal >= 0.05 or force_avg else np.median( _set) rng = np.std(_set) if normal > 0.05 or force_avg else stats.iqr(_set) print('{}:\t{:.2f}±{:.3f} ({:.3f})'.format(label, value, rng, normal)) results.set(**{label: struct(value=value, range=rng, normal=normal)}) return results
async def ritualPage(req): if 'facebookexternalhit' in req.headers.get('User-Agent', ''): return web.Response(status=403) name = req.match_info.get('name', 'error') if name not in active: return web.Response(text="Not Found", status=404) islead = req.url.path.endswith('/lead') if hasattr(active[name], 'participants'): foundLogin = connectUserRitual(req, active[name], islead) if not foundLogin: res = web.Response(body=tpl('html/login.html', errorhandler=error_handler), content_type='text/html') res.set_cookie('LastRitual', name) return res clientId = random_token() active[name].clients[clientId] = struct( chatQueue=asyncio.Queue(), lastSeen=datetime.now(), isStreamer=('streamer' in req.query), room=None, name='NotYetNamed', ) if active[name].welcome: active[name].clients[clientId].welcomed = False if 'fake' in req.query: active[name].clients[clientId].lastSeen = datetime(9999, 9, 9, 9, 9, 9) active[name].clients[clientId].welcomed = True for datum in active[name].allChats[-50:]: active[name].clients[clientId].chatQueue.put_nowait(datum) if hasattr(active[name], 'current_video_room'): await assign_twilio_room(active[name], clientId) else: video_room_id = '' video_token = '' if hasattr(active[name], 'participants') or hasattr( active[name], 'current_video_room'): for i, task in active[name].reqs.items(): task.cancel() return web.Response(body=tpl( 'html/client.html', name=name, clientId=clientId, errorhandler=error_handler, cclass=('shrunk' if hasattr(active[name], 'participants') or hasattr(active[name], 'current_video_room') else ''), ratio=str(active[name].ratio), breserve=active[name].breserve, islead=str(islead).lower(), bkgAll=str(active[name].bkgAll).lower(), rotate=str(active[name].rotate).lower(), videos=''.join( f'<video class="hidden" src="{video}" playsinline preload="auto"></video>' for video in active[name].videos), intercomappid=intercom_app_id, ), content_type='text/html', charset='utf8')
async def ritualPage(req): name = req.match_info.get('name', 'error') if name not in active: return web.Response(text="Not Found", status=404) islead = req.url.path.endswith('/lead') if hasattr(active[name], 'participants'): foundLogin = connectUserRitual(req, active[name], islead) if not foundLogin: res = web.Response(body=open('html/login.html').read(), content_type='text/html') res.set_cookie('LastRitual', name) return res clientId = random_token() active[name].clients[clientId] = struct(chatQueue=asyncio.Queue()) for datum in active[name].allChats[-50:]: active[name].clients[clientId].chatQueue.put_nowait(datum) if hasattr(active[name], 'current_video_room'): async with active[name].video_room_lock: if not active[name].current_video_room: active[name].current_video_room = await asyncio.get_event_loop( ).run_in_executor(None, twilio_client.video.rooms.create) video_room_id = active[name].current_video_room.unique_name active[name].population_of_current_video_room += 1 if active[name].population_of_current_video_room == 26: active[name].current_video_room = None active[name].population_of_current_video_room = 0 token_builder = twilio_access_token.AccessToken( account_sid=secrets['TWILIO_ACCOUNT_SID'], signing_key_sid=secrets['TWILIO_API_KEY'], secret=secrets['TWILIO_API_SECRET'], identity=clientId, ) token_builder.add_grant(twilio_grants.VideoGrant(room=video_room_id)) active[name].clients[clientId].video_token = token_builder.to_jwt( ).decode() active[name].clients[clientId].room = video_room_id else: video_room_id = '' video_token = '' if hasattr(active[name], 'participants') or hasattr( active[name], 'current_video_room'): for i, task in active[name].reqs.items(): task.cancel() return web.Response(body=tpl( 'html/client.html', name=name, clientId=clientId, cclass=('shrunk' if hasattr(active[name], 'participants') or video_room_id else ''), ratio=str(active[name].ratio), islead=str(islead).lower(), bkgAll=str(active[name].bkgAll).lower(), rotate=str(active[name].rotate).lower()), content_type='text/html', charset='utf8')
def AUC_of(stats, target='before', comparator='good', _from=0): ''' calculates ROC-AUC of stats using a target and a comparator ''' values = [v for source in stats for v in source.stats[target]] sens = 1 - sum([int(v < _from) for v in values]) / len(values) spec = np.average( [s for source in stats for s in source.stats[comparator]]) AUC = (sens + spec) / 2 print('sensitivity: {:.1%}'.format(sens)) print('specificity: {:.1%}'.format(spec)) print('ROC-AUC: {:.1%}'.format(AUC)) return struct(sens=sens, spec=spec, AUC=AUC)
def calculate_models_only(retries, hub, calc_args, message): ''' calculate models ''' results = [] while retries: print('{} tries before saving...'.format(retries)) print(message.format(M.DB.ids, M.DB.long_ids)) hub.calculate(**calc_args) hub.best = hub.unstacked assessed = set([int(s.hn) for s in hub.assessed]) result = struct(vars=hub.vars_of, stats=hub.stats, assessed=assessed) hub.best, hub.unstacked = [], [] results.append(result) retries -= 1 return results
async def login(req): form = await req.post() email = form['email'] name = form['name'] rid = np.base_repr(hash(email), 36) img = await getAvatar(form, rid) users[rid] = struct(name=name, img=img, email=email, rid=rid) logins = req.cookies.get('ritLogin') if logins: logins = logins.split('__') else: logins = [] print("logins: ",logins) logins = [ l for l in logins if l in users ] print("logins: ",logins) logins.append(rid) print("logins: ",logins) url = req.url if url.path == '/addLogin': url = str(url).replace('/addLogin','/manageLogins') # Curse the URL class's immutability res = web.HTTPFound(url) res.set_cookie('ritLogin', '__'.join(logins)) return res
def calculate_models(retries, hub, calc_args, curve_args, message): ''' calculate models and curves ''' results = [] while retries: print('{} tries before saving...'.format(retries)) print(message.format(M.DB.ids, M.DB.long_ids)) hub.calculate(**calc_args) hub.best = hub.unstacked ir, dc = set([int(s.hn) for s in hub.in_room ]), set([int(s.hn) for s in hub.dismissed]) result = struct(vars=hub.vars_of, stats=hub.stats, in_room=ir, discharged=dc) first, last, fcs, rcs, rc = calculate_curve(hub, **curve_args) result.set(first=first, last=last, fixed_curves=fcs, ranged_curves=rcs, reference_curve=rc) hub.best, hub.unstacked = [], [] results.append(result) retries -= 1 return results