def active_members(request): terms_list = Term.objects.filter( Q(quarter='0') | Q(quarter='1') | Q(quarter='3')) if request.method == "POST": term_id = int(request.POST['term']) term = Term.objects.get(id=term_id) return render( request, 'active_members.html', { 'member_list': ActiveMember.objects.filter(term=term, profile__user__is_staff=False), 'staff_member_list': ActiveMember.objects.filter(term=term, profile__user__is_staff=True), 'dropdown_term': term, 'terms': terms_list }) aMembers = ActiveMember.current return render( request, 'active_members.html', { 'member_list': aMembers.filter(profile__user__is_staff=False).order_by('profile'), 'staff_member_list': aMembers.filter(profile__user__is_staff=True).order_by('profile'), 'dropdown_term': Settings.objects.term(), 'terms': terms_list })
def candidates(request): terms_list = Term.objects.filter(Q(quarter='1') | Q(quarter='3')) #NOTE: candidate.generate_req_report is being called on the template side, not here #This is because the entire list of candidate objects need to be passed anyway, #so we might as well not pass the generated report as well if request.method == "POST": term_id = int(request.POST['term']) term = Term.objects.get(id=term_id) return render(request, 'all_candidate_requirements.html', {'candidate_list': Candidate.objects.filter(term=term), 'dropdown_term' : term, 'terms': terms_list}) return render(request, 'all_candidate_requirements.html', {'candidate_list': Candidate.current.order_by('profile'), 'dropdown_term' : Settings.objects.term(), 'terms': terms_list})
def index(): """ :return: """ return render()
def view(environ, start_response): """ View comment all users. :param environ: :param start_response: :return: """ try: status, result = query_to_db(sql_show_info, out='all') except Exception as ex: result = '' html = """ <tr class="view__tbody_row"> <td class="view__tbody_cell hidden">{0}</td> <td class="view__tbody_cell">{1}</td> <td class="view__tbody_cell">{2}</td> <td class="view__tbody_cell view__tbody_delete"><a href="{3}" class="delete">удалить</a></td> """ html_table = [html.format(ru_encode(name), ru_encode(lastname), ru_encode(cmt), user_id, ) for name, lastname, cmt, user_id in result] mapping = { 'data': ''.join(html_table), } start_response('200 OK', [('Content-Type', 'text/html')]) return render('view.html', mapping)
def dbobj(typ, db, obj): if db not in appconf.con: connect_db(db) _rnd = 'd' + typ if typ == 'table': _ddl = appconf.con[db].schema.get_table(obj) elif typ == 'view': _ddl = appconf.con[db].schema.get_view(obj) elif typ == 'trigger': _ddl = appconf.con[db].schema.get_trigger(obj) elif typ == 'procedure': _ddl = appconf.con[db].schema.get_procedure(obj) elif typ == 'function': _ddl = appconf.con[db].schema.get_function(obj) elif typ == 'exception': _ddl = appconf.con[db].schema.get_exception(obj) elif typ == 'domain': _ddl = appconf.con[db].schema.get_domain(obj) elif typ == 'sequence': _ddl = appconf.con[db].schema.get_sequence(obj) elif typ == 'index': _ddl = appconf.con[db].schema.get_index(obj) elif typ == 'constraint': _ddl = appconf.con[db].schema.get_constraint(obj) elif typ == 'role': _ddl = appconf.con[db].schema.get_role(obj) return render(_rnd, db=db, tbl=_ddl, obj=obj, typ=typ)
def dobj_list(typ, db): if db not in appconf.con: connect_db(db) _rnd = 'd' + typ if typ == 'domains': _ddl = appconf.con[db].domains elif typ == 'indices': _ddl = appconf.con[db].indices elif typ == 'sequences': _ddl = appconf.con[db].sequences elif typ == 'constraints': _ddl = appconf.con[db].constraints elif typ == 'exceptions': _ddl = appconf.con[db].exceptions elif typ == 'tables': _ddl = appconf.con[db].tables elif typ == 'views': _ddl = appconf.con[db].views elif typ == 'procedures': _ddl = appconf.con[db].procedures elif typ == 'triggers': _ddl = appconf.con[db].triggers elif typ == 'roles': _ddl = appconf.con[db].roles return render(_rnd, db=db, tbl=_ddl, typ=typ)
def event(request, url): try: event = Event.objects.get(url=url) except ObjectDoesNotExist: raise Http404 return render(request, 'event_template.html', {'event': Event.objects.get(url=url)})
def manage_events(request): current_action = MANAGE_ACTIONS[0] if request.method == "POST": # current_action = int(request.POST['action']) create_event_form = CreateEventForm(request.POST) if(create_event_form.is_valid()): create_event_form.save() return render(request, 'manage_events.html', {'current_action' : current_action, 'actions' : MANAGE_ACTIONS}) else: create_event_form = CreateEventForm() return render(request, 'manage_events.html', {'current_action' : current_action, 'actions' : MANAGE_ACTIONS, 'create_event_form': create_event_form})
def houses(request): term = Settings.objects.term() house_points = [ HousePoints.objects.get_or_create(house=house, term=term)[0] for house in House.objects.all() ] return render(request, 'houses.html', {'houses': house_points})
def stat(environ, start_response): """ View info of region :param environ: :param start_response: :return: """ try: status, result = query_to_db(sql_show_statistic, out='all') except Exception as ex: result = '' html = """ <tr class="statistic__tbody_row"> <td class="statistic__tbody_cell"> <a class="statistic__link" href="{2}"> {0}</a> </td> <td class="statistic__tbody_cell"> {1}</td> """ html_table = [html.format(ru_encode(name), count, region_id, ) for name, count, region_id in result] mapping = { 'data': ''.join(html_table), } start_response('200 OK', [('Content-Type', 'text/html')]) return render('stat.html', mapping)
def add_requirement(request): successC = None successD = None if request.method=="POST": term = Settings.objects.term() req = Requirement.current.get(id=request.POST['requirement']) successC = "Added Requirement " + str(req) +" to Candidates: " successD = "Added Requirement " + str(req) +" to Distinguished Actives: " for cand_id in request.POST.getlist('candidate'): cand = Candidate.objects.get(id=cand_id) try: cand.event_requirements.add(req) except IntegrityError: continue successC += str(cand) + " " for da_id in request.POST.getlist('da'): da = ActiveMember.objects.get(id=da_id) try: da.event_requirements.add(req) except IntegrityError: continue successD += str(da) + " " return render(request, 'add_requirement.html', {'candidate_list': Candidate.current.order_by('profile'), 'da_list': ActiveMember.current.order_by('profile'), 'requirement_list': Requirement.current.all(), "successC": successC, "successD": successD})
def schedule(request): """ :param request: :return: """ term = Settings.objects.term() if Settings.objects.display_tutoring(): try: return render(request, 'schedule.html', {'schedule': 'cached_schedule_snippet.html', 'term': term}) except TemplateDoesNotExist: pass return render(request, 'schedule.html', {'schedule': 'schedule_snippet.html', 'term': term, 'classes': get_classes(), 'tutors': get_tutors(), 'display': request.user.is_staff or Settings.objects.display_tutoring()})
def render_profile_page(request, template, template_args=None): """ Helper function that looks up the links for the profile tabs :param request: The request object used to generate this response. :param template: The full name of a template to use or sequence of template names. :param template_args: Variables to pass to the template :returns: Rendered template """ if template_args is None: template_args = { } # if no template_args were passed, initialize to empty dictionary tabs = [ (reverse('main.views.profile_view'), 'Profile'), # tuples of the url for the view and the tab label (reverse('main.views.edit'), 'Edit Profile'), (reverse('main.views.add'), 'Modify Classes'), (reverse('main.views.requirements_view'), request.user.profile.get_position_display()) ] template_args[ 'profile_tabs'] = tabs # add the tab tuples to the variables to pass to the template return render(request, template, additional=template_args) # render the template
def register(request): if request.user.is_authenticated(): return redirect_next(request) error = Error() if request.method == "POST": current_password = request.POST.get('current_password') if current_password != Settings.objects.get_password(): error.incorrect_password = True username = request.POST.get('username') error.username_taken = User.objects.filter(username=username).count() new_password = request.POST.get('new_password') confirm_password = request.POST.get('confirm_password') if new_password != confirm_password: error.non_matching_password = True if not error.error(): User.objects.create_user(username, password=new_password) user = auth.authenticate(username=username, password=new_password) auth.login(request, user) return redirect(edit, from_redirect='redirect') return render(request, 'register.html', {'error': error})
def preferences(request): if not request.user.is_authenticated(): return redirect_next(request) term = Settings.objects.term() tutors = (tutoring.profile for tutoring in Tutoring.objects.filter(term=term)) return render(request, "preferences.html", {"tutors": tutors})
def add_requirement(request): successC = None successD = None if request.method == "POST": term = Settings.objects.term() req = Requirement.current.get(id=request.POST['requirement']) successC = "Added Requirement " + str(req) + " to Candidates: " successD = "Added Requirement " + str( req) + " to Distinguished Actives: " for cand_id in request.POST.getlist('candidate'): cand = Candidate.objects.get(id=cand_id) try: cand.event_requirements.add(req) except IntegrityError: continue successC += str(cand) + " " for da_id in request.POST.getlist('da'): da = ActiveMember.objects.get(id=da_id) try: da.event_requirements.add(req) except IntegrityError: continue successD += str(da) + " " return render( request, 'add_requirement.html', { 'candidate_list': Candidate.current.order_by('profile'), 'da_list': ActiveMember.current.order_by('profile'), 'requirement_list': Requirement.current.all(), "successC": successC, "successD": successD })
def events(request): today = datetime.today() return render(request, 'events.html', {'upcoming_events': [event for event in Event.objects.filter(end__gt=today).order_by('end') if event.event_type != Event.SOCIAL or request.user.is_authenticated()], 'past_events': [event for event in Event.objects.filter(end__lte=today, term=Settings.objects.term()).order_by('-end') if event.event_type != Event.SOCIAL or request.user.is_authenticated()]})
def active_members(request): terms_list = Term.objects.filter(Q(quarter='0') | Q(quarter='1') | Q(quarter='3')) if request.method == "POST": term_id = int(request.POST['term']) term = Term.objects.get(id=term_id) return render(request, 'active_members.html', {'member_list': ActiveMember.objects.filter(term=term, profile__user__is_staff=False), 'staff_member_list': ActiveMember.objects.filter(term=term, profile__user__is_staff=True), 'dropdown_term' : term, 'terms': terms_list}) aMembers = ActiveMember.current return render(request, 'active_members.html', {'member_list': aMembers.filter(profile__user__is_staff=False).order_by('profile'), 'staff_member_list': aMembers.filter(profile__user__is_staff=True).order_by('profile'), 'dropdown_term' : Settings.objects.term(), 'terms': terms_list})
def db_page(db): if db not in appconf.con: connect_db(db) s = request.environ['beaker.session'] s['db'] = db return render('db_page', db=db)
def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): auth.login(request, form.cleaned_data['user']) return redirect(request.GET.get('next', 'home')) else: form = LoginForm() return render(request, "login.html", {'form': form})
def account(request): if request.method == "POST": form = UserAccountForm(request.POST, instance=request.user) if form.is_valid(): if form.cleaned_data['new_password']: request.user.set_password(form.cleaned_data['new_password']) form.save() form = UserAccountForm(instance=request.user) return render(request, 'account.html', {'form': form})
def pending_community_service(request): if request.method == "POST": for id in request.POST: if request.POST[id] == 'on': Candidate.objects.filter(id=id).update(community_service=1) return render( request, 'pending_community_service.html', { 'candidates': [candidate for candidate in Candidate.objects.filter(term=Settings.objects.term, community_service=0).order_by('profile') if not candidate.community_service_complete() and candidate.community_service_proof] })
def candidates(request): terms_list = Term.objects.filter(Q(quarter='1') | Q(quarter='3')) #NOTE: candidate.generate_req_report is being called on the template side, not here #This is because the entire list of candidate objects need to be passed anyway, #so we might as well not pass the generated report as well if request.method == "POST": term_id = int(request.POST['term']) term = Term.objects.get(id=term_id) return render( request, 'all_candidate_requirements.html', { 'candidate_list': Candidate.objects.filter(term=term), 'dropdown_term': term, 'terms': terms_list }) return render( request, 'all_candidate_requirements.html', { 'candidate_list': Candidate.current.order_by('profile'), 'dropdown_term': Settings.objects.term(), 'terms': terms_list })
def scribe_candidate_2015(request): if request.method == "POST": erid = int(request.POST["erid"]) er = models.ElectionResults.objects.get(pk=erid) er.did_scribe = True er.save() age = int(request.POST["age"]) occupation = request.POST["occupation"] affiliation = request.POST["affiliation"] gender = request.POST["gender"] fp = open(project.settings.BASE_DIR + SCRIBE_2015_PATH, "a") writer = csv.writer(fp) row = [er.constituency.label, str(er.candidate_number), str(age), occupation, affiliation, gender] writer.writerow([it.encode("utf-8") for it in row]) return common.HttpResponseRedirect(request.path) election = models.Election.objects.filter(code_name="dc2015").get() er = ( models.ElectionResults.objects.filter(constituency__election=election) .filter(did_scribe=False) .order_by("constituency__label")[0] ) occupations = set() affiliations = set() current_data = None with open(project.settings.BASE_DIR + SCRIBE_2015_PATH, "r") as fp: reader = csv.reader(fp) for row in reader: constituency_label, candidate_number, age, occupation, affiliation, gender = row age = int(age) occupation = occupation.decode("utf-8") affiliation = affiliation.decode("utf-8") affiliations.add(affiliation) occupations.add(occupation) if constituency_label == er.constituency.label and int(candidate_number) == er.candidate_number: current_data = [constituency_label, age, occupation, affiliation] return common.render( request, "scribe.html", { "election": election, "er": er, "occupations": json.dumps(list(occupations)), "affiliations": json.dumps(list(affiliations)), "current_data": current_data, }, )
def all_profiles(request): # data = '\n'.join(['First Name,Middle Name,Last Name,Email,Nickname,Gender,Birthday,Phone Number,Major,' # 'Initiation Term,Graduation Term'] + # [profile.dump() for profile in Profile.objects.all() if profile.user.id != 1]) # response = HttpResponse(data, content_type='text/csv') # response['Content-Disposition'] = 'attachment; filename=spreadsheet.csv' # return response prof_list_initial = Profile.objects.order_by("user__last_name") profile_list = [] for prof in prof_list_initial: if prof.user.last_name: profile_list.append(prof) return render(request, 'user_info_dump.html', {'profile_list': profile_list})
def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): username, new_password = map(form.cleaned_data.get, ('username', 'new_password')) user = User.objects.create_user(username, password=new_password) auth.login(request, auth.authenticate(username=username, password=new_password)) profile = Profile.objects.create(user=user) Candidate.objects.create(profile=profile, term=Settings.objects.term()) return redirect(edit) else: form = RegisterForm() return render(request, 'register.html', {'form': form})
def show_words_for(user, fb_id): word_list = memcache.get("word_list_" + fb_id + "-" + user.fb_id) if not word_list: url_re = """((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?""" word_list = [] for msg in Message.all().filter("conversation_partner_id =", fb_id): for word in msg.content.split(" "): if not re.match(url_re, word): word_list.append(word) memcache.put("word_list_" + fb_id + "-" + user.fb_id, word_list) return render('show.html', entries=word_list, user_name=user.name)
def db_drop(): if 'db' in request.GET: db = request.GET.db if db not in appconf.con: connect_db(db) appconf.con[db].drop_database() appconf.con.pop(db, None) appconf.ddl.pop(db, None) appconf.db_config.pop(db, None) redirect('/db/list') else: return render(tpl='db_drop')
def db_create(): if request.method == 'GET': _reg = { 'db_alias': '', 'db_server': '', 'db_path': '', 'db_user': '', 'db_pass': '', 'db_role': '', 'dialect': '', 'charset': '' } return render(tpl='db_register', reg=_reg, ftyp='create') else: prms = request.POST if prms['db_path'] in ['BASE_PATH', '', '.', './']: prms['db_path'] = appconf.basepath sql = """ create database '{db_server}:{db_path}/{db_name}' user '{db_user}' password '{db_pass}' page_size {db_page_size} DEFAULT CHARACTER SET {charset}""".format(**prms) appconf.con[prms.db_alias] = fdb.create_database( sql=sql, connection_class=fdb.ConnectionWithSchema, ) register_ddl(prms.db_alias) appconf.db_config[prms.db_alias] = { 'db_server': prms.db_server, 'db_path': prms.db_path + '/' + prms.db_name, 'db_user': prms.db_user, 'db_pass': prms.db_pass, 'db_role': prms.db_role, 'dialect': 3, #todo! prms.dialect, 'charset': prms.charset } with open('%s/dbconfig.ini' % appconf.basepath, 'w+', encoding='utf-8') as f: appconf.db_config.write(f) redirect('/db/list')
def profile_view(request): if not request.user.is_authenticated(): return redirect_next(request) user = request.user profile, created = Profile.objects.get_or_create(user=user) if not all([user.email, user.first_name, user.last_name, profile.graduation_term and profile.graduation_term.year]): return redirect(edit, from_redirect='redirect') if profile.position == profile.CANDIDATE: details = ((name, 'Completed' if requirement else 'Not Completed') for name, requirement in Candidate.objects.filter(profile=profile)[0].requirements()) else: details = ((active.term, 'Completed' if active.completed else 'In Progress') for active in ActiveMember.objects.filter(profile=profile)) return render(request, 'profile.html', {'user': user, 'profile': profile, 'details': details})
def pending_community_service(request): if request.method == "POST": for id in request.POST: if request.POST[id] == 'on': Candidate.objects.filter(id=id).update(community_service=1) return render( request, 'pending_community_service.html', { 'candidates': [ candidate for candidate in Candidate.objects.filter( term=Settings.objects.term, community_service=0).order_by( 'profile') if not candidate.community_service_complete() and candidate.community_service_proof ] })
def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): username, new_password = map(form.cleaned_data.get, ('username', 'new_password')) user = User.objects.create_user(username, password=new_password) auth.login( request, auth.authenticate(username=username, password=new_password)) profile = Profile.objects.create(user=user) Candidate.objects.create(profile=profile, term=Settings.objects.term()) return redirect(edit) else: form = RegisterForm() return render(request, 'register.html', {'form': form})
def faculty(request): faculty = Faculty.objects.all() facultyByDept = {} for f in faculty: facultyByDept.setdefault(str(f.get_dept_display()), []).append( (f.name, f.chapter, f.graduation, f.link)) facultyByDept['Advisors'] = [ ('William R. Goodin', 'CA E', "'75 (Chief Advisor)", ''), ('Stacey Ross', 'CA K', "'06 (District 16 Director)", ''), ('Neal Bussett', 'CA X', "'09 (District 16 Director)", ''), ('Jason Corl', 'CA Q', "'06 (District 16 Director)", ''), ('Scott Eckersall', 'CA I', "'96 (District 16 Director)", '') ] facultyByDept = [(dept, facultyByDept[dept]) for dept in sorted(facultyByDept)] return render(request, 'faculty.html', { 'faculty' : facultyByDept, 'facultyAdvisor' : 'Ann R. Karagozian' })
def officers(request): positionRe = re.compile( r'Club Liaison (\([^)]*\))' ) positions = [] liaisons = [] for position in Officer.objects.all(): match = positionRe.match( position.position ) if match: for officer in position.profile.all(): liaisons.append(' '.join([str(officer), match.group(1)])) else: positions.append( ( position.position, [ str( officer ) for officer in position.profile.all() ] ) ) positions.append( ( 'Faculty Advisor', [ 'Bill Goodin' ] ) ) positions.append( ( 'Club Liaison', liaisons ) ) return render(request, 'officers.html', { 'term' : 'Summer - Fall 2013', 'positions' : positions } )
def render_profile_page(request, template, template_args=None): """ Helper function that looks up the links for the profile tabs :param request: The request object used to generate this response. :param template: The full name of a template to use or sequence of template names. :param template_args: Variables to pass to the template :returns: Rendered template """ if template_args is None: template_args = {} # if no template_args were passed, initialize to empty dictionary tabs = [(reverse('main.views.profile_view'), 'Profile'), # tuples of the url for the view and the tab label (reverse('main.views.edit'), 'Edit Profile'), (reverse('main.views.add'), 'Modify Classes'), (reverse('main.views.requirements_view'), request.user.profile.get_position_display())] template_args['profile_tabs'] = tabs # add the tab tuples to the variables to pass to the template return render(request, template, additional=template_args) # render the template
def classes(request): """ :param request: :return: """ term = Settings.objects.term() tutors = [] for hour, hour_name in TUTORING_HOUR_CHOICES: tutors_for_hour = [] tutoring_objs = [t for t in Tutoring.current.all()] + [t for t in ForeignTutoring.current.all()] for day, day_name in TUTORING_DAY_CHOICES: tutors_for_hour.append( sorted(t for t in tutoring_objs if (t.hour_1 == hour and t.day_1 == day) or (t.hour_2 == hour and t.day_2 == day)) + sorted(itertools.chain.from_iterable(t.profile.classes.all() for t in tutoring_objs if (t.hour_1 == hour and t.day_1 == day) or (t.hour_2 == hour and t.day_2 == day)))) tutors.append((hour_name, tutors_for_hour)) return render(request, 'classes.html', {'term': term, 'tutors': tutors})
def db_register(): if request.method == 'GET': _reg = { 'db_server': '', 'db_path': '', 'db_user': '', 'db_pass': '', 'db_role': '', 'dialect': '', 'charset': '' } if 'db' in request.GET: _db = formval_to_utf8(request.GET['db']) for k in _reg: _reg[k] = appconf.db_config[_db][k] _reg['db_alias'] = _db else: _reg['db_alias'] = '' return render(tpl='db_register', reg=_reg) else: prms = request.POST if prms.old_alias: appconf.db_config.pop(prms.old_alias, None) appconf.db_config[prms.db_alias] = { 'db_server': prms.db_server, 'db_path': prms.db_path, 'db_user': prms.db_user, 'db_pass': prms.db_pass, 'db_role': prms.db_role, 'dialect': prms.dialect, 'charset': prms.charset } with open('%s/dbconfig.ini' % appconf.basepath, 'w+', encoding='utf-8') as f: appconf.db_config.write(f) redirect('/db/list')
def expanded_schedule(request): """ :param request: :return: """ term = Settings.objects.term() tutors = [] for hour, hour_name in TUTORING_HOUR_CHOICES: tutors_for_hour = [] for day, day_name in TUTORING_DAY_CHOICES: if Settings.objects.display_tutoring() or (request.user.is_authenticated and request.user.is_staff): tutors_for_hour.append(['{} {}'.format(1, tutor) for tutor in Tutoring.current.filter(best_hour=hour, best_day=day)] + ['{} {}'.format(1, tutor) for tutor in Tutoring.current.filter(best_hour=str(int(hour)-1), best_day=day)] + ['{} {}'.format(2, tutor) for tutor in Tutoring.current.filter(second_best_hour=hour, second_best_day=day)] + ['{} {}'.format(2, tutor) for tutor in Tutoring.current.filter(second_best_hour=str(int(hour)-1), second_best_day=day)] + ['{} {}'.format(3, tutor) for tutor in Tutoring.current.filter(third_best_hour=hour, third_best_day=day)] + ['{} {}'.format(3, tutor) for tutor in Tutoring.current.filter(third_best_hour=str(int(hour)-1), third_best_day=day)]) else: tutors_for_hour.append(None) tutors.append((hour_name, tutors_for_hour)) classes = [] for department, number in zip(Class.DEPT_CHOICES, numbers): department, _ = department courses = [(cls.course_number, cls.department+cls.course_number) for cls in sorted((c for c in Class.objects.filter(department=department, display=True) if any(filter(Profile.current, c.profile_set.all()))), key=lambda c: tuple(int(s) if s.isdigit() else s for s in re.search(r'(\d+)([ABCD]?L?)?', c.course_number).groups()))] if courses: classes.append((department, courses, 'collapse{}'.format(number))) return render(request, 'schedule.html', {'term': term, 'classes': classes, 'tutors': tutors, 'display': request.user.is_staff or Settings.objects.display_tutoring()})
for quality_score in range(0, CLASS_COUNT + 1): # Save class specific data class_data[quality_score] = data[np.where(data[:, -1] == quality_score)] # Drop off last column (class label) class_data[quality_score] = class_data[quality_score][:, :-1] # Normalize if len(class_data[quality_score]) > 0: class_data[quality_score] = normalize(class_data[quality_score], axis=0, norm='max') print( f'samples for class {quality_score}: {len(class_data[quality_score])}' ) return class_data class_data = read_data('winequality-red.csv') render(class_data) priors, gaussians, cov = create_distributions(class_data) render_pca(class_data, cov) labeled_data, classifications = classify(class_data, gaussians, priors) assess_classification(class_data, labeled_data, classifications, priors)
import numpy as np import sys import time import pickle start_time = time.time() graph_name = "zbug" g = gt.Graph(directed=False) v1 = g.add_vertex() v2 = g.add_vertex() e = g.add_edge(v1, v2) idx = [0, 1] pos = common.layout(g) pos_data = pos.get_2d_array(idx) print(pos_data) #pos_data[1][1] = 0.5 # [yaxis][node1] pos_data[0][0] = 0.5 # [yaxis][node1] pos.set_2d_array(pos_data, idx) pos_data = pos.get_2d_array(idx) print(pos_data) pos = common.render(g, None, None, graph_name, pos, vertex_text=g.vertex_index, vertex_font_size=18)
def feedback(request): return render(request, 'tutoring_feedback.html')
longest=True, fillvalue=False))[:-1] result_state = SortedDict() for i, surrounding_points in zip(state.keys(), state_with_surrounding_points): if surrounding_points in change_rules: result_state[i] = change_rules[surrounding_points] else: result_state[i] = False return result_state if __name__ == "__main__": with open('input.txt') as pot_info: pot_info = filter(None, map(lambda s: s.strip(), pot_info.readlines())) initial_state, change_rules = parse_point_info(list(pot_info)) state = initial_state for i in range(20): state = tick(state, change_rules) print(f"{i}:", end=' ') render(state) print("Final:", end=' ') render(state) print(sum(itertools.compress(state.keys(), state.values())))
def downloads(request): return render(request, 'downloads.html')
print(pos_array) print(pos_array[0]) print(pos_array[1]) print(np.amax(pos_array[0]), np.amin(pos_array[0])) print(np.amax(pos_array[1]), np.amin(pos_array[1])) fit_view = (0, 1, 90, 120) # 1.0 #True # (0, 0, 8, 8) nprop = u.vertex_properties[nprop_viz] eprop = u.edge_properties[eprop_viz] print(u) common.histo([(nprop_viz, nprop), (eprop_viz, eprop)], graph_name + "_norm_view0") pos = common.render(u, eprop, nprop, graph_name + "view0", pos, 5, fit_view=fit_view) sys.exit() poromax = np.amax(nprop.ma) cutoff = 0.8 poromin_filter = poromax * cutoff u = common.view(u, vfilter=lambda e: nprop[e] > poromin_filter) nprop = u.vertex_properties[nprop_viz] eprop = u.edge_properties[eprop_viz] print(u) common.histo([(nprop_viz, nprop), (eprop_viz, eprop)], graph_name + "_norm_view1")
def index(request): content = render('schedulers/schedulers.html', '') return output(content)
def event(request, url): get_object_or_404(Event, url=url) return render(request, 'event_template.html', {'event': Event.objects.get(url=url)})
def tutoring_logging(request): """ :param request: :return: """ c_term = Settings.objects.term() tutoring = None error = None isTutoring = False hours = 0 classes = None confirm = False last_logged_in = None sign_out_time = None # tutoring = get_object_or_404(Tutoring, profile=request.user.profile, term=c_term) try: tutoring = Tutoring.objects.get(profile=request.user.profile, term=c_term) except Tutoring.DoesNotExist: # Quick patch to make the error nice while we add allowance of weeks 1 and 2. # TODO: Find out what the true problem is for this user. It can be any of: # 1. Week < 3 # 2. Non-candidate (no peer teaching at all) # 3. Candidate who chose Academic Outreach # The error should be a diagnostic on one of these issues. error = "We apologize, but you cannot log your tutoring hours at this time. Please try again tomorrow." if tutoring: isTutoring = tutoring.is_tutoring td = (datetime.datetime.now() - tutoring.last_start).seconds hours = td // 3600 if (td // 60) % 60 >= 45: hours += 1 display_signout_screen = True if request.method == "POST": if 'sign_in' in request.POST and not isTutoring: display_signout_screen = False tutoring.is_tutoring = True isTutoring = True tutoring.last_start = datetime.datetime.now() hours = 0 classes = Class.objects.filter(display=True) confirm = True elif 'sign_out' in request.POST: display_signout_screen = False last_logged_in = tutoring.last_start sign_out_time = datetime.datetime.now() h = hours tutees = int(request.POST['tutees']) makeup_t = int(request.POST['makeup_tutoring']) makeup_e = int(request.POST['makeup_event']) class_ids = request.POST.getlist('subjects') if (makeup_t + makeup_e) > hours: error = ('Hmm please check your math. According to our records, you have tutored approximately {} ' 'hours this session (we round up after 45 minutes), but you have indicated {} makeup hours.'.format(str(hours), str(makeup_t + makeup_e))) display_signout_screen = True else: tutoring.is_tutoring = False isTutoring = False week = c_term.get_week() if makeup_e > 0: h -= makeup_e # hours not logged! send_mail('Make up Tutoring Hours!', 'Hi! {} indicated they tutored {} hours to make up for an event. Please check this out!'.format(tutoring.profile, makeup_e), '*****@*****.**', ['*****@*****.**'], fail_silently=True) if makeup_t > 0: for i in range(3, week): week_obj = getattr(tutoring, 'week_'+str(i)) while (not week_obj.complete()) and makeup_t > 0: week_obj.hours += 1 h -= 1 makeup_t -= 1 week_obj.no_makeup = False week_obj.save() cur_week = getattr(tutoring, 'week_'+str(week)) cur_week.hours += h cur_week.tutees += tutees cur_week.save() for s in class_ids: s = int(s) cur_week.classes.add(Class.objects.get(id=s)) confirm = True else: if tutoring.is_tutoring and tutoring.last_start.date() != datetime.datetime.now().date(): # midnight passed :P display_signout_screen = False error = 'You forgot to sign out of your last tutoring session. Please contact the tutoring chair at [email protected] to have those hours logged' tutoring.is_tutoring = False if display_signout_screen: classes = Class.objects.filter(display=True) tutoring.save() return render(request, 'tutoring_logging.html', {'error': error, 'isTutoring': isTutoring, 'hours': hours, 'classes': classes, 'confirm': confirm, 'last_logged_in': last_logged_in, 'sign_out_time': sign_out_time})
def tutoring_hours(request): return render(request, 'tutoring_hours.html', {'tutoring_list': Tutoring.current.order_by('profile')})
...................... ...................... ...................... ............#......... ........##...#.#...... ......#.....#..#...... .....#..##.##.#....... .......##.#....#...... ...........#....#..... ..............#....... ....#......#...#...... .....#.....##......... ...............#...... ...............#...... ...................... ...................... After 3 seconds, the message appeared briefly: HI. Of course, your message will be much longer and will take many more seconds to appear. What message will eventually appear in the sky? """ from common import parse_point_info_str, find_coherent_message, render if __name__ == "__main__": with open('input.txt') as point_info_str_list: point_info_list = list(map(parse_point_info_str, point_info_str_list)) _, message_points = find_coherent_message(point_info_list) render(message_points)