_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q15700
|
EighthActivity.restricted_activities_available_to_user
|
train
|
def restricted_activities_available_to_user(cls, user):
"""Find the restricted activities available to the given user."""
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)
|
python
|
{
"resource": ""
}
|
q15701
|
EighthActivity.get_active_schedulings
|
train
|
def get_active_schedulings(self):
"""Return EighthScheduledActivity's of this activity since the beginning of the year."""
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
|
python
|
{
"resource": ""
}
|
q15702
|
EighthActivity.frequent_users
|
train
|
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."""
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
|
python
|
{
"resource": ""
}
|
q15703
|
EighthBlockQuerySet.this_year
|
train
|
def this_year(self):
""" Get EighthBlocks from this school year only. """
start_date, end_date = get_date_range_this_year()
return self.filter(date__gte=start_date, date__lte=end_date)
|
python
|
{
"resource": ""
}
|
q15704
|
EighthBlockManager.get_blocks_this_year
|
train
|
def get_blocks_this_year(self):
"""Get a list of blocks that occur this school year."""
date_start, date_end = get_date_range_this_year()
return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end)
|
python
|
{
"resource": ""
}
|
q15705
|
EighthBlock.save
|
train
|
def save(self, *args, **kwargs):
"""Capitalize the first letter of the block name."""
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)
|
python
|
{
"resource": ""
}
|
q15706
|
EighthBlock.next_blocks
|
train
|
def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
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]
|
python
|
{
"resource": ""
}
|
q15707
|
EighthBlock.previous_blocks
|
train
|
def previous_blocks(self, quantity=-1):
"""Get the previous blocks in order."""
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])
|
python
|
{
"resource": ""
}
|
q15708
|
EighthBlock.get_surrounding_blocks
|
train
|
def get_surrounding_blocks(self):
"""Get the blocks around the one given.
Returns: a list of all of those blocks.
"""
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks
|
python
|
{
"resource": ""
}
|
q15709
|
EighthBlock.signup_time_future
|
train
|
def signup_time_future(self):
"""Is the signup time in the future?"""
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time()))
|
python
|
{
"resource": ""
}
|
q15710
|
EighthBlock.date_in_past
|
train
|
def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date)
|
python
|
{
"resource": ""
}
|
q15711
|
EighthBlock.in_clear_absence_period
|
train
|
def in_clear_absence_period(self):
"""Is the current date in the block's clear absence period?
(Should info on clearing the absence show?)
"""
now = datetime.datetime.now()
two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS)
return now.date() <= two_weeks
|
python
|
{
"resource": ""
}
|
q15712
|
EighthBlock.attendance_locked
|
train
|
def attendance_locked(self):
"""Is it past 10PM on the day of the block?"""
now = datetime.datetime.now()
return now.date() > self.date or (now.date() == self.date and now.time() > datetime.time(settings.ATTENDANCE_LOCK_HOUR, 0))
|
python
|
{
"resource": ""
}
|
q15713
|
EighthBlock.num_signups
|
train
|
def num_signups(self):
"""How many people have signed up?"""
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count()
|
python
|
{
"resource": ""
}
|
q15714
|
EighthBlock.num_no_signups
|
train
|
def num_no_signups(self):
"""How many people have not signed up?"""
signup_users_count = User.objects.get_students().count()
return signup_users_count - self.num_signups()
|
python
|
{
"resource": ""
}
|
q15715
|
EighthBlock.is_this_year
|
train
|
def is_this_year(self):
"""Return whether the block occurs after September 1st of this school year."""
return is_current_year(datetime.datetime.combine(self.date, datetime.time()))
|
python
|
{
"resource": ""
}
|
q15716
|
EighthScheduledActivityManager.for_sponsor
|
train
|
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.
"""
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
|
python
|
{
"resource": ""
}
|
q15717
|
EighthScheduledActivity.full_title
|
train
|
def full_title(self):
"""Gets the full title for the activity, appending the title of the scheduled activity to
the activity's name."""
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)
|
python
|
{
"resource": ""
}
|
q15718
|
EighthScheduledActivity.title_with_flags
|
train
|
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."""
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
|
python
|
{
"resource": ""
}
|
q15719
|
EighthScheduledActivity.get_true_sponsors
|
train
|
def get_true_sponsors(self):
"""Get the sponsors for the scheduled activity, taking into account activity defaults and
overrides."""
sponsors = self.sponsors.all()
if len(sponsors) > 0:
return sponsors
else:
return self.activity.sponsors.all()
|
python
|
{
"resource": ""
}
|
q15720
|
EighthScheduledActivity.user_is_sponsor
|
train
|
def user_is_sponsor(self, user):
"""Return whether the given user is a sponsor of the activity.
Returns:
Boolean
"""
sponsors = self.get_true_sponsors()
for sponsor in sponsors:
sp_user = sponsor.user
if sp_user == user:
return True
return False
|
python
|
{
"resource": ""
}
|
q15721
|
EighthScheduledActivity.get_true_rooms
|
train
|
def get_true_rooms(self):
"""Get the rooms for the scheduled activity, taking into account activity defaults and
overrides."""
rooms = self.rooms.all()
if len(rooms) > 0:
return rooms
else:
return self.activity.rooms.all()
|
python
|
{
"resource": ""
}
|
q15722
|
EighthScheduledActivity.get_true_capacity
|
train
|
def get_true_capacity(self):
"""Get the capacity for the scheduled activity, taking into account activity defaults and
overrides."""
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)
|
python
|
{
"resource": ""
}
|
q15723
|
EighthScheduledActivity.is_full
|
train
|
def is_full(self):
"""Return whether the activity is full."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= capacity
return False
|
python
|
{
"resource": ""
}
|
q15724
|
EighthScheduledActivity.is_overbooked
|
train
|
def is_overbooked(self):
"""Return whether the activity is overbooked."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up > capacity
return False
|
python
|
{
"resource": ""
}
|
q15725
|
EighthScheduledActivity.get_viewable_members
|
train
|
def get_viewable_members(self, user=None):
"""Get the list of members that you have permissions to view.
Returns: List of members
"""
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))
|
python
|
{
"resource": ""
}
|
q15726
|
EighthScheduledActivity.get_viewable_members_serializer
|
train
|
def get_viewable_members_serializer(self, request):
"""Get a QuerySet of User objects of students in the activity. Needed for the
EighthScheduledActivitySerializer.
Returns: QuerySet
"""
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)
|
python
|
{
"resource": ""
}
|
q15727
|
EighthScheduledActivity.get_hidden_members
|
train
|
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
"""
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
|
python
|
{
"resource": ""
}
|
q15728
|
EighthScheduledActivity.get_both_blocks_sibling
|
train
|
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
"""
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
|
python
|
{
"resource": ""
}
|
q15729
|
EighthScheduledActivity.cancel
|
train
|
def cancel(self):
"""Cancel an EighthScheduledActivity.
This does nothing besides set the cancelled flag and save the
object.
"""
# 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.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room not in list(self.rooms.all()):
self.rooms.all().delete()
self.rooms.add(cancelled_room)
if cancelled_sponsor not in list(self.sponsors.all()):
self.sponsors.all().delete()
self.sponsors.add(cancelled_sponsor)
self.save()
"""
|
python
|
{
"resource": ""
}
|
q15730
|
EighthScheduledActivity.uncancel
|
train
|
def uncancel(self):
"""Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object.
"""
if self.cancelled:
logger.debug("Uncancelling {}".format(self))
self.cancelled = False
self.save()
# NOT USED. Was broken anyway.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room in list(self.rooms.all()):
self.rooms.filter(id=cancelled_room.id).delete()
if cancelled_sponsor in list(self.sponsors.all()):
self.sponsors.filter(id=cancelled_sponsor.id).delete()
self.save()
"""
|
python
|
{
"resource": ""
}
|
q15731
|
EighthSignup.validate_unique
|
train
|
def validate_unique(self, *args, **kwargs):
"""Checked whether more than one EighthSignup exists for a User on a given EighthBlock."""
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",)})
|
python
|
{
"resource": ""
}
|
q15732
|
EighthSignup.remove_signup
|
train
|
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."""
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)
|
python
|
{
"resource": ""
}
|
q15733
|
transfer_students_action
|
train
|
def transfer_students_action(request):
"""Do the actual process of transferring students."""
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)
|
python
|
{
"resource": ""
}
|
q15734
|
start_date
|
train
|
def start_date(request):
"""Add the start date to the context for eighth admin views."""
if request.user and request.user.is_authenticated and request.user.is_eighth_admin:
return {"admin_start_date": get_start_date(request)}
return {}
|
python
|
{
"resource": ""
}
|
q15735
|
absence_count
|
train
|
def absence_count(request):
"""Add the absence count to the context for students."""
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 {}
|
python
|
{
"resource": ""
}
|
q15736
|
HostManager.visible_to_user
|
train
|
def visible_to_user(self, user):
"""Get a list of hosts available to a given user.
Same logic as Announcements and Events.
"""
return Host.objects.filter(Q(groups_visible__in=user.groups.all()) | Q(groups_visible__isnull=True)).distinct()
|
python
|
{
"resource": ""
}
|
q15737
|
DayManager.get_future_days
|
train
|
def get_future_days(self):
"""Return only future Day objects."""
today = timezone.now().date()
return Day.objects.filter(date__gte=today)
|
python
|
{
"resource": ""
}
|
q15738
|
DayManager.today
|
train
|
def today(self):
"""Return the Day for the current day"""
today = timezone.now().date()
try:
return Day.objects.get(date=today)
except Day.DoesNotExist:
return None
|
python
|
{
"resource": ""
}
|
q15739
|
get_date_range_this_year
|
train
|
def get_date_range_this_year(now=None):
"""Return the starting and ending date of the current school year."""
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)
|
python
|
{
"resource": ""
}
|
q15740
|
user_attr
|
train
|
def user_attr(username, attribute):
"""Gets an attribute of the user with the given username."""
return getattr(User.objects.get(username=username), attribute)
|
python
|
{
"resource": ""
}
|
q15741
|
argument_request_user
|
train
|
def argument_request_user(obj, func_name):
"""Pass request.user as an argument to the given function call."""
func = getattr(obj, func_name)
request = threadlocals.request()
if request:
return func(request.user)
|
python
|
{
"resource": ""
}
|
q15742
|
senior_email_forward_view
|
train
|
def senior_email_forward_view(request):
"""Add a forwarding address for graduating seniors."""
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})
|
python
|
{
"resource": ""
}
|
q15743
|
dashes
|
train
|
def dashes(phone):
"""Returns the phone number formatted with dashes."""
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
|
python
|
{
"resource": ""
}
|
q15744
|
check_emerg
|
train
|
def check_emerg():
"""Fetch from FCPS' emergency announcement page.
URL defined in settings.FCPS_EMERGENCY_PAGE
Request timeout defined in settings.FCPS_EMERGENCY_TIMEOUT
"""
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
|
python
|
{
"resource": ""
}
|
q15745
|
get_emerg
|
train
|
def get_emerg():
"""Get the cached FCPS emergency page, or check it again.
Timeout defined in settings.CACHE_AGE["emerg"]
"""
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
|
python
|
{
"resource": ""
}
|
q15746
|
index_view
|
train
|
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."""
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)
|
python
|
{
"resource": ""
}
|
q15747
|
logout_view
|
train
|
def logout_view(request):
"""Clear the Kerberos cache and logout."""
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")
|
python
|
{
"resource": ""
}
|
q15748
|
LoginView.post
|
train
|
def post(self, request):
"""Validate and process the login POST request."""
"""Before September 1st, do not allow Class of [year+4] to log in."""
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 to eighth admin view (for eighthoffice)."""
default_next_page = "eighth_admin_dashboard"
# if request.user.is_eighthoffice:
# """Eighthoffice's session should (almost) never expire."""
# 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)
|
python
|
{
"resource": ""
}
|
q15749
|
MongoBackend._unescape
|
train
|
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.
'''
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
|
python
|
{
"resource": ""
}
|
q15750
|
MongoBackend._batch_key
|
train
|
def _batch_key(self, query):
'''
Get a unique id from a query.
'''
return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] )
|
python
|
{
"resource": ""
}
|
q15751
|
MongoBackend._batch_insert
|
train
|
def _batch_insert(self, inserts, intervals, **kwargs):
'''
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 )
|
python
|
{
"resource": ""
}
|
q15752
|
MongoBackend._insert_data
|
train
|
def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
'''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
|
python
|
{
"resource": ""
}
|
q15753
|
debug_toolbar_callback
|
train
|
def debug_toolbar_callback(request):
"""Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office."""
if request.is_ajax():
return False
if not hasattr(request, 'user'):
return False
if not request.user.is_authenticated:
return False
if not request.user.is_staff:
return False
if request.user.id == 9999:
return False
return "debug" in request.GET or settings.DEBUG
|
python
|
{
"resource": ""
}
|
q15754
|
register_calculator_view
|
train
|
def register_calculator_view(request):
"""Register a calculator."""
if request.method == "POST":
form = CalculatorRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added calculator.")
return redirect("itemreg")
else:
messages.error(request, "Error adding calculator.")
else:
form = CalculatorRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "calculator", "form_route": "itemreg_calculator"})
|
python
|
{
"resource": ""
}
|
q15755
|
register_computer_view
|
train
|
def register_computer_view(request):
"""Register a computer."""
if request.method == "POST":
form = ComputerRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added computer.")
return redirect("itemreg")
else:
messages.error(request, "Error adding computer.")
else:
form = ComputerRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "computer", "form_route": "itemreg_computer"})
|
python
|
{
"resource": ""
}
|
q15756
|
register_phone_view
|
train
|
def register_phone_view(request):
"""Register a phone."""
if request.method == "POST":
form = PhoneRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added phone.")
return redirect("itemreg")
else:
messages.error(request, "Error adding phone.")
else:
form = PhoneRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "phone", "form_route": "itemreg_phone"})
|
python
|
{
"resource": ""
}
|
q15757
|
setup
|
train
|
def setup(app):
"""Setup autodoc."""
# Fix for documenting models.FileField
from django.db.models.fields.files import FileDescriptor
FileDescriptor.__get__ = lambda self, *args, **kwargs: self
import django
django.setup()
app.connect('autodoc-skip-member', skip)
app.add_stylesheet('_static/custom.css')
|
python
|
{
"resource": ""
}
|
q15758
|
profile_view
|
train
|
def profile_view(request, user_id=None):
"""Displays a view of a user's profile.
Args:
user_id
The ID of the user whose profile is being viewed. If not
specified, show the user's own profile.
"""
if request.user.is_eighthoffice and "full" not in request.GET and user_id is not None:
return redirect("eighth_profile", user_id=user_id)
if user_id is not None:
try:
profile_user = User.objects.get(id=user_id)
if profile_user is None:
raise Http404
except User.DoesNotExist:
raise Http404
else:
profile_user = request.user
num_blocks = 6
eighth_schedule = []
start_block = EighthBlock.objects.get_first_upcoming_block()
blocks = []
if start_block:
blocks = [start_block] + list(start_block.next_blocks(num_blocks - 1))
for block in blocks:
sch = {"block": block}
try:
sch["signup"] = EighthSignup.objects.get(scheduled_activity__block=block, user=profile_user)
except EighthSignup.DoesNotExist:
sch["signup"] = None
except MultipleObjectsReturned:
client.captureException()
sch["signup"] = None
eighth_schedule.append(sch)
if profile_user.is_eighth_sponsor:
sponsor = EighthSponsor.objects.get(user=profile_user)
start_date = get_start_date(request)
eighth_sponsor_schedule = (EighthScheduledActivity.objects.for_sponsor(sponsor).filter(block__date__gte=start_date).order_by(
"block__date", "block__block_letter"))
eighth_sponsor_schedule = eighth_sponsor_schedule[:10]
else:
eighth_sponsor_schedule = None
admin_or_teacher = (request.user.is_eighth_admin or request.user.is_teacher)
can_view_eighth = (profile_user.can_view_eighth or request.user == profile_user)
eighth_restricted_msg = (not can_view_eighth and admin_or_teacher)
if not can_view_eighth and not request.user.is_eighth_admin and not request.user.is_teacher:
eighth_schedule = []
has_been_nominated = profile_user.username in [
u.nominee.username for u in request.user.nomination_votes.filter(position__position_name=settings.NOMINATION_POSITION)
]
context = {
"profile_user": profile_user,
"eighth_schedule": eighth_schedule,
"can_view_eighth": can_view_eighth,
"eighth_restricted_msg": eighth_restricted_msg,
"eighth_sponsor_schedule": eighth_sponsor_schedule,
"nominations_active": settings.NOMINATIONS_ACTIVE,
"nomination_position": settings.NOMINATION_POSITION,
"has_been_nominated": has_been_nominated
}
return render(request, "users/profile.html", context)
|
python
|
{
"resource": ""
}
|
q15759
|
picture_view
|
train
|
def picture_view(request, user_id, year=None):
"""Displays a view of a user's picture.
Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture.
"""
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
raise Http404
default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
if user is None:
raise Http404
else:
if year is None:
preferred = user.preferred_photo
if preferred is None:
data = user.default_photo
if data is None:
image_buffer = io.open(default_image_path, mode="rb")
else:
image_buffer = io.BytesIO(data)
# Exclude 'graduate' from names array
else:
data = preferred.binary
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
else:
grade_number = Grade.number_from_name(year)
if user.photos.filter(grade_number=grade_number).exists():
data = user.photos.filter(grade_number=grade_number).first().binary
else:
data = None
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
response = HttpResponse(content_type="image/jpeg")
response["Content-Disposition"] = "filename={}_{}.jpg".format(user_id, year or preferred)
try:
img = image_buffer.read()
except UnicodeDecodeError:
img = io.open(default_image_path, mode="rb").read()
image_buffer.close()
response.write(img)
return response
|
python
|
{
"resource": ""
}
|
q15760
|
SqlBackend.expire
|
train
|
def expire(self, name):
'''
Expire all the data.
'''
for interval,config in self._intervals.items():
if config['expire']:
# Because we're storing the bucket time, expiry has the same
# "skew" as whatever the buckets are.
expire_from = config['i_calc'].to_bucket(time.time() - config['expire'])
conn = self._client.connect()
conn.execute( self._table.delete().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time<=expire_from
)
))
|
python
|
{
"resource": ""
}
|
q15761
|
SqlGauge._update_data
|
train
|
def _update_data(self, name, value, timestamp, interval, config, conn):
'''Support function for insert. Should be called within a transaction'''
i_time = config['i_calc'].to_bucket(timestamp)
if not config['coarse']:
r_time = config['r_calc'].to_bucket(timestamp)
else:
r_time = None
stmt = self._table.update().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time==i_time,
self._table.c.r_time==r_time)
).values({self._table.c.value: value})
rval = conn.execute( stmt )
return rval.rowcount
|
python
|
{
"resource": ""
}
|
q15762
|
add_get_parameters
|
train
|
def add_get_parameters(url, parameters, percent_encode=True):
"""Utility function to add GET parameters to an existing URL.
Args:
parameters
A dictionary of the parameters that should be added.
percent_encode
Whether the query parameters should be percent encoded.
Returns:
The updated URL.
"""
url_parts = list(parse.urlparse(url))
query = dict(parse.parse_qs(url_parts[4]))
query.update(parameters)
if percent_encode:
url_parts[4] = parse.urlencode(query)
else:
url_parts[4] = "&".join([key + "=" + value for key, value in query.items()])
return parse.urlunparse(url_parts)
|
python
|
{
"resource": ""
}
|
q15763
|
mobile_app
|
train
|
def mobile_app(request):
"""Determine if the site is being displayed in a WebView from a native application."""
ctx = {}
try:
ua = request.META.get('HTTP_USER_AGENT', '')
if "IonAndroid: gcmFrame" in ua:
logger.debug("IonAndroid %s", request.user)
ctx["is_android_client"] = True
registered = "appRegistered:False" in ua
ctx["android_client_registered"] = registered
if request.user and request.user.is_authenticated:
"""Add/update NotificationConfig object."""
import binascii
import os
from intranet.apps.notifications.models import NotificationConfig
from datetime import datetime
ncfg, _ = NotificationConfig.objects.get_or_create(user=request.user)
if not ncfg.android_gcm_rand:
rand = binascii.b2a_hex(os.urandom(32))
ncfg.android_gcm_rand = rand
else:
rand = ncfg.android_gcm_rand
ncfg.android_gcm_time = datetime.now()
logger.debug("GCM random token generated: %s", rand)
ncfg.save()
ctx["android_client_rand"] = rand
else:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
except Exception:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
return ctx
|
python
|
{
"resource": ""
}
|
q15764
|
global_custom_theme
|
train
|
def global_custom_theme(request):
"""Add custom theme javascript and css."""
today = datetime.datetime.now().date()
theme = {}
if today.month == 3 and (14 <= today.day <= 16):
theme = {"css": "themes/piday/piday.css"}
return {"theme": theme}
|
python
|
{
"resource": ""
}
|
q15765
|
export_csv_action
|
train
|
def export_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
"""This function returns an export csv action.
'fields' and 'exclude' work like in django
ModelForm 'header' is whether or not to output the column names as the first row.
https://djangosnippets.org/snippets/2369/
"""
def export_as_csv(modeladmin, request, queryset):
"""Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
opts = modeladmin.model._meta
field_names = set([field.name for field in opts.fields])
if fields:
fieldset = set(fields)
field_names = field_names & fieldset
elif exclude:
excludeset = set(exclude)
field_names = field_names - excludeset
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
writer = csv.writer(response)
if header:
writer.writerow(list(field_names))
for obj in queryset:
writer.writerow([str(getattr(obj, field)) for field in field_names])
return response
export_as_csv.short_description = description
return export_as_csv
|
python
|
{
"resource": ""
}
|
q15766
|
Command.handle
|
train
|
def handle(self, **options):
"""Exported "eighth_activity_permissions" table in CSV format."""
perm_map = {}
with open('eighth_activity_permissions.csv', 'r') as absperms:
perms = csv.reader(absperms)
for row in perms:
aid, uid = row
try:
usr = User.objects.get(id=uid)
except User.DoesNotExist:
self.stdout.write("User {} doesn't exist, aid {}".format(uid, aid))
else:
if aid in perm_map:
perm_map[aid].append(usr)
else:
perm_map[aid] = [usr]
for aid in perm_map:
try:
act = EighthActivity.objects.get(id=aid)
except EighthActivity.DoesNotExist:
self.stdout.write("Activity {} doesn't exist".format(aid))
else:
self.stdout.write("{}: {}".format(aid, EighthActivity.objects.get(id=aid)))
grp, _ = Group.objects.get_or_create(name="{} -- Permissions".format("{}".format(act)[:55]))
users = perm_map[aid]
for u in users:
u.groups.add(grp)
u.save()
act.groups_allowed.add(grp)
act.save()
self.stdout.write("Done.")
|
python
|
{
"resource": ""
}
|
q15767
|
check_page_range
|
train
|
def check_page_range(page_range, max_pages):
"""Returns the number of pages in the range, or False if it is an invalid range."""
pages = 0
try:
for r in page_range.split(","): # check all ranges separated by commas
if "-" in r:
rr = r.split("-")
if len(rr) != 2: # make sure 2 values in range
return False
else:
rl = int(rr[0])
rh = int(rr[1])
# check in page range
if not 0 < rl < max_pages and not 0 < rh < max_pages:
return False
if rl > rh: # check lower bound <= upper bound
return False
pages += rh - rl + 1
else:
if not 0 < int(r) <= max_pages: # check in page range
return False
pages += 1
except ValueError: # catch int parse fail
return False
return pages
|
python
|
{
"resource": ""
}
|
q15768
|
request_announcement_email
|
train
|
def request_announcement_email(request, form, obj):
"""Send an announcement request email.
form: The announcement request form
obj: The announcement request object
"""
logger.debug(form.data)
teacher_ids = form.data["teachers_requested"]
if not isinstance(teacher_ids, list):
teacher_ids = [teacher_ids]
logger.debug(teacher_ids)
teachers = User.objects.filter(id__in=teacher_ids)
logger.debug(teachers)
subject = "News Post Confirmation Request from {}".format(request.user.full_name)
emails = []
for teacher in teachers:
emails.append(teacher.tj_email)
logger.debug(emails)
logger.info("%s: Announcement request to %s, %s", request.user, teachers, emails)
base_url = request.build_absolute_uri(reverse('index'))
data = {
"teachers": teachers,
"user": request.user,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("approve_announcement", args=[obj.id])),
"base_url": base_url
}
logger.info("%s: Announcement request %s", request.user, data)
email_send("announcements/emails/teacher_approve.txt", "announcements/emails/teacher_approve.html", data, subject, emails)
|
python
|
{
"resource": ""
}
|
q15769
|
admin_request_announcement_email
|
train
|
def admin_request_announcement_email(request, form, obj):
"""Send an admin announcement request email.
form: The announcement request form
obj: The announcement request object
"""
subject = "News Post Approval Needed ({})".format(obj.title)
emails = [settings.APPROVAL_EMAIL]
base_url = request.build_absolute_uri(reverse('index'))
data = {
"req": obj,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("admin_approve_announcement", args=[obj.id])),
"base_url": base_url
}
email_send("announcements/emails/admin_approve.txt", "announcements/emails/admin_approve.html", data, subject, emails)
|
python
|
{
"resource": ""
}
|
q15770
|
announcement_approved_email
|
train
|
def announcement_approved_email(request, obj, req):
"""Email the requested teachers and submitter whenever an administrator approves an announcement
request.
obj: the Announcement object
req: the AnnouncementRequest object
"""
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
""" Email to teachers who approved. """
teachers = req.teachers_approved.all()
teacher_emails = []
for u in teachers:
em = u.tj_email
if em:
teacher_emails.append(em)
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
if len(teacher_emails) > 0:
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "approved"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject, teacher_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(teacher_emails)))
""" Email to submitter. """
submitter = req.user
submitter_email = submitter.tj_email
if submitter_email:
submitter_emails = [submitter_email]
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "submitted"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject,
submitter_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(submitter_emails)))
|
python
|
{
"resource": ""
}
|
q15771
|
announcement_posted_email
|
train
|
def announcement_posted_email(request, obj, send_all=False):
"""Send a notification posted email.
obj: The announcement object
"""
if settings.EMAIL_ANNOUNCEMENTS:
subject = "Announcement: {}".format(obj.title)
if send_all:
users = User.objects.all()
else:
users = User.objects.filter(receive_news_emails=True)
send_groups = obj.groups.all()
emails = []
users_send = []
for u in users:
if len(send_groups) == 0:
# no groups, public.
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
else:
# specific to a group
user_groups = u.groups.all()
if any(i in send_groups for i in user_groups):
# group intersection exists
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
logger.debug(users_send)
logger.debug(emails)
if not settings.PRODUCTION and len(emails) > 3:
raise exceptions.PermissionDenied("You're about to email a lot of people, and you aren't in production!")
return
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
data = {"announcement": obj, "info_link": url, "base_url": base_url}
email_send_bcc("announcements/emails/announcement_posted.txt", "announcements/emails/announcement_posted.html", data, subject, emails)
messages.success(request, "Sent email to {} users".format(len(users_send)))
else:
logger.debug("Emailing announcements disabled")
|
python
|
{
"resource": ""
}
|
q15772
|
scoped_connection
|
train
|
def scoped_connection(func):
'''
Decorator that gives out connections.
'''
def _with(series, *args, **kwargs):
connection = None
try:
connection = series._connection()
return func(series, connection, *args, **kwargs)
finally:
series._return( connection )
return _with
|
python
|
{
"resource": ""
}
|
q15773
|
CassandraBackend._connection
|
train
|
def _connection(self):
'''
Return a connection from the pool
'''
try:
return self._pool.get(False)
except Empty:
args = [
self._host, self._port, self._keyspace
]
kwargs = {
'user' : None,
'password' : None,
'cql_version' : self._cql_version,
'compression' : self._compression,
'consistency_level' : self._consistency_level,
'transport' : self._transport,
}
if self._credentials:
kwargs['user'] = self._credentials['user']
kwargs['password'] = self._credentials['password']
return cql.connect(*args, **kwargs)
|
python
|
{
"resource": ""
}
|
q15774
|
CassandraBackend._insert_data
|
train
|
def _insert_data(self, connection, name, value, timestamp, interval, config):
'''Helper to insert data into cql.'''
cursor = connection.cursor()
try:
stmt = self._insert_stmt(name, value, timestamp, interval, config)
if stmt:
cursor.execute(stmt)
finally:
cursor.close()
|
python
|
{
"resource": ""
}
|
q15775
|
Event.show_fuzzy_date
|
train
|
def show_fuzzy_date(self):
"""Return whether the event is in the next or previous 2 weeks.
Determines whether to display the fuzzy date.
"""
date = self.time.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
if diff.days >= 14:
return False
else:
diff = date - datetime.now()
if diff.days >= 14:
return False
return True
|
python
|
{
"resource": ""
}
|
q15776
|
fuzzy_date
|
train
|
def fuzzy_date(date):
"""Formats a `datetime.datetime` object relative to the current time."""
date = date.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "{} minutes ago".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "{} hour{} ago".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "yesterday"
elif diff.days < 7:
return "{} days ago".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("last %A")
else:
return date.strftime("%A, %B %d, %Y")
else:
diff = date - datetime.now()
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "in {} minutes".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "in {} hour{}".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "tomorrow"
elif diff.days < 7:
return "in {} days".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("next %A")
else:
return date.strftime("%A, %B %d, %Y")
|
python
|
{
"resource": ""
}
|
q15777
|
render_page
|
train
|
def render_page(page, page_args):
""" Renders the template at page.template
"""
print(page_args)
template_name = page.template if page.template else page.name
template = "signage/pages/{}.html".format(template_name)
if page.function:
context_method = getattr(pages, page.function)
else:
context_method = getattr(pages, page.name)
sign, request = page_args
context = context_method(page, sign, request)
return render_to_string(template, context)
|
python
|
{
"resource": ""
}
|
q15778
|
announcement_posted_hook
|
train
|
def announcement_posted_hook(request, obj):
"""Runs whenever a new announcement is created, or a request is approved and posted.
obj: The Announcement object
"""
logger.debug("Announcement posted")
if obj.notify_post:
logger.debug("Announcement notify on")
announcement_posted_twitter(request, obj)
try:
notify_all = obj.notify_email_all
except AttributeError:
notify_all = False
try:
if notify_all:
announcement_posted_email(request, obj, True)
else:
announcement_posted_email(request, obj)
except Exception as e:
logger.error("Exception when emailing announcement: {}".format(e))
messages.error(request, "Exception when emailing announcement: {}".format(e))
raise e
else:
logger.debug("Announcement notify off")
|
python
|
{
"resource": ""
}
|
q15779
|
request_announcement_view
|
train
|
def request_announcement_view(request):
"""The request announcement page."""
if request.method == "POST":
form = AnnouncementRequestForm(request.POST)
logger.debug(form)
logger.debug(form.data)
if form.is_valid():
teacher_objs = form.cleaned_data["teachers_requested"]
logger.debug("teacher objs:")
logger.debug(teacher_objs)
if len(teacher_objs) > 2:
messages.error(request, "Please select a maximum of 2 teachers to approve this post.")
else:
obj = form.save(commit=True)
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
ann = AnnouncementRequest.objects.get(id=obj.id)
logger.debug(teacher_objs)
approve_self = False
for teacher in teacher_objs:
ann.teachers_requested.add(teacher)
if teacher == request.user:
approve_self = True
ann.save()
if approve_self:
ann.teachers_approved.add(teacher)
ann.save()
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, ann)
ann.admin_email_sent = True
ann.save()
return redirect("request_announcement_success_self")
else:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
request_announcement_email(request, form, obj)
return redirect("request_announcement_success")
return redirect("index")
else:
messages.error(request, "Error adding announcement request")
else:
form = AnnouncementRequestForm()
return render(request, "announcements/request.html", {"form": form, "action": "add"})
|
python
|
{
"resource": ""
}
|
q15780
|
approve_announcement_view
|
train
|
def approve_announcement_view(request, req_id):
"""The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.user not in requested_teachers:
messages.error(request, "You do not have permission to approve this announcement.")
return redirect("index")
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
obj = form.save(commit=True)
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
if "approve" in request.POST:
obj.teachers_approved.add(request.user)
obj.save()
if not obj.admin_email_sent:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, obj)
obj.admin_email_sent = True
obj.save()
return redirect("approve_announcement_success")
else:
obj.save()
return redirect("approve_announcement_reject")
form = AnnouncementRequestForm(instance=req)
context = {"form": form, "req": req, "admin_approve": False}
return render(request, "announcements/approve.html", context)
|
python
|
{
"resource": ""
}
|
q15781
|
admin_approve_announcement_view
|
train
|
def admin_approve_announcement_view(request, req_id):
"""The administrator approval announcement request page. Admins will view this page through the
UI.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
req = form.save(commit=True)
# SAFE HTML
req.content = safe_html(req.content)
if "approve" in request.POST:
groups = []
if "groups" in request.POST:
group_ids = request.POST.getlist("groups")
groups = Group.objects.filter(id__in=group_ids)
logger.debug(groups)
announcement = Announcement.objects.create(title=req.title, content=req.content, author=req.author, user=req.user,
expiration_date=req.expiration_date)
for g in groups:
announcement.groups.add(g)
announcement.save()
req.posted = announcement
req.posted_by = request.user
req.save()
announcement_approved_hook(request, announcement, req)
announcement_posted_hook(request, announcement)
messages.success(request, "Successfully approved announcement request. It has been posted.")
else:
req.rejected = True
req.rejected_by = request.user
req.save()
messages.success(request, "You did not approve this request. It will be hidden.")
return redirect("index")
form = AnnouncementRequestForm(instance=req)
all_groups = Group.objects.all()
context = {"form": form, "req": req, "admin_approve": True, "all_groups": all_groups}
return render(request, "announcements/approve.html", context)
|
python
|
{
"resource": ""
}
|
q15782
|
add_announcement_view
|
train
|
def add_announcement_view(request):
"""Add an announcement."""
if request.method == "POST":
form = AnnouncementForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
announcement_posted_hook(request, obj)
messages.success(request, "Successfully added announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
form = AnnouncementForm()
return render(request, "announcements/add_modify.html", {"form": form, "action": "add"})
|
python
|
{
"resource": ""
}
|
q15783
|
view_announcement_view
|
train
|
def view_announcement_view(request, id):
"""View an announcement.
id: announcement id
"""
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/view.html", {"announcement": announcement})
|
python
|
{
"resource": ""
}
|
q15784
|
modify_announcement_view
|
train
|
def modify_announcement_view(request, id=None):
"""Modify an announcement.
id: announcement id
"""
if request.method == "POST":
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(request.POST, instance=announcement)
if form.is_valid():
obj = form.save()
logger.debug(form.cleaned_data)
if "update_added_date" in form.cleaned_data and form.cleaned_data["update_added_date"]:
logger.debug("Update added date")
obj.added = timezone.now()
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
messages.success(request, "Successfully modified announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(instance=announcement)
context = {"form": form, "action": "modify", "id": id, "announcement": announcement}
return render(request, "announcements/add_modify.html", context)
|
python
|
{
"resource": ""
}
|
q15785
|
delete_announcement_view
|
train
|
def delete_announcement_view(request, id):
"""Delete an announcement.
id: announcement id
"""
if request.method == "POST":
post_id = None
try:
post_id = request.POST["id"]
except AttributeError:
post_id = None
try:
a = Announcement.objects.get(id=post_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(request, "Successfully deleted announcement.")
else:
a.expiration_date = datetime.datetime.now()
a.save()
messages.success(request, "Successfully expired announcement.")
except Announcement.DoesNotExist:
pass
return redirect("index")
else:
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/delete.html", {"announcement": announcement})
|
python
|
{
"resource": ""
}
|
q15786
|
show_announcement_view
|
train
|
def show_announcement_view(request):
""" Unhide an announcement that was hidden by the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model.
"""
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
announcement.user_map.users_hidden.remove(request.user)
announcement.user_map.save()
return http.HttpResponse("Unhidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED")
|
python
|
{
"resource": ""
}
|
q15787
|
hide_announcement_view
|
train
|
def hide_announcement_view(request):
""" Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model.
"""
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
try:
announcement.user_map.users_hidden.add(request.user)
announcement.user_map.save()
except IntegrityError:
logger.warning("Duplicate value when hiding announcement {} for {}.".format(announcement_id, request.user.username))
return http.HttpResponse("Hidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED")
|
python
|
{
"resource": ""
}
|
q15788
|
AuthenticateForm.is_valid
|
train
|
def is_valid(self):
"""Validates the username and password in the form."""
form = super(AuthenticateForm, self).is_valid()
for f, error in self.errors.items():
if f != "__all__":
self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error))})
else:
errors = list(error)
if "This account is inactive." in errors:
message = "Intranet access restricted"
else:
message = "Invalid password"
self.fields["password"].widget.attrs.update({"class": "error", "placeholder": message})
return form
|
python
|
{
"resource": ""
}
|
q15789
|
RedisBackend._calc_keys
|
train
|
def _calc_keys(self, config, name, timestamp):
'''
Calculate keys given a stat name and timestamp.
'''
i_bucket = config['i_calc'].to_bucket( timestamp )
r_bucket = config['r_calc'].to_bucket( timestamp )
i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket)
r_key = '%s:%s'%(i_key, r_bucket)
return i_bucket, r_bucket, i_key, r_key
|
python
|
{
"resource": ""
}
|
q15790
|
RedisBackend._batch_insert
|
train
|
def _batch_insert(self, inserts, intervals, **kwargs):
'''
Specialized batch insert
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
own_pipe = False
else:
pipe = self._client.pipeline(transaction=False)
kwargs['pipeline'] = pipe
own_pipe = True
ttl_batch = set()
for timestamp,names in inserts.iteritems():
for name,values in names.iteritems():
for value in values:
# TODO: support config param to flush the pipe every X inserts
self._insert( name, value, timestamp, intervals, ttl_batch=ttl_batch, **kwargs )
for ttl_args in ttl_batch:
pipe.expire(*ttl_args)
if own_pipe:
kwargs['pipeline'].execute()
|
python
|
{
"resource": ""
}
|
q15791
|
RedisBackend._insert
|
train
|
def _insert(self, name, value, timestamp, intervals, **kwargs):
'''
Insert the value.
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
else:
pipe = self._client.pipeline(transaction=False)
for interval,config in self._intervals.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
self._insert_data(name, value, tstamp, interval, config, pipe,
ttl_batch=kwargs.get('ttl_batch'))
if 'pipeline' not in kwargs:
pipe.execute()
|
python
|
{
"resource": ""
}
|
q15792
|
RedisBackend._insert_data
|
train
|
def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None):
'''Helper to insert data into redis'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
if expire and not ttl:
return
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
if config['coarse']:
self._type_insert(pipe, i_key, value)
else:
# Add the resolution bucket to the interval. This allows us to easily
# discover the resolution intervals within the larger interval, and
# if there is a cap on the number of steps, it will go out of scope
# along with the rest of the data
pipe.sadd(i_key, r_bucket)
self._type_insert(pipe, r_key, value)
if expire:
ttl_args = (i_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args)
if not config['coarse']:
ttl_args = (r_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args)
|
python
|
{
"resource": ""
}
|
q15793
|
RedisBackend.delete
|
train
|
def delete(self, name):
'''
Delete all the data in a named timeseries.
'''
keys = self._client.keys('%s%s:*'%(self._prefix,name))
pipe = self._client.pipeline(transaction=False)
for key in keys:
pipe.delete( key )
pipe.execute()
# Could be not technically the exact number of keys deleted, but is a close
# enough approximation
return len(keys)
|
python
|
{
"resource": ""
}
|
q15794
|
RedisBackend._get
|
train
|
def _get(self, name, interval, config, timestamp, **kws):
'''
Fetch a single interval from redis.
'''
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if config['coarse']:
data = process_row( fetch(self._client, i_key) )
rval[ config['i_calc'].from_bucket(i_bucket) ] = data
else:
# First fetch all of the resolution buckets for this set.
resolution_buckets = sorted(map(int,self._client.smembers(i_key)))
# Create a pipe and go fetch all the data for each.
# TODO: turn off transactions here?
pipe = self._client.pipeline(transaction=False)
for bucket in resolution_buckets:
r_key = '%s:%s'%(i_key, bucket) # TODO: make this the "resolution_bucket" closure?
fetch(pipe, r_key)
res = pipe.execute()
for idx,data in enumerate(res):
data = process_row(data)
rval[ config['r_calc'].from_bucket(resolution_buckets[idx]) ] = data
return rval
|
python
|
{
"resource": ""
}
|
q15795
|
RedisCount._type_insert
|
train
|
def _type_insert(self, handle, key, value):
'''
Insert the value into the series.
'''
if value!=0:
if isinstance(value,float):
handle.incrbyfloat(key, value)
else:
handle.incr(key,value)
|
python
|
{
"resource": ""
}
|
q15796
|
_choose_from_list
|
train
|
def _choose_from_list(options, question):
"""Choose an item from a list."""
message = ""
for index, value in enumerate(options):
message += "[{}] {}\n".format(index, value)
message += "\n" + question
def valid(n):
if int(n) not in range(len(options)):
raise ValueError("Not a valid option.")
else:
return int(n)
prompt(message, validate=valid, key="answer")
return env.answer
|
python
|
{
"resource": ""
}
|
q15797
|
runserver
|
train
|
def runserver(port=8080, debug_toolbar="yes", werkzeug="no", dummy_cache="no", short_cache="no", template_warnings="no", log_level="DEBUG",
insecure="no"):
"""Clear compiled python files and start the Django dev server."""
if not port or (not isinstance(port, int) and not port.isdigit()):
abort("You must specify a port.")
# clean_pyc()
yes_or_no = ("debug_toolbar", "werkzeug", "dummy_cache", "short_cache", "template_warnings", "insecure")
for s in yes_or_no:
if locals()[s].lower() not in ("yes", "no"):
abort("Specify 'yes' or 'no' for {} option.".format(s))
_log_levels = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
if log_level not in _log_levels:
abort("Invalid log level.")
with shell_env(SHOW_DEBUG_TOOLBAR=debug_toolbar.upper(), DUMMY_CACHE=dummy_cache.upper(), SHORT_CACHE=short_cache.upper(),
WARN_INVALID_TEMPLATE_VARS=template_warnings.upper(), LOG_LEVEL=log_level):
local("./manage.py runserver{} 0.0.0.0:{}{}".format("_plus" if werkzeug.lower() == "yes" else "", port, " --insecure"
if insecure.lower() == "yes" else ""))
|
python
|
{
"resource": ""
}
|
q15798
|
clear_sessions
|
train
|
def clear_sessions(venv=None):
"""Clear all sessions for all sandboxes or for production."""
if "VIRTUAL_ENV" in os.environ:
ve = os.path.basename(os.environ["VIRTUAL_ENV"])
else:
ve = ""
if venv is not None:
ve = venv
else:
ve = prompt("Enter the name of the "
"sandbox whose sessions you would like to delete, or "
"\"ion\" to clear production sessions:", default=ve)
c = "redis-cli -n {0} KEYS {1}:session:* | sed 's/\"^.*\")//g'"
keys_command = c.format(REDIS_SESSION_DB, ve)
keys = local(keys_command, capture=True)
count = 0 if keys.strip() == "" else keys.count("\n") + 1
if count == 0:
puts("No sessions to destroy.")
return 0
plural = "s" if count != 1 else ""
if not confirm("Are you sure you want to destroy {} {}" "session{}?".format(count, "production " if ve == "ion" else "", plural)):
return 0
if count > 0:
local("{0}| xargs redis-cli -n " "{1} DEL".format(keys_command, REDIS_SESSION_DB))
puts("Destroyed {} session{}.".format(count, plural))
|
python
|
{
"resource": ""
}
|
q15799
|
clear_cache
|
train
|
def clear_cache(input=None):
"""Clear the production or sandbox redis cache."""
if input is not None:
n = input
else:
n = _choose_from_list(["Production cache", "Sandbox cache"], "Which cache would you like to clear?")
if n == 0:
local("redis-cli -n {} FLUSHDB".format(REDIS_PRODUCTION_CACHE_DB))
else:
local("redis-cli -n {} FLUSHDB".format(REDIS_SANDBOX_CACHE_DB))
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.