_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...
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_act...
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(ke...
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: r...
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: ...
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() <=...
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. Sponso...
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.spe...
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 ...
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: retur...
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: ...
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...
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(): ...
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.ca...
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 ...
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.can...
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() # ...
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 e...
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: ...
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(...
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 >...
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 va...
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....
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:])) el...
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...
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("Returni...
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() ...
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]) retur...
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_vie...
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 isins...
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, inte...
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 foll...
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 Fal...
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() mes...
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....
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(r...
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('_stat...
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 ...
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. """ ...
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() ...
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...
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. R...
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_c...
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://djangos...
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: ...
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...
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): teach...
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 = re...
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 productio...
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: ...
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' ...
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:...
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 ...
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) els...
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_twit...
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"...
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....
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_req...
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 = saf...
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...
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.ob...
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("announ...
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") ...
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...
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...
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...
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._normali...
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_...
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...
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 = Order...
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("N...
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()): ...
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 " ...
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_PROD...
python
{ "resource": "" }