def studentRenderGrades():
  try:
    content = request.get_json()
    c = Course.objects.get(id=content['cid'])
    u = User.objects.get(id=current_user.id)

    assignmentScores = getStudentAssignmentScores(c, u)

    userCourseScore = 0

    outString = "<tr><th>Your Scores</th>"
    # <td>{{link to problem grading}}</td>
    for assignment, a in zip(assignmentScores, c.assignments):
      #If this assignment doesn't have any problems we put a blank column in
      if len(assignment) == 0:
        outString += "<td class='active'></td>"
        continue

      for problem, p in zip(assignment, a.problems):
        if problem == None:
          #If there was no submission link to the make blank page
          outString += "<td class='active'>"
          outString += "0.00"
          outString += "</td>"
        else:
          highlight = createHighlight(problem)
          if 'finalTotalScore' in problem:
            points =  problem['finalTotalScore']
            userCourseScore += problem['finalTotalScore']
          else:
            points = problem['rawTotalScore']
            userCourseScore += problem['rawTotalScore']

          maxPoints = p.gradeColumn.maxScore
          cellTemplate = "<td %s>%.2f</td>" % (highlight, points)
          outString += cellTemplate

    for group in c.gradeBook.auxillaryGrades:
      if len(group.columns) == 0:
        outString += "<td class='active'></td>"
        continue

      for col in group.columns:
        score = col.scores.setdefault(u.keyOfUsername(), None)
        if score:
          outString += "<td>%.2f</td>" % (score.totalScore())
          userCourseScore += score.totalScore()
        else:
          outString += "<td>%.2f</td>" % (0)

    outString += "<td>%.2f</td></tr>" % (userCourseScore)
    return jsonify(res=outString, cid=str(c.id))

  except (Course.DoesNotExist,User.DoesNotExist):
    abort(404)
  except Exception as e:
    return jsonify(res=str(e))
def serveGradebook(cid, raw):
  try:
    course = Course.objects.get(id=cid)

    if not course in current_user.courseInstructor:
      abort(403)

    csvf = tempfile.NamedTemporaryFile()

    writer = csv.writer(csvf, delimiter=",", quotechar="\"")

    #Put the main headers on
    row = ['', 'Assignment']
    for a in course.gradeBook.groups():
      row += [a.name]*a.getWidth()
    writer.writerow(row)

    #Put the problem headers on
    row = ['', 'Problem']
    for c in course.gradeBook.columns():
      if c == None:
        row += ["None"]
      else:
        row += [c.name]
    row += ['Total Points']
    writer.writerow(row)

    #Put in the max points row
    row = ['', 'Max Points']
    for c in course.gradeBook.columns():
      if c == None:
        row += [0]
      else:
        row += [c.maxScore]
    row += [course.gradeBook.totalPoints()]
    writer.writerow(row)
    writer.writerow(['Name', 'Username'])

    #Do the user rows
    students = User.objects.filter(courseStudent=course)

    for s in students:
      if course.anonymousGrading:
        row = [(str(s.firstName) + ' ' + str(s.lastName)), \
                (s.username+ ' (' + course.getIdentifier(s.username) + ')')]
      else:
        row = [(str(s.firstName) + ' ' + str(s.lastName)), s.username]
      userCourseScore = 0
      scores = getStudentAssignmentScores(course, s)
      for a in scores:
        if len(a) == 0:
          row += ['N/A']
          continue
        for p in a:
          if p == None:
            row += [0]
          else:
            if 'finalTotalScore' in p:
              row += [p['finalTotalScore']]
              userCourseScore += p['finalTotalScore']
            else:
              row += [p['rawTotalScore']]
              userCourseScore += p['rawTotalScore']
      for group in course.gradeBook.auxillaryGrades:
        if len(group.columns) == 0:
          row += [0]

        for col in group.columns:
          score = col.scores.setdefault(s.keyOfUsername(), None)
          if score:
            row += [score.totalScore()]
            userCourseScore += score.totalScore()
          else:
            row += [0]
      row += [userCourseScore]
      writer.writerow(row)

    #Be kind rewind the file
    csvf.seek(0)

    return send_file(csvf,as_attachment=True, attachment_filename='grades.csv', cache_timeout=50)

  except Course.DoesNotExist:
    abort(404)
def commonRenderGrade(cid, instr):
  try:
    content = request.get_json()
    c = Course.objects.get(id=cid)
    u = User.objects.get(id=content['uid'])

    #If we are accessing the instructor version check that they are an instr
    if instr and not c in current_user.courseInstructor:
      abort(403)

    if not c in current_user.gradingCourses():
      abort(403)

    assignmentScores = getStudentAssignmentScores(c, u)

    userCourseScore = 0

    outString = "<tr>"
    # <td>{{username/identifier}}</td>
    outString += "<td>"
    if instr:
      outString += u.username
      if c.anonymousGrading:
        outString += " (" + c.getIdentifier(u.keyOfUsername()) + ")"
    else:
      if c.anonymousGrading:
        outString += c.getIdentifier(u.keyOfUsername())
      else:
        outString += u.username
    outString += "</td>"
    # <td>{{link to problem grading}}</td>
    for assignment, a in zip(assignmentScores, c.assignments):
      #If this assignment doesn't have any problems we put a blank column in
      if len(assignment) == 0:
        outString += "<td class='active'></td>"
        continue

      for problem, p in zip(assignment, a.problems):
        if problem == None:
          #If there was no submission link to the make blank page
          outString += "<td class='active'><a href='"
          outString += "#'" #TODO Replace this with an actual link
          outString += ">0.00"
          outString += "</a></td>"
        else:
          highlight = createHighlight(problem)
          url = url_for('grutorGradeSubmission', pid=p.id, uid=u.id, subnum=p.getSubmissionNumber(u))
          if 'finalTotalScore' in problem:
            points =  problem['finalTotalScore']
            userCourseScore += problem['finalTotalScore']
          else:
            points = problem['rawTotalScore']
            userCourseScore += problem['rawTotalScore']

          maxPoints = p.gradeColumn.maxScore
          cellTemplate = "<td %s><a href='%s'>%.2f</a></td>" % (highlight, url, points)
          outString += cellTemplate

    for group in c.gradeBook.auxillaryGrades:
      if len(group.columns) == 0:
        outString += "<td class='active'></td>"
        continue

      for col in group.columns:
        score = col.scores.setdefault(u.keyOfUsername(), None)
        if score:
          outString += "<td>%.2f</td>" % (score.totalScore())
          userCourseScore += score.totalScore()
        else:
          outString += "<td>%.2f</td>" % (0)

    outString += "<td>%.2f</td></tr>" % (userCourseScore)
    return jsonify(res=outString)

  except (Course.DoesNotExist,User.DoesNotExist):
    abort(404)