예제 #1
0
def grade_json(request, grade_ids):
    try:
        cache_key = 'grade_json_new ' + str(grade_ids)
        cached = cache.get(cache_key)
        if cached:
            print('Cache Hit in grade_json ' + grade_ids)
            return render_to_json(cached)
        actual_total = 0
        rtn = {}
        grade_ids = grade_ids.split('&')
        sections = Grade.objects.filter(id__in=grade_ids)
        course = Course.objects.get(id=sections.values_list('course', flat=True)[0])
        percentile_total = sections.aggregate(Sum('graded_total'))['graded_total__sum']

        percentile_ceiling = 0
        total_unweighted = 0
        for grade, display in STANDARD_GRADES:
            grade_entry = {}
            if grade == 'd':
                numerator = sum([sections.aggregate(Sum(d)).get(d + '__sum', 0) for d in ('d1', 'd2', 'd3')])
            else:
                numerator = sections.aggregate(Sum(grade)).get(grade + '__sum', 0)
            actual_total += numerator
            percent = numerator / percentile_total if percentile_total > 0 else 0.0
            grade_entry['percent'] = round(percent, 2)
            grade_entry['numerator'] = numerator
            if grade == 'p' or grade == 'np':
                grade_entry['percentile_high'] = 0
                grade_entry['percentile_low'] = 0
                total_unweighted += numerator
            else:
                grade_entry['percentile_high'] = abs(round(1.0 - percentile_ceiling, 2))
                grade_entry['percentile_low'] = abs(round(1.0 - percentile_ceiling - percent, 2))
            percentile_ceiling += percent
            rtn[display] = grade_entry
        rtn['course_id'] = course.id
        rtn['title'] = course.abbreviation + ' ' + course.course_number
        rtn['subtitle'] = course.title
        rtn['course_gpa'] = round(course.grade_average, 3)
        rtn['course_letter'] = course.letter_average
        weighted_letter_grade_counter, total = add_up_grades(sections)
        if total == 0:
            rtn['section_gpa'] = -1
            rtn['section_letter'] = 'N/A'
        else:
            rtn['section_gpa'] = round(float(sum(weighted_letter_grade_counter.values())) / total, 3)
            rtn['section_letter'] = gpa_to_letter_grade(rtn['section_gpa'])
        rtn['denominator'] = total + total_unweighted

        if rtn['course_letter'] == '':
            rtn['course_letter'] = 'N/A'

        if rtn['section_letter'] == '':
            rtn['section_letter'] = 'N/A'

        cache.set(cache_key, rtn, CACHE_TIMEOUT)
        return render_to_json(rtn)
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()
예제 #2
0
def filter(request):
    """Filter something."""
    try:
        if request.method == 'GET':
            course_id = request.GET.get('course_id')
            if course_id:
                course = courses_to_json(Course.objects.filter(pk=course_id))
                if course:
                    return render_to_json(course)
                raise Http404
            filter_ids = request.GET['filters'].strip(',').split(',')
            unioned = list(
                set(
                    Playlist.objects.filter(id__in=filter_ids).values_list(
                        'category', flat=True)))
            for index, category in enumerate(unioned):
                unioned[index] = union_by_category(category, filter_ids)

            if unioned:
                courses = reduce(lambda x, y: x & y, unioned).distinct()
                return render_to_json(courses_to_json(courses))
            return render_to_empty_json()
        else:
            raise Http404
    except Exception as e:
        print(e)
        return render_to_empty_json()
예제 #3
0
def enrollment_section_render(request, course_id):
    try:
        cached = cache.get('enrollment_section_render_new ' + course_id)
        if cached:
            print('Cache Hit in enrollment_section_render with course_id ' +
                  course_id)
            prefetch(course_id)
            return render_to_json(cached)
        semesters = {}
        if TELEBEARS_ALREADY_STARTED:
            semesters[(CURRENT_SEMESTER, CURRENT_YEAR)] = 0
        for sem in reversed(PAST_SEMESTERS):
            semesters[(sem['semester'], sem['year'])] = len(semesters)

        all_sections = Section.objects.filter(
            course_id=course_id,
            disabled=False,
            is_primary=True,
        )

        sem_to_sections = {}
        for sect in all_sections:
            if sect.enrolled is None or (sect.semester,
                                         sect.year) not in semesters:
                continue

            if (sect.semester, sect.year) not in sem_to_sections:
                sem_to_sections[(sect.semester, sect.year)] = {
                    'semester': sect.semester,
                    'year': sect.year,
                    'sections': []
                }

            sem_to_sections[(sect.semester, sect.year)]['sections'].append({
                'section_number':
                sect.section_number,
                'section_id':
                sect.id,
                'instructor':
                sect.instructor,
            })

        rtn = sorted(sem_to_sections.values(),
                     key=lambda sect: semesters[
                         (sect['semester'], sect['year'])])

        cache.set('enrollment_section_render_new ' + str(course_id), rtn,
                  CACHE_TIMEOUT)
        prefetch(course_id)
        return render_to_json(rtn)
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()
예제 #4
0
def course_box_json(request):
    """Render the HTML for a course box."""
    try:
        course = Course.objects.get(id=request.GET.get('course_id'))

        semester = request.GET.get('semester', CURRENT_SEMESTER)
        year = request.GET.get('year', CURRENT_YEAR)
        sections = Section.objects.filter(
            course_id=course.id, semester=semester, year=year,
            disabled=False).order_by('section_number')

        return render_to_json({
            'course':
            course.as_json(),
            'sections':
            list(map(lambda s: s.as_json(), sections)),
            'requirements':
            all_requirements(course),  # Backwards-compatible
            # 'universal_requirements': universal_requirements(course),  # Enable when ready
            # 'requirements_by_semester': semester_requirements(course),  # Enable when ready
            'last_enrollment_update':
            get_last_enrollment_update(sections),
        })

    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()
예제 #5
0
def grade_section_json(request, course_id):
    """
    {'instructor': 'Shewchuk', 'semester': 'spring', 'year': 2012, 'section_number': '003', 'grade_id': 1533}
    """
    try:
        cached = cache.get('grade_section_json_new ' + str(course_id))
        if cached:
            print('Cache Hit in grade_section_json course_id ' + course_id)
            return render_to_json(cached)
        sections = [
            {
                'instructor': entry.instructor,
                'semester': entry.semester,
                'year': entry.year,
                'section_number': entry.section_number,
                'grade_id': entry.id,
            } for entry in Grade.objects.filter(course__id=int(course_id))
        ]
        sections = sorted(sections, key=year_and_semester_to_value, reverse=True)
        cache.set('grade_section_json_new ' + str(course_id), sections, CACHE_TIMEOUT)
        return render_to_json(sections)
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json_with_status_code(500)
예제 #6
0
def catalog_filters_json(request, abbreviation='', course_number=''):
    """Return JSON of filters for the catalog page."""

    filters = catalog_filters(request,
                              abbreviation=abbreviation,
                              course_number=course_number)
    playlist_type = type(Playlist.objects.all())

    for playlist in filters:
        if type(filters[playlist]) == playlist_type:
            filters[playlist] = list(
                map(lambda x: x.as_json(), filters[playlist]))

    filters['department'].insert(0, {
        'category': 'department',
        'name': '-',
        'id': -1,
    })

    return render_to_json(filters)
예제 #7
0
def course_json(request, course_id):
    """Render the JSON for a single course given a course_id."""
    try:
        course = Course.objects.get(pk=course_id)
        sections = Section.objects.filter(
            course_id=course_id,
            semester=CURRENT_SEMESTER,
            year=CURRENT_YEAR,
            disabled=False).order_by('section_number')

        return render_to_json(
            {
                'title': course.title,
                'course': f'{course.abbreviation} {course.course_number}',
                'last_enrollment_update': get_last_enrollment_update(sections),
                'offered': bool(sections),
            }, )
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()
예제 #8
0
def catalog_context_json(request, abbreviation='', course_number=''):
    """Return JSON of all courses"""

    long_form = request.GET.get('form', 'short') == 'long'
    cache_key = 'all__courses_new'
    if long_form:
        cache_key = 'all__courses__long_new'
    cached = cache.get(cache_key)
    if cached:
        rtn = cached
    else:
        courses = Course.objects.distinct().order_by('abbreviation',
                                                     'course_number')
        if long_form:
            rtn = courses.values('id', 'abbreviation', 'course_number',
                                 'title')
        else:
            rtn = courses.values('id', 'abbreviation', 'course_number')
        rtn = sort_course_dicts(rtn)
        cache.set(cache_key, rtn, CACHE_TIMEOUT)
    return render_to_json({'courses': rtn})
예제 #9
0
def grade_context_json(request):
    return render_to_json(grade_context(long_form=request.GET.get('form', 'short') == 'long'))
예제 #10
0
def enrollment_context_json(request):
    return render_to_json(
        enrollment_context(
            long_form=request.GET.get('form', 'short') == 'long'))
예제 #11
0
def enrollment_json(request, section_id):
    try:
        cached = cache.get('enrollment_json_new' + str(section_id))
        if cached:
            print('Cache Hit in enrollment_json with section_id ' + section_id)
            return render_to_json(cached)
        rtn = {}
        section = Section.objects.get(id=section_id)
        course = section.course
        rtn['course_id'] = course.id
        rtn['section_id'] = section.id
        rtn['title'] = course.abbreviation + ' ' + course.course_number
        rtn['subtitle'] = course.title
        if section.instructor == '' or section.instructor is None:
            section.instructor = 'No Instructor Assigned'
        rtn['section_name'] = section.instructor + ' - ' + section.section_number

        semester = section.semester
        year = section.year
        new_section = None
        if semester != CURRENT_SEMESTER or year != CURRENT_YEAR:
            CORRECTED_TELEBEARS_JSON = PAST_SEMESTERS_TELEBEARS_JSON[semester +
                                                                     ' ' +
                                                                     year]
            CORRECTED_TELEBEARS = PAST_SEMESTERS_TELEBEARS[semester + ' ' +
                                                           year]
        else:
            CORRECTED_TELEBEARS_JSON = TELEBEARS_JSON
            CORRECTED_TELEBEARS = TELEBEARS
            try:
                new_section = enrollment_service.get_live_enrollment(
                    semester=semester,
                    year=year,
                    course_id=course.id,
                    abbreviation=course.abbreviation,
                    course_number=course.course_number,
                    ccn=section.ccn,
                    log=True,
                )[0]
            except:
                print('SIS did not return valid live enrollment')

        rtn['telebears'] = CORRECTED_TELEBEARS_JSON
        enrolled_max = section.enrollment_set.all().latest(
            'date_created').enrolled_max
        waitlisted_max = section.enrollment_set.all().latest(
            'date_created').waitlisted_max
        rtn['enrolled_max'] = enrolled_max
        rtn['waitlisted_max'] = waitlisted_max

        rtn['data'] = []
        for d in section.enrollment_set.all().filter(
                date_created__gte=CORRECTED_TELEBEARS['phase1_start']
        ).order_by('date_created'):
            curr_d = {}
            curr_d['enrolled'] = d.enrolled
            curr_d['waitlisted'] = d.waitlisted
            curr_d['enrolled_max'] = enrolled_max
            curr_waitlisted_max = section.enrollment_set.all().latest(
                'date_created').waitlisted_max
            curr_d['waitlisted_max'] = curr_waitlisted_max
            curr_d['day'] = (d.date_created -
                             CORRECTED_TELEBEARS['phase1_start']).days + 1
            curr_d['date'] = (d.date_created).strftime('%m/%d/%Y-%H:%M:%S')
            curr_d['enrolled_percent'] = round(d.enrolled / enrolled_max,
                                               3) if enrolled_max else -1
            curr_d['waitlisted_percent'] = round(
                d.waitlisted /
                curr_waitlisted_max, 3) if curr_waitlisted_max else -1
            rtn['data'].append(curr_d)

        if semester == CURRENT_SEMESTER and year == CURRENT_YEAR and new_section is not None:
            last_enrolled = new_section['enrolled']
            last_waitlisted = new_section['waitlisted']
            enrolled_max = new_section['enrolled_max']
            waitlisted_max = new_section['waitlisted_max']
            rtn['data'][-1]['enrolled'] = last_enrolled
            rtn['data'][-1]['waitlisted'] = last_waitlisted
            rtn['data'][-1]['enrolled_percent'] = round(
                last_enrolled / enrolled_max, 3) if enrolled_max else -1
            rtn['data'][-1]['waitlisted_percent'] = round(
                last_waitlisted / waitlisted_max, 3) if waitlisted_max else -1
            rtn['data'][-1]['enrolled_max'] = enrolled_max
            rtn['data'][-1]['waitlisted_max'] = waitlisted_max
            rtn['enrolled_max'] = enrolled_max
            rtn['waitlisted_max'] = waitlisted_max

        rtn['instructor'] = section.instructor
        enrolled_outliers = [
            d['enrolled_percent'] for d in rtn['data']
            if d['enrolled_percent'] >= 1.0
        ]
        rtn['enrolled_percent_max'] = max(
            enrolled_outliers) * 1.10 if enrolled_outliers else 1.10
        waitlisted_outliers = [
            d['waitlisted_percent'] for d in rtn['data']
            if d['waitlisted_percent'] >= 1.0
        ]
        rtn['waitlisted_percent_max'] = max(
            waitlisted_outliers) * 1.10 if waitlisted_outliers else 1.10
        rtn['enrolled_scale_max'] = int(rtn['enrolled_percent_max'] *
                                        rtn['enrolled_max'])
        rtn['waitlisted_scale_max'] = int(rtn['waitlisted_percent_max'] *
                                          rtn['enrolled_max'])

        cache.set('enrollment_json_new' + str(section_id), rtn, CACHE_TIMEOUT)
        rtn = render_to_json(rtn)

        return rtn
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()
예제 #12
0
def enrollment_aggregate_json(request,
                              course_id,
                              semester=CURRENT_SEMESTER,
                              year=CURRENT_YEAR):
    try:
        cached = cache.get('enrollment_aggregate_json_new ' + str(course_id) +
                           semester + str(year))
        if cached:
            print('Cache Hit in enrollment_aggregate_json with course_id  ' +
                  course_id + ' semester ' + semester + ' year ' + year)
            return render_to_json(cached)
        rtn = {}
        course = Course.objects.get(id=course_id)
        sections = course.section_set.all().filter(semester=semester,
                                                   year=year,
                                                   disabled=False,
                                                   is_primary=True)
        if sections:
            rtn['course_id'] = course.id
            rtn['section_id'] = 'all'
            rtn['title'] = course.abbreviation + ' ' + course.course_number
            rtn['subtitle'] = course.title
            rtn['section_name'] = 'All Sections'

            new_sections = None
            if semester != CURRENT_SEMESTER or year != CURRENT_YEAR:
                CORRECTED_TELEBEARS_JSON = PAST_SEMESTERS_TELEBEARS_JSON[
                    semester + ' ' + year]
                CORRECTED_TELEBEARS = PAST_SEMESTERS_TELEBEARS[semester + ' ' +
                                                               year]
            else:
                CORRECTED_TELEBEARS_JSON = TELEBEARS_JSON
                CORRECTED_TELEBEARS = TELEBEARS
                try:
                    new_sections = enrollment_service.get_live_enrollment(
                        semester=semester,
                        year=year,
                        course_id=course_id,
                        abbreviation=course.abbreviation,
                        course_number=course.course_number,
                        log=True,
                    )
                except:
                    print('SIS did not return valid live enrollment')

            rtn['telebears'] = CORRECTED_TELEBEARS_JSON  #THIS NEEDS TO BE FROM THE OTHER SEMESTER, NOT THE CURRENT SEMESTER
            rtn['telebears']['semester'] = semester.capitalize() + ' ' + year
            last_date = sections[0].enrollment_set.all().latest(
                'date_created').date_created
            enrolled_max = Enrollment.objects.filter(
                section__in=sections, date_created=last_date).aggregate(
                    Sum('enrolled_max'))['enrolled_max__sum']
            waitlisted_max = Enrollment.objects.filter(
                section__in=sections, date_created=last_date).aggregate(
                    Sum('waitlisted_max'))['waitlisted_max__sum']
            rtn['enrolled_max'] = enrolled_max
            rtn['waitlisted_max'] = waitlisted_max
            dates = {
                d: [0, 0]
                for d in sections[0].enrollment_set.all().values_list(
                    'date_created', flat=True)
            }
            for s in sections:
                enrollment = s.enrollment_set.filter(
                    date_created__gte=CORRECTED_TELEBEARS['phase1_start']
                ).order_by('date_created')
                for (d, enrolled, waitlisted) in enrollment.values_list(
                        'date_created', 'enrolled', 'waitlisted'):
                    if d in dates:
                        dates[d][0] += enrolled
                        dates[d][1] += waitlisted

            rtn['data'] = []
            for d in sorted(dates.items(),
                            key=lambda date_enrollment_data_pair:
                            date_enrollment_data_pair[0]):
                curr_d = {}
                curr_d['enrolled'] = d[1][0]
                curr_d['waitlisted'] = d[1][1]
                curr_d['day'] = (d[0] -
                                 CORRECTED_TELEBEARS['phase1_start']).days + 1
                curr_d['date'] = (d[0]).strftime('%m/%d/%Y-%H:%M:%S')
                curr_enrolled_max = Enrollment.objects.filter(
                    section__in=sections, date_created=d[0]).aggregate(
                        Sum('enrolled_max'))['enrolled_max__sum']
                curr_d['enrolled_max'] = curr_enrolled_max
                curr_waitlisted_max = Enrollment.objects.filter(
                    section__in=sections, date_created=d[0]).aggregate(
                        Sum('waitlisted_max'))['waitlisted_max__sum']
                curr_d['waitlisted_max'] = curr_waitlisted_max
                curr_d['enrolled_percent'] = round(
                    d[1][0] /
                    curr_enrolled_max, 3) if curr_enrolled_max else -1
                curr_d['waitlisted_percent'] = round(
                    d[1][1] /
                    curr_waitlisted_max, 3) if curr_waitlisted_max else -1
                rtn['data'].append(curr_d)

            if semester == CURRENT_SEMESTER and year == CURRENT_YEAR and new_sections is not None:
                last_enrolled = sum([s['enrolled'] for s in new_sections])
                last_waitlisted = sum([s['waitlisted'] for s in new_sections])
                enrolled_max = sum([s['enrolled_max'] for s in new_sections])
                waitlisted_max = sum(
                    [s['waitlisted_max'] for s in new_sections])
                rtn['data'][-1]['enrolled'] = last_enrolled
                rtn['data'][-1]['waitlisted'] = last_waitlisted
                rtn['data'][-1]['enrolled_percent'] = round(
                    last_enrolled / enrolled_max, 3) if enrolled_max else -1
                rtn['data'][-1]['waitlisted_percent'] = round(
                    last_waitlisted /
                    waitlisted_max, 3) if waitlisted_max else -1
                rtn['data'][-1]['enrolled_max'] = enrolled_max
                rtn['data'][-1]['waitlisted_max'] = waitlisted_max
                rtn['enrolled_max'] = enrolled_max
                rtn['waitlisted_max'] = waitlisted_max

            enrolled_outliers = [
                d['enrolled_percent'] for d in rtn['data']
                if d['enrolled_percent'] >= 1.0
            ]
            rtn['enrolled_percent_max'] = max(
                enrolled_outliers) * 1.10 if enrolled_outliers else 1.10
            waitlisted_outliers = [
                d['waitlisted_percent'] for d in rtn['data']
                if d['waitlisted_percent'] >= 1.0
            ]
            rtn['waitlisted_percent_max'] = max(
                waitlisted_outliers) * 1.10 if waitlisted_outliers else 1.10
            rtn['enrolled_scale_max'] = int(rtn['enrolled_percent_max'] *
                                            rtn['enrolled_max'])
            rtn['waitlisted_scale_max'] = int(rtn['waitlisted_percent_max'] *
                                              rtn['waitlisted_max'])

            cache.set(
                'enrollment_aggregate_json_new ' + str(course_id) + semester +
                str(year), rtn, CACHE_TIMEOUT)
            rtn = render_to_json(rtn)

        return rtn
    except Exception as e:
        traceback.print_exc()
        return render_to_empty_json()