code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
question_votes = votes = Answer.objects.filter(question=q) users = q.get_users_voted() num_users_votes = {u.id: votes.filter(user=u).count() for u in users} user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users} choices = [] for c in q.choice_set.all().order_by("num"): votes = question_votes.filter(choice=c) vote_users = set([v.user for v in votes]) choice = { "choice": c, "votes": { "total": { "all": len(vote_users), "all_percent": perc(len(vote_users), users.count()), "male": fmt(sum([v.user.is_male * user_scale[v.user.id] for v in votes])), "female": fmt(sum([v.user.is_female * user_scale[v.user.id] for v in votes])) } }, "users": [v.user for v in votes] } for yr in range(9, 14): yr_votes = [v.user if v.user.grade and v.user.grade.number == yr else None for v in votes] yr_votes = list(filter(None, yr_votes)) choice["votes"][yr] = { "all": len(set(yr_votes)), "male": fmt(sum([u.is_male * user_scale[u.id] for u in yr_votes])), "female": fmt(sum([u.is_female * user_scale[u.id] for u in yr_votes])), } choices.append(choice) votes = question_votes.filter(clear_vote=True) clr_users = set([v.user for v in votes]) choice = { "choice": "Clear vote", "votes": { "total": { "all": len(clr_users), "all_percent": perc(len(clr_users), users.count()), "male": fmt(sum([v.user.is_male * user_scale[v.user.id] for v in votes])), "female": fmt(sum([v.user.is_female * user_scale[v.user.id] for v in votes])) } }, "users": clr_users } for yr in range(9, 14): yr_votes = [v.user if v.user.grade and v.user.grade.number == yr else None for v in votes] yr_votes = list(filter(None, yr_votes)) choice["votes"][yr] = { "all": len(yr_votes), "male": fmt(sum([u.is_male * user_scale[u.id] for u in yr_votes])), "female": fmt(sum([u.is_female * user_scale[u.id] for u in yr_votes])) } choices.append(choice) choice = { "choice": "Total", "votes": { "total": { "all": users.count(), "votes_all": question_votes.count(), "all_percent": perc(users.count(), users.count()), "male": users.filter(gender=True).count(), "female": users.filter(gender__isnull=False, gender=False).count() } } } for yr in range(9, 14): yr_votes = [u if u.grade and u.grade.number == yr else None for u in users] yr_votes = list(filter(None, yr_votes)) choice["votes"][yr] = { "all": len(set(yr_votes)), "male": fmt(sum([u.is_male * user_scale[u.id] for u in yr_votes])), "female": fmt(sum([u.is_female * user_scale[u.id] for u in yr_votes])) } choices.append(choice) return {"question": q, "choices": choices, "user_scale": user_scale}
def handle_sap(q)
Clear vote
1.732995
1.714475
1.010802
is_events_admin = request.user.has_admin_permission('events') if request.method == "POST": if "approve" in request.POST and is_events_admin: event_id = request.POST.get('approve') event = get_object_or_404(Event, id=event_id) event.rejected = False event.approved = True event.approved_by = request.user event.save() messages.success(request, "Approved event {}".format(event)) if "reject" in request.POST and is_events_admin: event_id = request.POST.get('reject') event = get_object_or_404(Event, id=event_id) event.approved = False event.rejected = True event.rejected_by = request.user event.save() messages.success(request, "Rejected event {}".format(event)) if is_events_admin and "show_all" in request.GET: viewable_events = (Event.objects.all().this_year().prefetch_related("groups")) else: viewable_events = (Event.objects.visible_to_user(request.user).this_year().prefetch_related("groups")) # get date objects for week and month today = datetime.date.today() delta = today - datetime.timedelta(days=today.weekday()) this_week = (delta, delta + datetime.timedelta(days=7)) this_month = (this_week[1], this_week[1] + datetime.timedelta(days=31)) events_categories = [{ "title": "This week", "events": viewable_events.filter(time__gte=this_week[0], time__lt=this_week[1]) }, { "title": "This month", "events": viewable_events.filter(time__gte=this_month[0], time__lt=this_month[1]) }, { "title": "Future", "events": viewable_events.filter(time__gte=this_month[1]) }] if is_events_admin: unapproved_events = (Event.objects.filter(approved=False, rejected=False).prefetch_related("groups")) events_categories = [{"title": "Awaiting Approval", "events": unapproved_events}] + events_categories if is_events_admin and "show_all" in request.GET: events_categories.append({"title": "Past", "events": viewable_events.filter(time__lt=this_week[0])}) context = { "events": events_categories, "num_events": sum([x["events"].count() for x in events_categories]), "is_events_admin": is_events_admin, "events_admin": is_events_admin, "show_attend": True, "show_icon": True } return render(request, "events/home.html", context)
def events_view(request)
Events homepage. Shows a list of events occurring in the next week, month, and future.
1.983023
1.957136
1.013227
event = get_object_or_404(Event, id=id) if request.method == "POST": if not event.show_attending: return redirect("events") if "attending" in request.POST: attending = request.POST.get("attending") attending = (attending == "true") if attending: event.attending.add(request.user) else: event.attending.remove(request.user) return redirect("events") context = {"event": event, "is_events_admin": request.user.has_admin_permission('events')} return render(request, "events/join_event.html", context)
def join_event_view(request, id)
Join event page. If a POST request, actually add or remove the attendance of the current user. Otherwise, display a page with confirmation. id: event id
2.337017
2.397372
0.974824
event = get_object_or_404(Event, id=id) full_roster = list(event.attending.all()) viewable_roster = [] num_hidden_members = 0 for p in full_roster: if p.can_view_eighth: viewable_roster.append(p) else: num_hidden_members += 1 context = { "event": event, "viewable_roster": viewable_roster, "full_roster": full_roster, "num_hidden_members": num_hidden_members, "is_events_admin": request.user.has_admin_permission('events'), } return render(request, "events/roster.html", context)
def event_roster_view(request, id)
Show the event roster. Users with hidden eighth period permissions will not be displayed. Users will be able to view all other users, along with a count of the number of hidden users. (Same as 8th roster page.) Admins will see a full roster at the bottom. id: event id
2.410322
2.231744
1.080017
is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: return redirect("request_event") if request.method == "POST": form = EventForm(data=request.POST, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = safe_html(obj.description) # auto-approve if admin obj.approved = True obj.approved_by = request.user messages.success(request, "Because you are an administrator, this event was auto-approved.") obj.created_hook(request) obj.save() return redirect("events") else: messages.error(request, "Error adding event.") else: form = EventForm(all_groups=request.user.has_admin_permission('groups')) context = {"form": form, "action": "add", "action_title": "Add" if is_events_admin else "Submit", "is_events_admin": is_events_admin} return render(request, "events/add_modify.html", context)
def add_event_view(request)
Add event page. Currently, there is an approval process for events. If a user is an events administrator, they can create events directly. Otherwise, their event is added in the system but must be approved.
3.269598
3.119518
1.04811
event = get_object_or_404(Event, id=id) is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: raise exceptions.PermissionDenied if request.method == "POST": if is_events_admin: form = AdminEventForm(data=request.POST, instance=event, all_groups=request.user.has_admin_permission('groups')) else: form = EventForm(data=request.POST, instance=event, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_valid(): obj = form.save() # SAFE HTML obj.description = safe_html(obj.description) obj.save() messages.success(request, "Successfully modified event.") # return redirect("events") else: messages.error(request, "Error modifying event.") else: if is_events_admin: form = AdminEventForm(instance=event, all_groups=request.user.has_admin_permission('groups')) else: form = EventForm(instance=event, all_groups=request.user.has_admin_permission('groups')) context = {"form": form, "action": "modify", "action_title": "Modify", "id": id, "is_events_admin": is_events_admin} return render(request, "events/add_modify.html", context)
def modify_event_view(request, id=None)
Modify event page. You may only modify an event if you were the creator or you are an administrator. id: event id
2.057407
2.078239
0.989976
event = get_object_or_404(Event, id=id) if not request.user.has_admin_permission('events'): raise exceptions.PermissionDenied if request.method == "POST": try: event.delete() messages.success(request, "Successfully deleted event.") except Event.DoesNotExist: pass return redirect("events") else: return render(request, "events/delete.html", {"event": event})
def delete_event_view(request, id)
Delete event page. You may only delete an event if you were the creator or you are an administrator. Confirmation page if not POST. id: event id
2.276001
2.459116
0.925536
if request.method == "POST": event_id = request.POST.get("event_id") if event_id: event = Event.objects.get(id=event_id) event.user_map.users_hidden.remove(request.user) event.user_map.save() return http.HttpResponse("Unhidden") raise http.Http404 else: return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED")
def show_event_view(request)
Unhide an event that was hidden by the logged-in user. events_hidden in the user model is the related_name for "users_hidden" in the EventUserMap model.
3.027049
2.441753
1.239703
logger.debug(request.POST) if request.method == "POST": if "user_token" in request.POST and "gcm_token" in request.POST: user_token = request.POST.get("user_token") gcm_token = request.POST.get("gcm_token") logger.debug(user_token) logger.debug(gcm_token) try: ncfg = NotificationConfig.objects.get(android_gcm_rand=user_token) except NotificationConfig.DoesNotExist: logger.debug("No pair") return HttpResponse('{"error":"Invalid data."}', content_type="text/json") ncfg.gcm_token = gcm_token ncfg.android_gcm_rand = None ncfg.android_gcm_date = None ncfg.save() return HttpResponse('{"success":"Now registered."}', content_type="text/json") return HttpResponse('{"error":"Invalid arguments."}', content_type="text/json")
def android_setup_view(request)
Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Android app is detected through the user agent. If it has the same value, it is assumed to be correct.
2.594064
2.42951
1.067732
data = {} if request.user.is_authenticated: # authenticated session notifs = GCMNotification.objects.filter(sent_to__user=request.user).order_by("-time") if notifs.count() > 0: notif = notifs.first() ndata = notif.data if "title" in ndata and "text" in ndata: data = { "title": ndata['title'] if 'title' in ndata else '', "text": ndata['text'] if 'text' in ndata else '', "url": ndata['url'] if 'url' in ndata else '' } else: schedule_chk = chrome_getdata_check(request) if schedule_chk: data = schedule_chk else: schedule_chk = chrome_getdata_check(request) if schedule_chk: data = schedule_chk else: return HttpResponse("null", content_type="text/json") else: schedule_chk = chrome_getdata_check(request) if schedule_chk: data = schedule_chk else: data = {"title": "Check Intranet", "text": "You have a new notification that couldn't be loaded right now."} j = json.dumps(data) return HttpResponse(j, content_type="text/json")
def chrome_getdata_view(request)
Get the data of the last notification sent to the current user. This is needed because Chrome, as of version 44, doesn't support sending a data payload to a notification. Thus, information on what the notification is actually for must be manually fetched.
2.596908
2.502352
1.037787
logger.debug(request.POST) token = None if request.method == "POST": if "token" in request.POST: token = request.POST.get("token") if not token: return HttpResponse('{"error":"Invalid data."}', content_type="text/json") ncfg, _ = NotificationConfig.objects.get_or_create(user=request.user) ncfg.gcm_token = token ncfg.save() return HttpResponse('{"success":"Now registered."}', content_type="text/json")
def chrome_setup_view(request)
Set up a browser-side GCM session. This *requires* a valid login session. A "token" POST parameter is saved under the "gcm_token" parameter in the logged in user's NotificationConfig.
3.161468
2.460306
1.28499
if request.method == "POST": form = LostItemForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = safe_html(obj.description) obj.save() messages.success(request, "Successfully added lost item.") return redirect("lostitem_view", obj.id) else: messages.error(request, "Error adding lost item.") else: form = LostItemForm() return render(request, "lostfound/lostitem_form.html", {"form": form, "action": "add"})
def lostitem_add_view(request)
Add a lostitem.
2.288805
2.259739
1.012863
if request.method == "POST": lostitem = get_object_or_404(LostItem, id=item_id) form = LostItemForm(request.POST, instance=lostitem) if form.is_valid(): obj = form.save() logger.debug(form.cleaned_data) # SAFE HTML obj.description = safe_html(obj.description) obj.save() messages.success(request, "Successfully modified lost item.") return redirect("lostitem_view", obj.id) else: messages.error(request, "Error adding lost item.") else: lostitem = get_object_or_404(LostItem, id=item_id) form = LostItemForm(instance=lostitem) context = {"form": form, "action": "modify", "id": item_id, "lostitem": lostitem} return render(request, "lostfound/lostitem_form.html", context)
def lostitem_modify_view(request, item_id=None)
Modify a lostitem. id: lostitem id
1.963871
1.995928
0.983939
if request.method == "POST": try: a = LostItem.objects.get(id=item_id) if request.POST.get("full_delete", False): a.delete() messages.success(request, "Successfully deleted lost item.") else: a.found = True a.save() messages.success(request, "Successfully marked lost item as found!") except LostItem.DoesNotExist: pass return redirect("index") else: lostitem = get_object_or_404(LostItem, id=item_id) return render(request, "lostfound/lostitem_delete.html", {"lostitem": lostitem})
def lostitem_delete_view(request, item_id)
Delete a lostitem. id: lostitem id
2.157551
2.18892
0.985669
lostitem = get_object_or_404(LostItem, id=item_id) return render(request, "itemreg/item_view.html", {"item": lostitem, "type": "lost"})
def lostitem_view(request, item_id)
View a lostitem. id: lostitem id
2.702386
3.174525
0.851273
if request.method == "POST": founditem = get_object_or_404(FoundItem, id=item_id) form = FoundItemForm(request.POST, instance=founditem) if form.is_valid(): obj = form.save() logger.debug(form.cleaned_data) # SAFE HTML obj.description = safe_html(obj.description) obj.save() messages.success(request, "Successfully modified found item.") return redirect("founditem_view", obj.id) else: messages.error(request, "Error adding found item.") else: founditem = get_object_or_404(FoundItem, id=item_id) form = FoundItemForm(instance=founditem) context = {"form": form, "action": "modify", "id": item_id, "founditem": founditem} return render(request, "lostfound/founditem_form.html", context)
def founditem_modify_view(request, item_id=None)
Modify a founditem. id: founditem id
1.959637
2.006909
0.976446
if request.method == "POST": try: a = FoundItem.objects.get(id=item_id) if request.POST.get("full_delete", False): a.delete() messages.success(request, "Successfully deleted found item.") else: a.found = True a.save() messages.success(request, "Successfully marked found item as found!") except FoundItem.DoesNotExist: pass return redirect("index") else: founditem = get_object_or_404(FoundItem, id=item_id) return render(request, "lostfound/founditem_delete.html", {"founditem": founditem})
def founditem_delete_view(request, item_id)
Delete a founditem. id: founditem id
2.207007
2.289917
0.963794
founditem = get_object_or_404(FoundItem, id=item_id) return render(request, "itemreg/item_view.html", {"item": founditem, "type": "found"})
def founditem_view(request, item_id)
View a founditem. id: founditem id
2.83258
3.508887
0.807259
hosts = Host.objects.visible_to_user(request.user) context = {"hosts": hosts} return render(request, "files/home.html", context)
def files_view(request)
The main filecenter view.
4.199695
3.662592
1.146646
if "password" in request.POST: key = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(key, AES.MODE_CFB, iv) message = request.POST.get("password") if isinstance(message, str): message = message.encode("utf-8") ciphertext = obj.encrypt(message) request.session["files_iv"] = base64.b64encode(iv).decode() request.session["files_text"] = base64.b64encode(ciphertext).decode() cookie_key = base64.b64encode(key).decode() nexturl = request.GET.get("next", None) if nexturl and nexturl.startswith("/files"): response = redirect(nexturl) else: response = redirect("files") response.set_cookie(key="files_key", value=cookie_key) if "username" in request.POST: request.session["filecenter_username"] = request.POST.get("username") return response else: return render(request, "files/auth.html", {"is_admin": request.user.member_of("admin_all")})
def files_auth(request)
Display authentication for filecenter.
2.61958
2.536651
1.032692
if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)): return False iv = base64.b64decode(request.session["files_iv"]) text = base64.b64decode(request.session["files_text"]) key = base64.b64decode(request.COOKIES["files_key"]) obj = AES.new(key, AES.MODE_CFB, iv) password = obj.decrypt(text) username = request.session["filecenter_username"] if "filecenter_username" in request.session else request.user.username return {"username": username, "password": password}
def get_authinfo(request)
Get authentication info from the encrypted message.
2.501704
2.487164
1.005846
if user and user.grade: grade = int(user.grade) else: return host_dir if grade in range(9, 13): win_path = "/{}/".format(user.username) else: win_path = "" return host_dir.replace("{win}", win_path)
def windows_dir_format(host_dir, user)
Format a string for the location of the user's folder on the Windows (TJ03) fileserver.
4.832685
4.530689
1.066656
print('------------------------------') try: str2 = str2[0] except IndexError: str2 = None if str1 and str2: return str1.replace(str2, "<b>{}</b>".format(str2)) else: return str1
def highlight(str1, str2)
Highlight str1 with the contents of str2.
3.287098
3.30314
0.995143
with open('eighth_absentees.csv', 'r') as absopen: absences = csv.reader(absopen) for row in absences: bid, uid = row try: usr = User.objects.get(id=uid) except User.DoesNotExist: self.stdout.write("User {} doesn't exist, bid {}".format(usr, bid)) else: try: blk = EighthBlock.objects.get(id=bid) except EighthBlock.DoesNotExist: self.stdout.write("Block {} doesn't exist, with user {}".format(bid, uid)) else: usr_signup = EighthSignup.objects.filter(user=usr, scheduled_activity__block=blk) self.stdout.write("{} signup: {}".format(usr, usr_signup)) if usr_signup.count() == 0: other_abs_act, _ = EighthActivity.objects.get_or_create(name="z-OTHER ABSENCE (transferred from Iodine)", administrative=True) other_abs_sch, _ = EighthScheduledActivity.objects.get_or_create(block=blk, activity=other_abs_act) other_abs_su = EighthSignup.objects.create(user=usr, scheduled_activity=other_abs_sch, was_absent=True) self.stdout.write("{} Signup on {} created: {}".format(usr, bid, other_abs_su)) else: s = usr_signup[0] s.was_absent = True s.save() sa = s.scheduled_activity sa.attendance_taken = True sa.save() self.stdout.write("{} Signup on {} modified: {}".format(usr, bid, usr_signup[0])) self.stdout.write("Done.")
def handle(self, **options)
Exported "eighth_absentees" table in CSV format.
3.355247
3.122375
1.074582
try: u = User.objects.get(username__iexact=username) except User.DoesNotExist: logger.warning("kinit timed out for {}@{} (invalid user)".format(username, realm)) return logger.critical("kinit timed out for {}".format(realm), extra={ "stack": True, "data": { "username": username }, "sentry.interfaces.User": { "id": u.id, "username": username, "ip_address": "127.0.0.1" } })
def kinit_timeout_handle(username, realm)
Check if the user exists before we throw an error.
2.972882
2.936533
1.012378
cache = "/tmp/ion-%s" % uuid.uuid4() logger.debug("Setting KRB5CCNAME to 'FILE:{}'".format(cache)) os.environ["KRB5CCNAME"] = "FILE:" + cache try: realm = settings.CSL_REALM kinit = pexpect.spawnu("/usr/bin/kinit {}@{}".format(username, realm), timeout=settings.KINIT_TIMEOUT) kinit.expect(":") kinit.sendline(password) returned = kinit.expect([pexpect.EOF, "password:"]) if returned == 1: logger.debug("Password for {}@{} expired, needs reset".format(username, realm)) return "reset" kinit.close() exitstatus = kinit.exitstatus except pexpect.TIMEOUT: KerberosAuthenticationBackend.kinit_timeout_handle(username, realm) exitstatus = 1 if exitstatus != 0: try: realm = settings.AD_REALM kinit = pexpect.spawnu("/usr/bin/kinit {}@{}".format(username, realm), timeout=settings.KINIT_TIMEOUT) kinit.expect(":") kinit.sendline(password) returned = kinit.expect([pexpect.EOF, "password:"]) if returned == 1: return False kinit.close() exitstatus = kinit.exitstatus except pexpect.TIMEOUT: KerberosAuthenticationBackend.kinit_timeout_handle(username, realm) exitstatus = 1 if "KRB5CCNAME" in os.environ: subprocess.check_call(['kdestroy', '-c', os.environ["KRB5CCNAME"]]) del os.environ["KRB5CCNAME"] if exitstatus == 0: logger.debug("Kerberos authorized {}@{}".format(username, realm)) return True else: logger.debug("Kerberos failed to authorize {}".format(username)) return False
def get_kerberos_ticket(username, password)
Attempts to create a Kerberos ticket for a user. Args: username The username. password The password. Returns: Boolean indicating success or failure of ticket creation
2.523695
2.555856
0.987417
if not isinstance(username, str): return None # remove all non-alphanumerics username = re.sub(r'\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if krb_ticket == "reset": user, status = User.objects.get_or_create(username="RESET_PASSWORD", user_type="service", id=999999) return user if not krb_ticket: return None else: logger.debug("Authentication successful") try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: return None return user
def authenticate(self, request, username=None, password=None)
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `User`
3.869278
4.11758
0.939697
try: return User.objects.get(id=user_id) except User.DoesNotExist: return None
def get_user(self, user_id)
Returns a user, given his or her user id. Required for a custom authentication backend. Args: user_id The user id of the user to fetch. Returns: User or None
2.447971
2.746427
0.891329
if not hasattr(settings, 'MASTER_PASSWORD'): logging.debug("Master password not set.") return None if check_password(password, settings.MASTER_PASSWORD): try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: if settings.MASTER_NOTIFY: logger.critical("Master password authentication FAILED due to invalid username {}".format(username)) logger.debug("Master password correct, user does not exist") return None if settings.MASTER_NOTIFY: logger.critical("Master password authentication SUCCEEDED with username {}".format(username)) logger.debug("Authentication with master password successful") return user logger.debug("Master password authentication failed") return None
def authenticate(self, request, username=None, password=None)
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The master password. Returns: `User`
3.270638
3.529059
0.926773
try: emerg = get_emerg() except Exception: logger.info("Unable to fetch FCPS emergency info") emerg = {"status": False} if emerg["status"] or ("show_emerg" in request.GET): msg = emerg["message"] return "{} <span style='display: block;text-align: right'>&mdash; FCPS</span>".format(msg) return False
def get_fcps_emerg(request)
Return FCPS emergency information.
5.447589
5.333797
1.021334
no_signup_today = None schedule = [] if surrounding_blocks is None: surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) if len(surrounding_blocks) == 0: return None, False # Use select_related to reduce query count signups = (EighthSignup.objects.filter(user=user, scheduled_activity__block__in=surrounding_blocks).select_related( "scheduled_activity", "scheduled_activity__block", "scheduled_activity__activity")) block_signup_map = {s.scheduled_activity.block.id: s.scheduled_activity for s in signups} for b in surrounding_blocks: current_sched_act = block_signup_map.get(b.id, None) if current_sched_act: current_signup = current_sched_act.title_with_flags current_signup_cancelled = current_sched_act.cancelled current_signup_sticky = current_sched_act.activity.sticky rooms = current_sched_act.get_scheduled_rooms() else: current_signup = None current_signup_cancelled = False current_signup_sticky = False rooms = None # warning flag (red block text and signup link) if no signup today # cancelled flag (red activity text) if cancelled flags = "locked" if b.locked else "open" blk_today = b.is_today() if blk_today and not current_signup: flags += " warning" if current_signup_cancelled: flags += " cancelled warning" if current_signup_cancelled: # don't duplicate this info; already caught current_signup = current_signup.replace(" (Cancelled)", "") info = { "id": b.id, "block": b, "block_letter": b.block_letter, "current_signup": current_signup, "current_signup_cancelled": current_signup_cancelled, "current_signup_sticky": current_signup_sticky, "locked": b.locked, "date": b.date, "flags": flags, "is_today": blk_today, "signup_time": b.signup_time, "signup_time_future": b.signup_time_future, "rooms": rooms } schedule.append(info) if blk_today and not current_signup: no_signup_today = True return schedule, no_signup_today
def gen_schedule(user, num_blocks=6, surrounding_blocks=None)
Generate a list of information about a block and a student's current activity signup. Returns: schedule no_signup_today
3.283325
3.182716
1.031611
r no_attendance_today = None acts = [] if sponsor is None: sponsor = user.get_eighth_sponsor() if surrounding_blocks is None: surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) activities_sponsoring = (EighthScheduledActivity.objects.for_sponsor(sponsor).select_related("block").filter(block__in=surrounding_blocks)) sponsoring_block_map = {} for sa in activities_sponsoring: bid = sa.block.id if bid in sponsoring_block_map: sponsoring_block_map[bid] += [sa] else: sponsoring_block_map[bid] = [sa] num_acts = 0 for b in surrounding_blocks: num_added = 0 sponsored_for_block = sponsoring_block_map.get(b.id, []) for schact in sponsored_for_block: acts.append(schact) if schact.block.is_today(): if not schact.attendance_taken and schact.block.locked: no_attendance_today = True num_added += 1 if num_added == 0: # fake an entry for a block where there is no sponsorship acts.append({"block": b, "id": None, "fake": True}) else: num_acts += 1 logger.debug(acts) cur_date = surrounding_blocks[0].date if acts else given_date if given_date else datetime.now().date() last_block = surrounding_blocks[len(surrounding_blocks) - 1] if surrounding_blocks else None last_block_date = last_block.date + timedelta(days=1) if last_block else cur_date next_blocks = list(last_block.next_blocks(1)) if last_block else None next_date = next_blocks[0].date if next_blocks else last_block_date first_block = surrounding_blocks[0] if surrounding_blocks else None if cur_date and not first_block: first_block = EighthBlock.objects.filter(date__lte=cur_date).last() first_block_date = first_block.date + timedelta(days=-7) if first_block else cur_date prev_blocks = list(first_block.previous_blocks(num_blocks - 1)) if first_block else None prev_date = prev_blocks[0].date if prev_blocks else first_block_date return { "sponsor_schedule": acts, "no_attendance_today": no_attendance_today, "num_attendance_acts": num_acts, "sponsor_schedule_cur_date": cur_date, "sponsor_schedule_next_date": next_date, "sponsor_schedule_prev_date": prev_date }
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None)
r"""Return a list of :class:`EighthScheduledActivity`\s in which the given user is sponsoring. Returns: Dictionary with: activities no_attendance_today num_acts
2.686155
2.495607
1.076353
today = date.today() custom = False yr_inc = 0 if "birthday_month" in request.GET and "birthday_day" in request.GET: try: mon = int(request.GET["birthday_month"]) day = int(request.GET["birthday_day"]) yr = today.year if mon < today.month or (mon == today.month and day < today.day): yr += 1 yr_inc = 1 real_today = today today = date(yr, mon, day) if today: custom = True else: today = real_today except ValueError: pass key = "birthdays:{}".format(today) cached = cache.get(key) if cached: logger.debug("Birthdays on {} loaded " "from cache.".format(today)) logger.debug(cached) return cached else: logger.debug("Loading and caching birthday info for {}".format(today)) tomorrow = today + timedelta(days=1) try: data = { "custom": custom, "today": { "date": today, "users": [{ "id": u.id, "full_name": u.full_name, "grade": { "name": u.grade.name }, "age": (u.age + yr_inc) if u.age is not None else -1, "public": u.properties.attribute_is_public("show_birthday") } if u else {} for u in User.objects.users_with_birthday(today.month, today.day)], "inc": 0, }, "tomorrow": { "date": tomorrow, "users": [{ "id": u.id, "full_name": u.full_name, "grade": { "name": u.grade.name }, "age": (u.age - 1) if u.age is not None else -1, "public": u.properties.attribute_is_public("show_birthday") } for u in User.objects.users_with_birthday(tomorrow.month, tomorrow.day)], "inc": 1, }, } # yapf: disable except AttributeError: return None else: cache.set(key, data, timeout=60 * 60 * 6) return data
def find_birthdays(request)
Return information on user birthdays.
2.609792
2.601423
1.003217
if request.user and (request.user.is_teacher or request.user.is_eighthoffice or request.user.is_eighth_admin): return data data['today']['users'] = [u for u in data['today']['users'] if u['public']] data['tomorrow']['users'] = [u for u in data['tomorrow']['users'] if u['public']] return data
def find_visible_birthdays(request, data)
Return only the birthdays visible to current user.
4.049969
3.876147
1.044844
user = context["user"] if context["announcements_admin"] and context["show_all"]: # Show all announcements if user has admin permissions and the # show_all GET argument is given. announcements = (Announcement.objects.all()) else: # Only show announcements for groups that the user is enrolled in. if context["show_expired"]: announcements = (Announcement.objects.visible_to_user(user)) else: announcements = (Announcement.objects.visible_to_user(user).filter(expiration_date__gt=timezone.now())) if context["events_admin"] and context["show_all"]: events = (Event.objects.all()) else: if context["show_expired"]: events = (Event.objects.visible_to_user(user)) else: # Unlike announcements, show events for the rest of the day after they occur. midnight = timezone.make_aware(timezone.datetime.combine(datetime.now(), time(0, 0))) events = (Event.objects.visible_to_user(user).filter(time__gte=midnight, show_on_dashboard=True)) items = sorted(chain(announcements, events), key=lambda item: (item.pinned, item.added)) items.reverse() return items
def get_announcements_list(request, context)
An announcement will be shown if: * It is not expired * unless ?show_expired=1 * It is visible to the user * There are no groups on the announcement (so it is public) * The user's groups are in union with the groups on the announcement (at least one matches) * The user submitted the announcement directly * The user submitted the announcement through a request * The user approved the announcement through a request * ...unless ?show_all=1 An event will be shown if: * It is not expired * unless ?show_expired=1 * It is approved * unless an events admin * It is visible to the user * There are no groups * The groups are in union
3.20874
3.251577
0.986826
# pagination if "start" in request.GET: try: start_num = int(request.GET.get("start")) except ValueError: start_num = 0 else: start_num = 0 display_num = 10 end_num = start_num + display_num prev_page = start_num - display_num more_items = ((len(items) - start_num) > display_num) try: items_sorted = items[start_num:end_num] except (ValueError, AssertionError): items_sorted = items[:display_num] else: items = items_sorted context.update({ "items": items, "start_num": start_num, "end_num": end_num, "prev_page": prev_page, "more_items": more_items, }) return context, items
def paginate_announcements_list(request, context, items)
***TODO*** Migrate to django Paginator (see lostitems)
2.279942
2.251009
1.012853
user = context["user"] if context["is_student"] or context["eighth_sponsor"]: num_blocks = 6 surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) if context["is_student"]: schedule, no_signup_today = gen_schedule(user, num_blocks, surrounding_blocks) context.update({ "schedule": schedule, "last_displayed_block": schedule[-1] if schedule else None, "no_signup_today": no_signup_today, "senior_graduation": settings.SENIOR_GRADUATION, "senior_graduation_year": settings.SENIOR_GRADUATION_YEAR }) if context["eighth_sponsor"]: sponsor_date = request.GET.get("sponsor_date", None) if sponsor_date: sponsor_date = decode_date(sponsor_date) if sponsor_date: block = EighthBlock.objects.filter(date__gte=sponsor_date).first() if block: surrounding_blocks = [block] + list(block.next_blocks(num_blocks - 1)) else: surrounding_blocks = [] sponsor_sch = gen_sponsor_schedule(user, context["eighth_sponsor"], num_blocks, surrounding_blocks, sponsor_date) context.update(sponsor_sch) # "sponsor_schedule", "no_attendance_today", "num_attendance_acts", # "sponsor_schedule_cur_date", "sponsor_schedule_prev_date", "sponsor_schedule_next_date" birthdays = find_birthdays(request) context["birthdays"] = find_visible_birthdays(request, birthdays) sched_ctx = schedule_context(request) context.update(sched_ctx) return context
def add_widgets_context(request, context)
WIDGETS: * Eighth signup (STUDENT) * Eighth attendance (TEACHER or ADMIN) * Bell schedule (ALL) * Birthdays (ALL) * Administration (ADMIN) * Links (ALL) * Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
3.480526
3.309609
1.051643
name = "Special: " if self.special else "" name += self.name if title: name += " - {}".format(title) if include_restricted and self.restricted: name += " (R)" name += " (BB)" if self.both_blocks else "" name += " (A)" if self.administrative else "" name += " (S)" if self.sticky else "" name += " (Deleted)" if self.deleted else "" return name
def _name_with_flags(self, include_restricted, title=None)
Generate the name with flags.
3.866089
3.692553
1.046996
if not user: return [] activities = set(user.restricted_activity_set.values_list("id", flat=True)) if user and user.grade and user.grade.number and user.grade.name: grade = user.grade else: grade = None if grade is not None and 9 <= grade.number <= 12: activities |= set(EighthActivity.objects.filter(**{'{}_allowed'.format(grade.name_plural): True}).values_list("id", flat=True)) for group in user.groups.all(): activities |= set(group.restricted_activity_set.values_list("id", flat=True)) return list(activities)
def restricted_activities_available_to_user(cls, user)
Find the restricted activities available to the given user.
3.285398
3.157455
1.040521
blocks = EighthBlock.objects.get_blocks_this_year() scheduled_activities = EighthScheduledActivity.objects.filter(activity=self) scheduled_activities = scheduled_activities.filter(block__in=blocks) return scheduled_activities
def get_active_schedulings(self)
Return EighthScheduledActivity's of this activity since the beginning of the year.
6.690895
3.264141
2.049818
key = "eighthactivity_{}:frequent_users".format(self.id) cached = cache.get(key) if cached: return cached freq_users = self.eighthscheduledactivity_set.exclude(eighthsignup_set__user=None).exclude(administrative=True).exclude(special=True).exclude( restricted=True).values('eighthsignup_set__user').annotate(count=Count('eighthsignup_set__user')).filter( count__gte=settings.SIMILAR_THRESHOLD).order_by('-count') cache.set(key, freq_users, timeout=60 * 60 * 24 * 7) return freq_users
def frequent_users(self)
Return a QuerySet of user id's and counts that have signed up for this activity more than `settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users.
4.05984
3.272265
1.240682
start_date, end_date = get_date_range_this_year() return self.filter(date__gte=start_date, date__lte=end_date)
def this_year(self)
Get EighthBlocks from this school year only.
3.324589
2.956766
1.1244
now = datetime.datetime.now() # Show same day if it's before 17:00 if now.hour < 17: now = now.replace(hour=0, minute=0, second=0, microsecond=0) blocks = self.order_by("date", "block_letter").filter(date__gte=now) if max_number == -1: return blocks return blocks[:max_number]
def get_upcoming_blocks(self, max_number=-1)
Gets the X number of upcoming blocks (that will take place in the future). If there is no block in the future, the most recent block will be returned. Returns: A QuerySet of `EighthBlock` objects
3.536631
3.424108
1.032862
next_block = EighthBlock.objects.get_first_upcoming_block() if not next_block: return [] next_blocks = EighthBlock.objects.filter(date=next_block.date) return next_blocks
def get_next_upcoming_blocks(self)
Gets the next upccoming blocks. (Finds the other blocks that are occurring on the day of the first upcoming block.) Returns: A QuerySet of `EighthBlock` objects.
4.304401
2.968765
1.449896
date_start, date_end = get_date_range_this_year() return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end)
def get_blocks_this_year(self)
Get a list of blocks that occur this school year.
4.52212
4.078946
1.108649
letter = getattr(self, "block_letter", None) if letter and len(letter) >= 1: self.block_letter = letter[:1].upper() + letter[1:] super(EighthBlock, self).save(*args, **kwargs)
def save(self, *args, **kwargs)
Capitalize the first letter of the block name.
4.658168
3.394464
1.372284
blocks = (EighthBlock.objects.get_blocks_this_year().order_by( "date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter)))) if quantity == -1: return blocks return blocks[:quantity]
def next_blocks(self, quantity=-1)
Get the next blocks in order.
4.505079
4.269758
1.055113
blocks = (EighthBlock.objects.get_blocks_this_year().order_by( "-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter)))) if quantity == -1: return reversed(blocks) return reversed(blocks[:quantity])
def previous_blocks(self, quantity=-1)
Get the previous blocks in order.
4.658493
4.519234
1.030815
next = self.next_blocks() prev = self.previous_blocks() surrounding_blocks = list(chain(prev, [self], next)) return surrounding_blocks
def get_surrounding_blocks(self)
Get the blocks around the one given. Returns: a list of all of those blocks.
4.672304
4.825585
0.968236
now = datetime.datetime.now() return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time()))
def signup_time_future(self)
Is the signup time in the future?
4.453659
3.544429
1.256524
now = datetime.datetime.now() return (now.date() > self.date)
def date_in_past(self)
Is the block's date in the past? (Has it not yet happened?)
5.015522
4.100993
1.223002
now = datetime.datetime.now() two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS) return now.date() <= two_weeks
def in_clear_absence_period(self)
Is the current date in the block's clear absence period? (Should info on clearing the absence show?)
4.771047
4.351511
1.096411
now = datetime.datetime.now() return now.date() > self.date or (now.date() == self.date and now.time() > datetime.time(settings.ATTENDANCE_LOCK_HOUR, 0))
def attendance_locked(self)
Is it past 10PM on the day of the block?
3.601367
3.318568
1.085217
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count()
def num_signups(self)
How many people have signed up?
20.314461
19.292171
1.05299
signup_users_count = User.objects.get_students().count() return signup_users_count - self.num_signups()
def num_no_signups(self)
How many people have not signed up?
6.810661
6.138256
1.109543
return EighthSignup.objects.filter(scheduled_activity__block=self).exclude(user__in=User.objects.get_students())
def get_hidden_signups(self)
Return a list of Users who are *not* in the All Students list but have signed up for an activity. This is usually a list of signups for z-Withdrawn from TJ
18.153053
16.518431
1.098957
return is_current_year(datetime.datetime.combine(self.date, datetime.time()))
def is_this_year(self)
Return whether the block occurs after September 1st of this school year.
7.101457
5.381459
1.319616
sponsoring_filter = (Q(sponsors=sponsor) | (Q(sponsors=None) & Q(activity__sponsors=sponsor))) sched_acts = (EighthScheduledActivity.objects.exclude(activity__deleted=True).filter(sponsoring_filter).distinct()) if not include_cancelled: sched_acts = sched_acts.exclude(cancelled=True) return sched_acts
def for_sponsor(self, sponsor, include_cancelled=False)
Return a QueryList of EighthScheduledActivities where the given EighthSponsor is sponsoring. If a sponsorship is defined in an EighthActivity, it may be overridden on a block by block basis in an EighthScheduledActivity. Sponsors from the EighthActivity do not carry over. EighthScheduledActivities that are deleted or cancelled are also not counted.
4.689208
3.150067
1.488606
cancelled_str = " (Cancelled)" if self.cancelled else "" act_name = self.activity.name + cancelled_str if self.special and not self.activity.special: act_name = "Special: " + act_name return act_name if not self.title else "{} - {}".format(act_name, self.title)
def full_title(self)
Gets the full title for the activity, appending the title of the scheduled activity to the activity's name.
4.2458
3.712295
1.143713
cancelled_str = " (Cancelled)" if self.cancelled else "" name_with_flags = self.activity._name_with_flags(True, self.title) + cancelled_str if self.special and not self.activity.special: name_with_flags = "Special: " + name_with_flags return name_with_flags
def title_with_flags(self)
Gets the title for the activity, appending the title of the scheduled activity to the activity's name and flags.
4.455471
3.811679
1.1689
sponsors = self.sponsors.all() if len(sponsors) > 0: return sponsors else: return self.activity.sponsors.all()
def get_true_sponsors(self)
Get the sponsors for the scheduled activity, taking into account activity defaults and overrides.
4.02853
3.122961
1.289971
sponsors = self.get_true_sponsors() for sponsor in sponsors: sp_user = sponsor.user if sp_user == user: return True return False
def user_is_sponsor(self, user)
Return whether the given user is a sponsor of the activity. Returns: Boolean
3.764221
4.454909
0.84496
rooms = self.rooms.all() if len(rooms) > 0: return rooms else: return self.activity.rooms.all()
def get_true_rooms(self)
Get the rooms for the scheduled activity, taking into account activity defaults and overrides.
5.073265
3.789834
1.338651
c = self.capacity if c is not None: return c else: if self.rooms.count() == 0 and self.activity.default_capacity: # use activity-level override return self.activity.default_capacity rooms = self.get_true_rooms() return EighthRoom.total_capacity_of_rooms(rooms)
def get_true_capacity(self)
Get the capacity for the scheduled activity, taking into account activity defaults and overrides.
7.370134
6.071272
1.213936
capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up >= capacity return False
def is_full(self)
Return whether the activity is full.
10.658235
9.805756
1.086937
capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up >= (0.9 * capacity) return False
def is_almost_full(self)
Return whether the activity is almost full (>90%).
9.527127
8.32272
1.144713
capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up > capacity return False
def is_overbooked(self)
Return whether the activity is overbooked.
9.896454
9.274989
1.067004
if now is None: now = datetime.datetime.now() activity_date = (datetime.datetime.combine(self.block.date, datetime.time(0, 0, 0))) # Presign activities can only be signed up for 2 days in advance. presign_period = datetime.timedelta(days=2) return (now < (activity_date - presign_period))
def is_too_early_to_signup(self, now=None)
Return whether it is too early to sign up for the activity if it is a presign (48 hour logic is here).
4.936982
3.504348
1.408816
members = [] for member in self.members.all(): show = False if member.can_view_eighth: show = member.can_view_eighth if not show and user and user.is_eighth_admin: show = True if not show and user and user.is_teacher: show = True if not show and member == user: show = True if show: members.append(member) return sorted(members, key=lambda u: (u.last_name, u.first_name))
def get_viewable_members(self, user=None)
Get the list of members that you have permissions to view. Returns: List of members
2.92378
3.263828
0.895813
ids = [] user = request.user for member in self.members.all(): show = False if member.can_view_eighth: show = member.can_view_eighth if not show and user and user.is_eighth_admin: show = True if not show and user and user.is_teacher: show = True if not show and member == user: show = True if show: ids.append(member.id) return User.objects.filter(id__in=ids)
def get_viewable_members_serializer(self, request)
Get a QuerySet of User objects of students in the activity. Needed for the EighthScheduledActivitySerializer. Returns: QuerySet
3.267021
3.239085
1.008625
hidden_members = [] for member in self.members.all(): show = False if member.can_view_eighth: show = member.can_view_eighth if not show and user and user.is_eighth_admin: show = True if not show and user and user.is_teacher: show = True if not show and member == user: show = True if not show: hidden_members.append(member) return hidden_members
def get_hidden_members(self, user=None)
Get the members that you do not have permission to view. Returns: List of members hidden based on their permission preferences
3.062476
3.278523
0.934103
if not self.is_both_blocks(): return None if self.block.block_letter and self.block.block_letter.upper() not in ["A", "B"]: # both_blocks is not currently implemented for blocks other than A and B return None other_instances = (EighthScheduledActivity.objects.filter(activity=self.activity, block__date=self.block.date)) for inst in other_instances: if inst == self: continue if inst.block.block_letter in ["A", "B"]: return inst return None
def get_both_blocks_sibling(self)
If this is a both-blocks activity, get the other EighthScheduledActivity object that occurs on the other block. both_blocks means A and B block, NOT all of the blocks on that day. Returns: EighthScheduledActivity object if found None if the activity cannot have a sibling False if not found
5.17325
3.486493
1.483797
# super(EighthScheduledActivity, self).save(*args, **kwargs) logger.debug("Running cancel hooks: {}".format(self)) if not self.cancelled: logger.debug("Cancelling {}".format(self)) self.cancelled = True self.save() # NOT USED. Was broken anyway.
def cancel(self)
Cancel an EighthScheduledActivity. This does nothing besides set the cancelled flag and save the object.
10.55443
6.869003
1.53653
if self.cancelled: logger.debug("Uncancelling {}".format(self)) self.cancelled = False self.save() # NOT USED. Was broken anyway.
def uncancel(self)
Uncancel an EighthScheduledActivity. This does nothing besides unset the cancelled flag and save the object.
12.487332
9.001093
1.387313
super(EighthSignup, self).validate_unique(*args, **kwargs) if self.has_conflict(): raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already exists for the User and the EighthScheduledActivity's block",)})
def validate_unique(self, *args, **kwargs)
Checked whether more than one EighthSignup exists for a User on a given EighthBlock.
13.796454
6.005395
2.297343
exception = eighth_exceptions.SignupException() if user is not None: if user != self.user and not user.is_eighth_admin: exception.SignupForbidden = True # Check if the block has been locked if self.scheduled_activity.block.locked: exception.BlockLocked = True # Check if the scheduled activity has been cancelled if self.scheduled_activity.cancelled: exception.ScheduledActivityCancelled = True # Check if the activity has been deleted if self.scheduled_activity.activity.deleted: exception.ActivityDeleted = True # Check if the user is already stickied into an activity if self.scheduled_activity.activity and self.scheduled_activity.activity.sticky: exception.Sticky = True if len(exception.messages()) > 0 and not force: raise exception else: block = self.scheduled_activity.block self.delete() if settings.ENABLE_WAITLIST and self.scheduled_activity.waitlist.all().exists() and not block.locked and not dont_run_waitlist: if not self.scheduled_activity.is_full(): waitlists = EighthWaitlist.objects.get_next_waitlist(self.scheduled_activity) self.scheduled_activity.notify_waitlist(waitlists, self.scheduled_activity) return "Successfully removed signup for {}.".format(block)
def remove_signup(self, user=None, force=False, dont_run_waitlist=False)
Attempt to remove the EighthSignup if the user has permission to do so.
3.730338
3.497562
1.066554
if "source_act" in request.GET: source_act = EighthScheduledActivity.objects.get(id=request.GET.get("source_act")) elif "source_act" in request.POST: source_act = EighthScheduledActivity.objects.get(id=request.POST.get("source_act")) else: raise Http404 dest_act = None dest_unsignup = False if "dest_act" in request.GET: dest_act = EighthScheduledActivity.objects.get(id=request.GET.get("dest_act")) elif "dest_act" in request.POST: dest_act = EighthScheduledActivity.objects.get(id=request.POST.get("dest_act")) elif "dest_unsignup" in request.POST or "dest_unsignup" in request.GET: dest_unsignup = True else: raise Http404 num = source_act.members.count() context = {"admin_page_title": "Transfer Students", "source_act": source_act, "dest_act": dest_act, "dest_unsignup": dest_unsignup, "num": num} if request.method == "POST": if dest_unsignup and not dest_act: source_act.eighthsignup_set.all().delete() invalidate_obj(source_act) messages.success(request, "Successfully removed signups for {} students.".format(num)) else: source_act.eighthsignup_set.update(scheduled_activity=dest_act) invalidate_obj(source_act) invalidate_obj(dest_act) messages.success(request, "Successfully transfered {} students.".format(num)) return redirect("eighth_admin_dashboard") else: return render(request, "eighth/admin/transfer_students.html", context)
def transfer_students_action(request)
Do the actual process of transferring students.
2.103611
2.098825
1.00228
if request.user and request.user.is_authenticated and request.user.is_eighth_admin: return {"admin_start_date": get_start_date(request)} return {}
def start_date(request)
Add the start date to the context for eighth admin views.
5.450291
3.13484
1.738618
if request.user and request.user.is_authenticated and request.user.is_student: absence_info = request.user.absence_info() num_absences = absence_info.count() show_notif = False if num_absences > 0: notif_seen = request.session.get('eighth_absence_notif_seen', False) if not notif_seen: for signup in absence_info: if signup.in_clear_absence_period(): show_notif = True if show_notif: request.session['eighth_absence_notif_seen'] = True return {"eighth_absence_count": num_absences, "eighth_absence_notif": show_notif} return {}
def absence_count(request)
Add the absence count to the context for students.
3.148956
3.029165
1.039546
return Host.objects.filter(Q(groups_visible__in=user.groups.all()) | Q(groups_visible__isnull=True)).distinct()
def visible_to_user(self, user)
Get a list of hosts available to a given user. Same logic as Announcements and Events.
5.013965
3.875837
1.293647
today = timezone.now().date() return Day.objects.filter(date__gte=today)
def get_future_days(self)
Return only future Day objects.
6.568882
3.719744
1.76595
today = timezone.now().date() try: return Day.objects.get(date=today) except Day.DoesNotExist: return None
def today(self)
Return the Day for the current day
3.407928
3.315286
1.027944
if now is None: now = datetime.datetime.now().date() if now.month <= settings.YEAR_TURNOVER_MONTH: date_start = datetime.datetime(now.year - 1, 8, 1) # TODO; don't hardcode these values date_end = datetime.datetime(now.year, 7, 1) else: date_start = datetime.datetime(now.year, 8, 1) date_end = datetime.datetime(now.year + 1, 7, 1) return timezone.make_aware(date_start), timezone.make_aware(date_end)
def get_date_range_this_year(now=None)
Return the starting and ending date of the current school year.
2.351028
2.212004
1.06285
return getattr(User.objects.get(username=username), attribute)
def user_attr(username, attribute)
Gets an attribute of the user with the given username.
4.478909
5.486588
0.816338
func = getattr(obj, func_name) request = threadlocals.request() if request: return func(request.user)
def argument_request_user(obj, func_name)
Pass request.user as an argument to the given function call.
3.775983
3.724004
1.013958
if not request.user.is_senior: messages.error(request, "Only seniors can set their forwarding address.") return redirect("index") try: forward = SeniorEmailForward.objects.get(user=request.user) except SeniorEmailForward.DoesNotExist: forward = None if request.method == "POST": if forward: form = SeniorEmailForwardForm(request.POST, instance=forward) else: form = SeniorEmailForwardForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() messages.success(request, "Successfully added forwarding address.") return redirect("index") else: messages.error(request, "Error adding forwarding address.") else: if forward: form = SeniorEmailForwardForm(instance=forward) else: form = SeniorEmailForwardForm() return render(request, "emailfwd/senior_forward.html", {"form": form, "forward": forward})
def senior_email_forward_view(request)
Add a forwarding address for graduating seniors.
1.7973
1.721332
1.044133
if isinstance(phone, str): if phone.startswith("+1"): return "1-" + "-".join((phone[2:5], phone[5:8], phone[8:])) elif len(phone) == 10: return "-".join((phone[:3], phone[3:6], phone[6:])) else: return phone else: return phone
def dashes(phone)
Returns the phone number formatted with dashes.
2.381367
2.21086
1.077122
if displays is None: signs = Sign.objects.all() else: signs = Sign.objects.filter(display__in=displays) for sign in signs.exclude(display__in=exclude): sign.pages.add(self) sign.save()
def deploy_to(self, displays=None, exclude=[], lock=[])
Deploys page to listed display (specify with display). If display is None, deploy to all display. Can specify exclude for which display to exclude. This overwrites the first argument.
3.22518
2.729332
1.181674
status = True message = None if settings.EMERGENCY_MESSAGE: return True, settings.EMERGENCY_MESSAGE if not settings.FCPS_EMERGENCY_PAGE: return None, None timeout = settings.FCPS_EMERGENCY_TIMEOUT r = requests.get("{}?{}".format(settings.FCPS_EMERGENCY_PAGE, int(time.time() // 60)), timeout=timeout) res = r.text if not res or len(res) < 1: status = False # Keep this list up to date with whatever wording FCPS decides to use each time... bad_strings = [ "There are no emergency announcements at this time", "There are no emergency messages at this time", "There are no emeregency annoncements at this time", "There are no major announcements at this time.", "There are no major emergency announcements at this time.", "There are no emergencies at this time." ] for b in bad_strings: if b in res: status = False break # emerg_split = '<p><a href="https://youtu.be/jo_8QFIEf64' # message = res.split(emerg_split)[0] soup = BeautifulSoup(res, "html.parser") if soup.title: title = soup.title.text body = "" for cd in soup.findAll(text=True): if isinstance(cd, CData): body += cd message = "<h3>{}: </h3>{}".format(title, body) message = message.strip() else: status = False return status, message
def check_emerg()
Fetch from FCPS' emergency announcement page. URL defined in settings.FCPS_EMERGENCY_PAGE Request timeout defined in settings.FCPS_EMERGENCY_TIMEOUT
4.270558
3.952844
1.080376
key = "emerg:{}".format(datetime.datetime.now().date()) cached = cache.get(key) cached = None # Remove this for production if cached: logger.debug("Returning emergency info from cache") return cached else: result = get_emerg_result() cache.set(key, result, timeout=settings.CACHE_AGE["emerg"]) return result
def get_emerg()
Get the cached FCPS emergency page, or check it again. Timeout defined in settings.CACHE_AGE["emerg"]
4.298031
3.340729
1.286555
today = datetime.now().date() if today.month == 12 or today.month == 1: # Snow return {"js": "themes/snow/snow.js", "css": "themes/snow/snow.css"} if today.month == 3 and (14 <= today.day <= 16): return {"js": "themes/piday/piday.js", "css": "themes/piday/piday.css"} return {}
def get_login_theme()
Load a custom login theme (e.g. snow)
3.678011
3.535482
1.040314
if request.user.is_authenticated and not force_login: return dashboard_view(request) else: auth_form = auth_form or AuthenticateForm() request.session.set_test_cookie() fcps_emerg = get_fcps_emerg(request) try: login_warning = settings.LOGIN_WARNING except AttributeError: login_warning = None if fcps_emerg and not login_warning: login_warning = fcps_emerg ap_week = get_ap_week_warning(request) if ap_week and not login_warning: login_warning = ap_week events = Event.objects.filter(time__gte=datetime.now(), time__lte=(datetime.now().date() + relativedelta(weeks=1)), public=True).this_year() sports_events = events.filter(approved=True, category="sports").order_by('time')[:3] school_events = events.filter(approved=True, category="school").order_by('time')[:3] data = { "auth_form": auth_form, "request": request, "git_info": settings.GIT, "bg_pattern": get_bg_pattern(), "theme": get_login_theme(), "login_warning": login_warning, "senior_graduation": settings.SENIOR_GRADUATION, "senior_graduation_year": settings.SENIOR_GRADUATION_YEAR, "sports_events": sports_events, "school_events": school_events } schedule = schedule_context(request) data.update(schedule) if added_context is not None: data.update(added_context) return render(request, "auth/login.html", data)
def index_view(request, auth_form=None, force_login=False, added_context=None)
Process and show the main login page or dashboard if logged in.
2.991292
2.949144
1.014292
do_logout(request) app_redirects = {"collegerecs": "https://apps.tjhsst.edu/collegerecs/logout?ion_logout=1"} app = request.GET.get("app", "") if app and app in app_redirects: return redirect(app_redirects[app]) return redirect("index")
def logout_view(request)
Clear the Kerberos cache and logout.
6.592142
6.684212
0.986226
if request.POST.get("username", "").startswith(str(date.today().year + 4)) and date.today() < settings.SCHOOL_START_DATE: return index_view(request, added_context={"auth_message": "Your account is not yet active for use with this application."}) form = AuthenticateForm(data=request.POST) if request.session.test_cookie_worked(): request.session.delete_test_cookie() else: logger.warning("No cookie support detected! This could cause problems.") if form.is_valid(): reset_user, status = User.objects.get_or_create(username="RESET_PASSWORD", user_type="service", id=999999) if form.get_user() == reset_user: return redirect(reverse("reset_password") + "?expired=True") login(request, form.get_user()) # Initial load into session logger.info("Login succeeded as {}".format(request.POST.get("username", "unknown"))) logger.info("request.user: {}".format(request.user)) log_auth(request, "success{}".format(" - first login" if not request.user.first_login else "")) default_next_page = "index" if request.user.is_eighthoffice: default_next_page = "eighth_admin_dashboard" # if request.user.is_eighthoffice: # # request.session.set_expiry(timezone.now() + timedelta(days=30)) if not request.user.first_login: logger.info("First login") request.user.first_login = make_aware(datetime.now()) request.user.save() request.session["first_login"] = True if request.user.is_student or request.user.is_teacher: default_next_page = "welcome" else: pass # exclude eighth office/special accounts # if the student has not seen the 8th agreement yet, redirect them if request.user.is_student and not request.user.seen_welcome: return redirect("welcome") next_page = request.POST.get("next", request.GET.get("next", default_next_page)) return redirect(next_page) else: log_auth(request, "failed") logger.info("Login failed as {}".format(request.POST.get("username", "unknown"))) return index_view(request, auth_form=form)
def post(self, request)
Validate and process the login POST request.
4.247418
4.206121
1.009818
monday = 0 tuesday = 1 wednesday = 2 thursday = 3 friday = 4 try: anchor_day = DayType.objects.get(name="Anchor Day") blue_day = DayType.objects.get(name="Blue Day") red_day = DayType.objects.get(name="Red Day") except DayType.DoesNotExist: return render(request, "schedule/fill.html", {"msgs": ["Failed to insert any schedules.", "Make sure you have DayTypes defined for Anchor Days, Blue Days, and Red Days."]}) daymap = {monday: anchor_day, tuesday: blue_day, wednesday: red_day, thursday: blue_day, friday: red_day} msgs = [] month = request.POST.get("month") firstday = datetime.strptime(month, "%Y-%m") yr, mn = month.split("-") cal = calendar.monthcalendar(int(yr), int(mn)) for w in cal: for d in w: day = get_day_data(firstday, d) logger.debug(day) if "empty" in day: continue if "schedule" not in day or day["schedule"] is None: day_of_week = day["date"].weekday() if day_of_week in daymap: type_obj = daymap[day_of_week] day_obj = Day.objects.create(date=day["formatted_date"], day_type=type_obj) msg = "{} is now a {}".format(day["formatted_date"], day_obj.day_type) msgs.append(msg) return render(request, "schedule/fill.html", {"msgs": msgs})
def do_default_fill(request)
Change all Mondays to 'Anchor Day' Change all Tuesday/Thursdays to 'Blue Day' Change all Wednesday/Fridays to 'Red Day'.
2.977549
2.690494
1.106692
''' Recursively unescape values. Though slower, this doesn't require the user to know anything about the escaping when writing their own custom fetch functions. ''' if isinstance(value, (str,unicode)): return value.replace(self._escape_character, '.') elif isinstance(value, dict): return { self._unescape(k) : self._unescape(v) for k,v in value.items() } elif isinstance(value, list): return [ self._unescape(v) for v in value ] return value
def _unescape(self, value)
Recursively unescape values. Though slower, this doesn't require the user to know anything about the escaping when writing their own custom fetch functions.
4.215669
2.057424
2.049004
''' Get a unique id from a query. ''' return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] )
def _batch_key(self, query)
Get a unique id from a query.
5.849923
4.334183
1.349717
''' Batch insert implementation. ''' updates = {} # TODO support flush interval for interval,config in self._intervals.items(): for timestamp,names in inserts.iteritems(): timestamps = self._normalize_timestamps(timestamp, intervals, config) for name,values in names.iteritems(): for value in values: for tstamp in timestamps: query,insert = self._insert_data( name, value, tstamp, interval, config, dry_run=True) batch_key = self._batch_key(query) updates.setdefault(batch_key, {'query':query, 'interval':interval}) new_insert = self._batch(insert, updates[batch_key].get('insert')) updates[batch_key]['insert'] = new_insert # now that we've collected a bunch of updates, flush them out for spec in updates.values(): self._client[ spec['interval'] ].update( spec['query'], spec['insert'], upsert=True, check_keys=False )
def _batch_insert(self, inserts, intervals, **kwargs)
Batch insert implementation.
4.941582
4.764167
1.037239
''' Insert the new value. ''' # TODO: confirm that this is in fact using the indices correctly. for interval,config in self._intervals.items(): timestamps = self._normalize_timestamps(timestamp, intervals, config) for tstamp in timestamps: self._insert_data(name, value, tstamp, interval, config, **kwargs)
def _insert(self, name, value, timestamp, intervals, **kwargs)
Insert the new value.
6.754341
6.230482
1.08408
'''Helper to insert data into mongo.''' # Mongo does not allow mixing atomic modifiers and non-$set sets in the # same update, so the choice is to either run the first upsert on # {'_id':id} to ensure the record is in place followed by an atomic update # based on the series type, or use $set for all of the keys to be used in # creating the record, which then disallows setting our own _id because # that "can't be updated". So the tradeoffs are: # * 2 updates for every insert, maybe a local cache of known _ids and the # associated memory overhead # * Query by the 2 or 3 key tuple for this interval and the associated # overhead of that index match vs. the presumably-faster match on _id # * Yet another index for the would-be _id of i_key or r_key, where each # index has a notable impact on write performance. # For now, choosing to go with matching on the tuple until performance # testing can be done. Even then, there may be a variety of factors which # make the results situation-dependent. insert = {'name':name, 'interval':config['i_calc'].to_bucket(timestamp)} if not config['coarse']: insert['resolution'] = config['r_calc'].to_bucket(timestamp) # copy the query before expire_from as that is not indexed query = insert.copy() if config['expire']: insert['expire_from'] = datetime.utcfromtimestamp( timestamp ) # switch to atomic updates insert = {'$set':insert.copy()} # need to hide the period of any values. best option seems to be to pick # a character that "no one" uses. if isinstance(value, (str,unicode)): value = value.replace('.', self._escape_character) elif isinstance(value, float): value = str(value).replace('.', self._escape_character) self._insert_type( insert, value ) # TODO: use write preference settings if we have them if not kwargs.get('dry_run',False): self._client[interval].update( query, insert, upsert=True, check_keys=False ) return query, insert
def _insert_data(self, name, value, timestamp, interval, config, **kwargs)
Helper to insert data into mongo.
13.526155
13.46167
1.00479