code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Get the interval.
'''
i_bucket = config['i_calc'].to_bucket(timestamp)
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
query = {'name':name, 'interval':i_bucket}
if config['coarse']:
if fetch:
record = fetch( ... | def _get(self, name, interval, config, timestamp, **kws) | Get the interval. | 3.831485 | 3.690951 | 1.038075 |
'''
Fetch a series of buckets.
'''
# make a copy of the buckets because we're going to mutate it
buckets = list(buckets)
rval = OrderedDict()
step = config['step']
resolution = config.get('resolution',step)
fetch = kws.get('fetch')
process_row = kws.get('process_row', self._proce... | def _series(self, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 3.630885 | 3.523831 | 1.03038 |
'''
Delete time series by name across all intervals. Returns the number of
records deleted.
'''
# TODO: confirm that this does not use the combo index and determine
# performance implications.
num_deleted = 0
for interval,config in self._intervals.items():
# TODO: use write prefere... | def delete(self, name) | Delete time series by name across all intervals. Returns the number of
records deleted. | 11.156181 | 8.186248 | 1.362795 |
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... | def debug_toolbar_callback(request) | Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office. | 2.799552 | 2.723675 | 1.027858 |
return Announcement.objects.filter(
Q(groups__in=user.groups.all()) | Q(groups__isnull=True) | Q(announcementrequest__teachers_requested=user) |
Q(announcementrequest__user=user) | Q(user=user)).distinct() | def visible_to_user(self, user) | Get a list of visible announcements for a given user (usually request.user).
These visible announcements will be those that either have no
groups assigned to them (and are therefore public) or those in
which the user is a member.
Apparently this .filter() call occasionally returns dupl... | 5.091147 | 3.506516 | 1.45191 |
ids = user.announcements_hidden.all().values_list("announcement__id")
return Announcement.objects.filter(id__in=ids) | def hidden_announcements(self, user) | Get a list of announcements marked as hidden for a given user (usually request.user).
These are all announcements visible to the user -- they have just decided to
hide them. | 4.359414 | 4.019605 | 1.084538 |
start_date, end_date = get_date_range_this_year()
return Announcement.objects.filter(added__gte=start_date, added__lte=end_date) | def this_year(self) | Get AnnouncementRequests from this school year only. | 4.288083 | 3.18933 | 1.344509 |
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.")
... | def register_calculator_view(request) | Register a calculator. | 2.536345 | 2.507692 | 1.011426 |
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.")
re... | def register_computer_view(request) | Register a computer. | 2.589406 | 2.569836 | 1.007616 |
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 r... | def register_phone_view(request) | Register a phone. | 2.599176 | 2.548756 | 1.019782 |
# 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') | def setup(app) | Setup autodoc. | 4.501891 | 4.402749 | 1.022518 |
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... | 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. | 2.695166 | 2.738291 | 0.984251 |
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.pre... | 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. | 2.470236 | 2.435435 | 1.01429 |
if not (request.user.is_eighth_admin or request.user.is_teacher):
return render(request, "error/403.html", {"reason": "You do not have permission to view statistics for this activity."}, status=403)
activity = get_object_or_404(EighthActivity, id=activity_id)
if request.GET.get("print", False... | def stats_view(request, activity_id=None) | If a the GET parameter `year` is set, it uses stats from given year
with the following caveats:
- If it's the current year and start_date is set, start_date is ignored
- If it's the current year, stats will only show up to today - they won't
go into the future.
`all... | 2.595032 | 2.58023 | 1.005737 |
'''
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'])
... | def expire(self, name) | Expire all the data. | 8.111815 | 7.637103 | 1.062159 |
'''
Get the interval.
'''
i_bucket = config['i_calc'].to_bucket(timestamp)
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if fetch:
data = fetch( self._client.connect(), self._table, name, interval, i_bucket )
else:
... | def _get(self, name, interval, config, timestamp, **kws) | Get the interval. | 4.27075 | 4.087893 | 1.044731 |
'''
Delete time series by name across all intervals. Returns the number of
records deleted.
'''
conn = self._client.connect()
conn.execute( self._table.delete().where(self._table.c.name==name) ) | def delete(self, name) | Delete time series by name across all intervals. Returns the number of
records deleted. | 7.304821 | 4.24768 | 1.71972 |
'''Helper to insert data into sql.'''
kwargs = {
'name' : name,
'interval' : interval,
'insert_time' : time.time(),
'i_time' : config['i_calc'].to_bucket(timestamp),
'value' : value
}
if not config['coarse']:
kwargs['r_time'] = config['r_calc'].to... | def _insert_data(self, name, value, timestamp, interval, config, **kwargs) | Helper to insert data into sql. | 4.768992 | 4.506093 | 1.058343 |
'''Helper to insert data into sql.'''
conn = self._client.connect()
if not self._update_data(name, value, timestamp, interval, config, conn):
try:
kwargs = {
'name' : name,
'interval' : interval,
'i_time' : config['i_calc'].to_bucket(timestamp),
... | def _insert_data(self, name, value, timestamp, interval, config, **kwargs) | Helper to insert data into sql. | 4.153696 | 4.009569 | 1.035946 |
'''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==n... | def _update_data(self, name, value, timestamp, interval, config, conn) | Support function for insert. Should be called within a transaction | 3.881883 | 3.279669 | 1.18362 |
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... | 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. | 1.675819 | 1.901115 | 0.881492 |
categories = [(r"^/$", "dashboard"), (r"^/announcements", "dashboard"), (r"^/eighth/admin", "eighth_admin"), (r"^/eighth", "eighth"),
(r"^/events", "events"), (r"^/files", "files"), (r"^/printing", "printing"), (r"^/groups", "groups"), (r"^/polls", "polls"),
(r"^/board", "b... | def nav_categorizer(request) | Determine which top-level nav category (left nav) a request
falls under | 3.300526 | 3.177298 | 1.038784 |
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"... | def mobile_app(request) | Determine if the site is being displayed in a WebView from a native application. | 3.642903 | 3.639427 | 1.000955 |
today = datetime.datetime.now().date()
theme = {}
if today.month == 3 and (14 <= today.day <= 16):
theme = {"css": "themes/piday/piday.css"}
return {"theme": theme} | def global_custom_theme(request) | Add custom theme javascript and css. | 6.648963 | 6.715431 | 0.990102 |
return {'show_homecoming': settings.HOCO_START_DATE < datetime.date.today() and datetime.date.today() < settings.HOCO_END_DATE} | def show_homecoming(request) | Show homecoming ribbon / scores | 5.594386 | 5.544635 | 1.008973 |
def export_as_csv(modeladmin, request, queryset):
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 ... | 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/ | 1.708978 | 1.673699 | 1.021079 |
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:
... | def handle(self, **options) | Exported "eighth_activity_permissions" table in CSV format. | 2.800086 | 2.455642 | 1.140266 |
start_date, end_date = get_date_range_this_year()
return self.filter(start_time__gte=start_date, start_time__lte=end_date) | def this_year(self) | Get AnnouncementRequests from this school year only. | 3.441342 | 2.837542 | 1.21279 |
return Poll.objects.filter(Q(groups__in=user.groups.all()) | Q(groups__isnull=True)) | def visible_to_user(self, user) | Get a list of visible polls for a given user (usually request.user).
These visible polls will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. | 5.738325 | 3.18837 | 1.799767 |
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]... | def check_page_range(page_range, max_pages) | Returns the number of pages in the range, or False if it is an invalid range. | 2.860061 | 2.673702 | 1.069701 |
if not request.user.is_student:
return redirect("index")
# context = {"first_login": request.session["first_login"] if "first_login" in request.session else False}
# return render(request, "welcome/old_student.html", context)
return dashboard_view(request, show_welcome=True) | def student_welcome_view(request) | Welcome/first run page for students. | 3.84794 | 3.909785 | 0.984182 |
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... | def request_announcement_email(request, form, obj) | Send an announcement request email.
form: The announcement request form
obj: The announcement request object | 3.015193 | 2.979177 | 1.012089 |
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", ... | def admin_request_announcement_email(request, form, obj) | Send an admin announcement request email.
form: The announcement request form
obj: The announcement request object | 4.215709 | 4.30416 | 0.97945 |
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
teachers = req.teachers_approved.all()
teacher_emails = []
for u in teachers:
em = u.tj_email
... | 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 | 2.594965 | 2.501858 | 1.037215 |
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 = [... | def announcement_posted_email(request, obj, send_all=False) | Send a notification posted email.
obj: The announcement object | 3.082051 | 3.105877 | 0.992329 |
text = get_template(text_template)
html = get_template(html_template)
text_content = text.render(data)
html_content = html.render(data)
subject = settings.EMAIL_SUBJECT_PREFIX + subject
headers = {} if headers is None else headers
msg = EmailMultiAlternatives(subject, text_content, set... | def email_send(text_template, html_template, data, subject, emails, headers=None) | Send an HTML/Plaintext email with the following fields.
text_template: URL to a Django template for the text email's contents
html_template: URL to a Django tempalte for the HTML email's contents
data: The context to pass to the templates
subject: The subject of the email
emails: The addresses to s... | 2.00558 | 2.065724 | 0.970885 |
try:
field = self.fields[name]
except KeyError:
raise KeyError("Key %r not found in '%s'" % (name, self.__class__.__name__))
return BoundField(self, field, name) | def field_(self, name) | From https://github.com/halfnibble/django-underscore-filters
Get a form field starting with _.
Taken near directly from Django > forms.
Returns a BoundField with the given name. | 3.387937 | 2.906827 | 1.16551 |
'''
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 | def scoped_connection(func) | Decorator that gives out connections. | 6.446458 | 4.399168 | 1.465381 |
'''
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_versi... | def _connection(self) | Return a connection from the pool | 2.855349 | 2.57977 | 1.106823 |
'''
Insert the new value.
'''
if self._value_type in QUOTE_TYPES and not QUOTE_MATCH.match(value):
value = "'%s'"%(value)
for interval,config in self._intervals.items():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
self._i... | def _insert(self, name, value, timestamp, intervals, **kwargs) | Insert the new value. | 5.22236 | 4.90844 | 1.063955 |
'''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() | def _insert_data(self, connection, name, value, timestamp, interval, config) | Helper to insert data into cql. | 4.115893 | 3.169132 | 1.298745 |
'''
Fetch a series of buckets.
'''
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if fetch:
data = fetch( connection, self._table, name, interval, buckets )
else:
data = self._type_get(name, interval, buckets[0], buck... | def _series(self, connection, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 2.866827 | 2.73692 | 1.047464 |
'''Helper to generate the insert statement.'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
if expire and not ttl:
return None
i_time = config['i_calc'].to_bucket(timestamp)
if not config['coarse']:
r_time = config... | def _insert_stmt(self, name, value, timestamp, interval, config) | Helper to generate the insert statement. | 5.150522 | 4.986388 | 1.032916 |
return (Event.objects.filter(approved=True).filter(Q(groups__in=user.groups.all()) | Q(groups__isnull=True) | Q(user=user))) | def visible_to_user(self, user) | Get a list of visible events for a given user (usually request.user).
These visible events will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. | 5.08454 | 3.369342 | 1.50906 |
ids = user.events_hidden.all().values_list("event__id")
return Event.objects.filter(id__in=ids) | def hidden_events(self, user) | Get a list of events marked as hidden for a given user (usually request.user).
These are all events visible to the user -- they have just decided to
hide them. | 4.462564 | 4.562928 | 0.978004 |
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
ret... | def show_fuzzy_date(self) | Return whether the event is in the next or previous 2 weeks.
Determines whether to display the fuzzy date. | 2.952812 | 2.675376 | 1.1037 |
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 "... | def fuzzy_date(date) | Formats a `datetime.datetime` object relative to the current time. | 1.581689 | 1.554592 | 1.01743 |
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... | def render_page(page, page_args) | Renders the template at page.template | 3.874441 | 3.739832 | 1.035993 |
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 not... | def announcement_posted_hook(request, obj) | Runs whenever a new announcement is created, or a request is approved and posted.
obj: The Announcement object | 2.972195 | 3.141587 | 0.946081 |
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... | def request_announcement_view(request) | The request announcement page. | 2.846394 | 2.849417 | 0.998939 |
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(... | 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 | 2.549066 | 2.534003 | 1.005944 |
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... | 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 | 2.499067 | 2.524252 | 0.990022 |
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()
announc... | def add_announcement_view(request) | Add an announcement. | 2.587851 | 2.519349 | 1.02719 |
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/view.html", {"announcement": announcement}) | def view_announcement_view(request, id) | View an announcement.
id: announcement id | 1.980157 | 2.250952 | 0.879698 |
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.cleane... | def modify_announcement_view(request, id=None) | Modify an announcement.
id: announcement id | 2.059318 | 2.086924 | 0.986772 |
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()... | def delete_announcement_view(request, id) | Delete an announcement.
id: announcement id | 2.091582 | 2.119523 | 0.986817 |
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()
... | 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. | 2.896885 | 2.544947 | 1.138289 |
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_... | 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. | 2.820324 | 2.737162 | 1.030383 |
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)
... | def is_valid(self) | Validates the username and password in the form. | 3.924408 | 3.642652 | 1.077349 |
'''
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_buc... | def _calc_keys(self, config, name, timestamp) | Calculate keys given a stat name and timestamp. | 4.242075 | 3.522103 | 1.204415 |
'''
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()... | def _batch_insert(self, inserts, intervals, **kwargs) | Specialized batch insert | 4.998303 | 4.806277 | 1.039953 |
'''
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 ... | def _insert(self, name, value, timestamp, intervals, **kwargs) | Insert the value. | 4.4439 | 4.262599 | 1.042533 |
'''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']:
se... | def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None) | Helper to insert data into redis | 4.726976 | 4.773969 | 0.990157 |
'''
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... | def delete(self, name) | Delete all the data in a named timeseries. | 6.644253 | 5.381636 | 1.234616 |
'''
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... | def _get(self, name, interval, config, timestamp, **kws) | Fetch a single interval from redis. | 5.248916 | 4.884436 | 1.074621 |
'''
Fetch a series of buckets.
'''
pipe = self._client.pipeline(transaction=False)
step = config['step']
resolution = config.get('resolution',step)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
for inter... | def _series(self, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 3.729472 | 3.621986 | 1.029676 |
'''
Insert the value into the series.
'''
if value!=0:
if isinstance(value,float):
handle.incrbyfloat(key, value)
else:
handle.incr(key,value) | def _type_insert(self, handle, key, value) | Insert the value into the series. | 6.539765 | 5.167148 | 1.265643 |
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(me... | def _choose_from_list(options, question) | Choose an item from a list. | 4.113002 | 3.9517 | 1.040819 |
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"... | 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. | 3.076589 | 3.054615 | 1.007193 |
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 "
"\... | def clear_sessions(venv=None) | Clear all sessions for all sandboxes or for production. | 4.789537 | 4.439146 | 1.078932 |
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(REDI... | def clear_cache(input=None) | Clear the production or sandbox redis cache. | 3.919778 | 3.121404 | 1.255774 |
if local("pwd", capture=True) == PRODUCTION_DOCUMENT_ROOT:
abort("Refusing to automatically load fixtures into production database!")
if not confirm("Are you sure you want to load all fixtures? This could have unintended consequences if the database is not empty."):
abort("Aborted.")
... | def load_fixtures() | Populate a database with data from fixtures. | 4.384126 | 4.384146 | 0.999995 |
_require_root()
if not confirm("This will apply any available migrations to the database. Has the database been backed up?"):
abort("Aborted.")
if not confirm("Are you sure you want to deploy?"):
abort("Aborted.")
with lcd(PRODUCTION_DOCUMENT_ROOT):
with shell_env(PRODUCTI... | def deploy() | Deploy to production. | 4.353025 | 4.230963 | 1.02885 |
if app is None:
abort("No app name given.")
local("./manage.py migrate {} --fake".format(app))
local("./manage.py migrate {}".format(app)) | def forcemigrate(app=None) | Force migrations to apply for a given app. | 6.282579 | 5.400341 | 1.163367 |
results = User.objects.filter(student_id=student_id)
if len(results) == 1:
return results.first()
return None | def user_with_student_id(self, student_id) | Get a unique user object by FCPS student ID. (Ex. 1624472) | 2.865819 | 2.576452 | 1.112312 |
if isinstance(student_id, str) and not student_id.isdigit():
return None
results = User.objects.filter(id=student_id)
if len(results) == 1:
return results.first()
return None | def user_with_ion_id(self, student_id) | Get a unique user object by Ion ID. (Ex. 489) | 2.888205 | 2.614371 | 1.104742 |
results = []
if sn and not given_name:
results = User.objects.filter(last_name=sn)
elif given_name:
query = {'first_name': given_name}
if sn:
query['last_name'] = sn
results = User.objects.filter(**query)
if l... | def user_with_name(self, given_name=None, sn=None) | Get a unique user object by given name (first/nickname and last). | 2.587249 | 2.459547 | 1.051921 |
users = User.objects.filter(properties___birthday__month=month, properties___birthday__day=day)
results = []
for user in users:
# TODO: permissions system
results.append(user)
return results | def users_with_birthday(self, month, day) | Return a list of user objects who have a birthday on a given date. | 4.96335 | 4.453869 | 1.114391 |
users = User.objects.filter(user_type="student", graduation_year__gte=settings.SENIOR_GRADUATION_YEAR)
users = users.exclude(id__in=EXTRA)
return users | def get_students(self) | Get user objects that are students (quickly). | 7.044644 | 6.063632 | 1.161786 |
users = User.objects.filter(user_type="teacher")
users = users.exclude(id__in=EXTRA)
# Add possible exceptions handling here
users = users | User.objects.filter(id__in=[31863, 32327, 32103, 33228])
return users | def get_teachers(self) | Get user objects that are teachers (quickly). | 7.654307 | 7.124785 | 1.074321 |
teachers = self.get_teachers()
teachers = [(u.last_name, u.first_name, u.id) for u in teachers]
for t in teachers:
if t is None or t[0] is None or t[1] is None or t[2] is None:
teachers.remove(t)
for t in teachers:
if t[0] is None or len(t... | def get_teachers_sorted(self) | Get teachers sorted by last name.
This is used for the announcement request page. | 2.58558 | 2.561136 | 1.009544 |
if isinstance(group, Group):
group = group.name
return self.groups.filter(name=group).exists() | def member_of(self, group) | Returns whether a user is a member of a certain group.
Args:
group
The name of a group (string) or a group object
Returns:
Boolean | 3.852734 | 4.886926 | 0.788376 |
return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "") | def last_first(self) | Return a name in the format of:
Lastname, Firstname [(Nickname)] | 4.572806 | 2.944182 | 1.553167 |
return ("{}{} ".format(self.last_name, ", " + self.first_name if self.first_name else "") + ("({}) ".format(self.nickname)
if self.nickname else "") +
("({})".format(self.student_id if s... | def last_first_id(self) | Return a name in the format of:
Lastname, Firstname [(Nickname)] (Student ID/ID/Username) | 5.077783 | 3.390174 | 1.497794 |
return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname)
if self.nickname else "")) | def last_first_initial(self) | Return a name in the format of:
Lastname, F [(Nickname)] | 5.900945 | 4.102404 | 1.438412 |
for email in self.emails.all():
if email.address.endswith(("@fcps.edu", "@tjhsst.edu")):
return email
if self.is_teacher:
domain = "fcps.edu"
else:
domain = "tjhsst.edu"
return "{}@{}".format(self.username, domain) | def tj_email(self) | Get (or guess) a user's TJ email.
If a fcps.edu or tjhsst.edu email is specified in their email
list, use that. Otherwise, append the user's username to the
proper email suffix, depending on whether they are a student or
teacher. | 4.997909 | 2.806064 | 1.78111 |
preferred = self.preferred_photo
if preferred is not None:
return preferred.binary
if preferred is None:
if self.user_type == "teacher":
current_grade = 12
else:
current_grade = int(self.grade)
if curre... | def default_photo(self) | Returns default photo (in binary) that should be used
Returns:
Binary data | 3.787372 | 3.686406 | 1.027389 |
# TODO: optimize this, it's kind of a bad solution for listing a mostly
# static set of files.
# We could either add a permissions dict as an attribute or cache this
# in some way. Creating a dict would be another place we have to define
# the permission, so I'm not a hu... | def permissions(self) | Dynamically generate dictionary of privacy options | 7.195666 | 6.937486 | 1.037215 |
try:
# threadlocals is a module, not an actual thread locals object
request = threadlocals.request()
if request is None:
return False
requesting_user = request.user
if isinstance(requesting_user, AnonymousUser) or not requestin... | def _current_user_override(self) | Return whether the currently logged in user is a teacher, and can view all of a student's
information regardless of their privacy settings. | 4.932723 | 4.42706 | 1.114221 |
date = datetime.today().date()
b = self.birthday
if b:
return int((date - b).days / 365)
return None | def age(self) | Returns a user's age, based on their birthday.
Returns:
integer | 5.445366 | 6.308296 | 0.863207 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSponsor
return EighthSponsor.objects.filter(user=self).exists() | def is_eighth_sponsor(self) | Determine whether the given user is associated with an.
:class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity
sponsoring information. | 10.267078 | 6.462948 | 1.588606 |
key = "{}:frequent_signups".format(self.username)
cached = cache.get(key)
if cached:
return cached
freq_signups = self.eighthsignup_set.exclude(scheduled_activity__activity__administrative=True).exclude(
scheduled_activity__activity__special=True).exclude... | def frequent_signups(self) | Return a QuerySet of activity id's and counts for the activities that a given user
has signed up for more than `settings.SIMILAR_THRESHOLD` times | 3.436193 | 2.860965 | 1.201061 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSponsor
try:
sp = EighthSponsor.objects.get(user=self)
except EighthSponsor.DoesNotExist:
return False
return sp | def get_eighth_sponsor(self) | Return the :class:`intranet.apps.eighth.models.EighthSponsor` that a given user is
associated with. | 6.191461 | 4.344767 | 1.425039 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True).count() | def absence_count(self) | Return the user's absence count.
If the user has no absences
or is not a signup user, returns 0. | 17.940636 | 14.637687 | 1.225647 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True) | def absence_info(self) | Return information about the user's absences. | 21.744503 | 20.108152 | 1.081377 |
from intranet.apps.eighth.models import EighthScheduledActivity
EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update(
archived_member_count=F('archived_member_count')+1) | def handle_delete(self) | Handle a graduated user being deleted. | 9.617333 | 7.775703 | 1.236844 |
try:
if not getattr(self, 'parent_{}'.format(permission)) and not parent and not admin:
return False
level = 'parent' if parent else 'self'
setattr(self, '{}_{}'.format(level, permission), value)
# Set student permission to false if paren... | def set_permission(self, permission, value, parent=False, admin=False) | Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful. | 3.394343 | 3.358478 | 1.010679 |
try:
# threadlocals is a module, not an actual thread locals object
request = threadlocals.request()
if request and request.user and request.user.is_authenticated:
requesting_user_id = request.user.id
return str(requesting_user_id) == ... | def is_http_request_sender(self) | Checks if a user the HTTP request sender (accessing own info)
Used primarily to load private personal information from the
cache. (A student should see all info on his or her own profile
regardless of how the permissions are set.)
Returns:
Boolean | 4.27975 | 4.380775 | 0.976939 |
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student) or (self.is_http_request_sender() or self._current_user_override())
except Exception:
logger.error("Could... | def attribute_is_visible(self, permission) | Checks privacy options to see if an attribute is visible to public | 7.272315 | 7.033591 | 1.033941 |
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student)
except Exception:
logger.error("Could not retrieve permissions for {}".format(permission)) | def attribute_is_public(self, permission) | Checks if attribute is visible to public (regardless of admins status) | 5.265708 | 4.97392 | 1.058664 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.