Skip to content

Commit

Permalink
#476 fix line length issues
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlittle committed Nov 24, 2019
1 parent 1fd4568 commit c85084b
Show file tree
Hide file tree
Showing 17 changed files with 144 additions and 77 deletions.
21 changes: 12 additions & 9 deletions content/views.py
Expand Up @@ -84,11 +84,12 @@ def process_media_file(media_guid,
# create some image/screenshots
image_path = generate_media_screenshots(media_local_file,
media_guid)
processed_media['embed_code'] = content.EMBED_TEMPLATE % (media_url.split('/')[-1],
media_url,
md5sum,
file_size,
file_length)
processed_media['embed_code'] = \
content.EMBED_TEMPLATE % (media_url.split('/')[-1],
media_url,
md5sum,
file_size,
file_length)

# Add the generated images to the output
processed_media['image_url_root'] = settings.MEDIA_URL \
Expand Down Expand Up @@ -136,7 +137,8 @@ def get_length(filename):
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)

duration = float(json.loads(result.stdout.read())['streams'][0]['duration'])
duration = float(
json.loads(result.stdout.read())['streams'][0]['duration'])
if duration != 0:
return True, duration
else:
Expand All @@ -155,9 +157,10 @@ def generate_media_screenshots(media_local_file, media_guid):
if not os.path.exists(image_path):
os.makedirs(image_path)

image_generator_command = ("%s %s" %
(settings.SCREENSHOT_GENERATOR_PROGRAM,
settings.SCREENSHOT_GENERATOR_PROGRAM_PARAMS)) \
image_generator_command = \
("%s %s" %
(settings.SCREENSHOT_GENERATOR_PROGRAM,
settings.SCREENSHOT_GENERATOR_PROGRAM_PARAMS)) \
% (media_local_file,
content.SCREENSHOT_IMAGE_WIDTH,
content.SCREENSHOT_IMAGE_HEIGHT,
Expand Down
35 changes: 20 additions & 15 deletions oppia/forms/cohort.py
Expand Up @@ -11,21 +11,26 @@ class CohortHelperDiv(Div):
class CohortForm(forms.Form):

description = forms.CharField(required=True)
teachers = forms.CharField(widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of usernames"), )
students = forms.CharField(widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of usernames"), )
start_date = forms.CharField(required=True,
error_messages={'required': _('Please enter a valid date'),
'invalid': _('Please enter a valid date')}, )
end_date = forms.CharField(required=True,
error_messages={'required': _('Please enter a valid date'),
'invalid': _('Please enter a valid date')}, )
courses = forms.CharField(widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of course codes"), )
teachers = forms.CharField(
widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of usernames"))
students = forms.CharField(
widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of usernames"))
start_date = forms.CharField(
required=True,
error_messages={'required': _('Please enter a valid date'),
'invalid': _('Please enter a valid date')})
end_date = forms.CharField(
required=True,
error_messages={'required': _('Please enter a valid date'),
'invalid': _('Please enter a valid date')})
courses = forms.CharField(
widget=forms.Textarea(),
required=False,
help_text=_("A comma separated list of course codes"))

def __init__(self, *args, **kwargs):
super(CohortForm, self).__init__(* args, ** kwargs)
Expand Down
6 changes: 4 additions & 2 deletions oppia/forms/upload.py
Expand Up @@ -66,9 +66,11 @@ def clean(self):

class UploadCourseStep2Form(forms.Form):
tags = forms.CharField(
help_text=_("A comma separated list of tags to help classify your course"),
help_text=_("A comma separated list of tags to help classify \
your course"),
required=True,
error_messages={'required': _('Please enter at least one tag')}, )
error_messages={'required':
_('Please enter at least one tag')})
is_draft = forms.BooleanField(
help_text=_("Whether this course is only a draft"),
required=False, )
Expand Down
10 changes: 7 additions & 3 deletions oppia/management/commands/cleanup_uploads.py
Expand Up @@ -28,13 +28,17 @@ def handle(self, *args, **options):
courses = Course.objects.filter(filename=filename)
if courses.count() == 0:
# delete the file
os.remove(os.path.join(settings.COURSE_UPLOAD_DIR, filename))
os.remove(os.path.join(settings.COURSE_UPLOAD_DIR,
filename))
self.stdout.write("Removed: " + filename)

"""
Flag up courses that don't have files
"""
courses = Course.objects.all()
for course in courses:
if not os.path.isfile(os.path.join(settings.COURSE_UPLOAD_DIR, course.filename)):
self.stdout.write("FILE MISSING: %s for %s " % (course.filename, course.title))
if not os.path.isfile(os.path.join(settings.COURSE_UPLOAD_DIR,
course.filename)):
self.stdout \
.write("FILE MISSING: %s for %s " % (course.filename,
course.title))
7 changes: 5 additions & 2 deletions oppia/management/commands/oppiacron.py
Expand Up @@ -32,7 +32,8 @@ def handle(self, *args, **options):
hours = 0

# check if cron already running
prop, created = SettingProperties.objects.get_or_create(key='oppia_cron_lock', int_value=1)
prop, created = SettingProperties.objects \
.get_or_create(key='oppia_cron_lock', int_value=1)
if not created:
self.stdout.write("Oppia cron is already running")
return
Expand All @@ -49,7 +50,9 @@ def handle(self, *args, **options):
if os.path.isfile(f):
os.remove(f)
else:
self.stdout.write('{path} does not exist. Don\'t need to clean it'.format(path=path))
self.stdout \
.write('{path} does not exist. Don\'t need to clean it'
.format(path=path))

from oppia.awards import courses_completed
courses_completed(int(hours))
Expand Down
5 changes: 4 additions & 1 deletion oppia/models/tag.py
Expand Up @@ -15,7 +15,10 @@ class Tag(models.Model):
description = models.TextField(blank=True, null=True, default=None)
order_priority = models.IntegerField(default=0)
highlight = models.BooleanField(default=False)
icon = models.FileField(upload_to="tags", null=True, blank=True, default=None)
icon = models.FileField(upload_to="tags",
null=True,
blank=True,
default=None)

class Meta:
verbose_name = _('Tag')
Expand Down
8 changes: 5 additions & 3 deletions oppia/uploader.py
Expand Up @@ -396,8 +396,9 @@ def parse_and_save_activity(req,
data=msg_text).save()
else:
msg_text = _(u'Activity "%(act)s"(%(digest)s) previously existed. \
Updated with new information') % {'act': activity.title,
'digest': activity.digest}
Updated with new information') \
% {'act': activity.title,
'digest': activity.digest}
'''
If we also want to show the activities that previously existed,
uncomment this next line
Expand Down Expand Up @@ -574,7 +575,8 @@ def clean_old_course(req, user, oldsections, old_course_filename, course):
data=msg_text).save()
sec.delete()

if old_course_filename is not None and old_course_filename != course.filename:
if old_course_filename is not None \
and old_course_filename != course.filename:
try:
os.remove(os.path.join(settings.COURSE_UPLOAD_DIR,
old_course_filename))
Expand Down
23 changes: 17 additions & 6 deletions oppia/utils/courseFile.py
Expand Up @@ -22,23 +22,34 @@ def remove_from_zip(zipfname, temp_zip_path, course_shortname, *filenames):


def unescape_xml(xml_content):
new_xml = unescape(xml_content, {"'": "'", """: '"', " ": " "})
new_xml = new_xml.replace(' ', ' ').replace('"', '"').replace('&', '&')
new_xml = unescape(xml_content,
{"'": "'", """: '"', " ": " "})
new_xml = new_xml.replace(' ', ' ') \
.replace('"', '"') \
.replace('&', '&')
return new_xml


def rewrite_xml_contents(user, course, xml_doc):
temp_zip_path = os.path.join(settings.COURSE_UPLOAD_DIR, 'temp', str(user.id))
temp_zip_path = os.path.join(settings.COURSE_UPLOAD_DIR,
'temp',
str(user.id))
module_xml = course.shortname + '/module.xml'
try:
os.makedirs(temp_zip_path)
except OSError:
pass # leaf dir for user id already exists

course_zip_file = os.path.join(settings.COURSE_UPLOAD_DIR, course.filename)
remove_from_zip(course_zip_file, temp_zip_path, course.shortname, module_xml)
course_zip_file = os.path.join(settings.COURSE_UPLOAD_DIR,
course.filename)
remove_from_zip(course_zip_file,
temp_zip_path,
course.shortname,
module_xml)

xml_content = xml_doc.toprettyxml(indent='', newl='', encoding='utf-8').decode('utf-8')
xml_content = xml_doc.toprettyxml(indent='',
newl='',
encoding='utf-8').decode('utf-8')
xml_content = unescape_xml(xml_content)

with zipfile.ZipFile(course_zip_file, 'a') as z:
Expand Down
34 changes: 21 additions & 13 deletions oppia/views.py
Expand Up @@ -144,9 +144,11 @@ def teacher_home_view(request):
# get student activity
activity = []
no_days = (end_date - start_date).days + 1
students = User.objects.filter(participant__role=Participant.STUDENT,
participant__cohort__in=cohorts).distinct()
courses = Course.objects.filter(coursecohort__cohort__in=cohorts).distinct()
students = User.objects \
.filter(participant__role=Participant.STUDENT,
participant__cohort__in=cohorts).distinct()
courses = Course.objects \
.filter(coursecohort__cohort__in=cohorts).distinct()
trackers = Tracker.objects.filter(course__in=courses,
user__in=students,
tracker_date__gte=start_date,
Expand All @@ -155,7 +157,9 @@ def teacher_home_view(request):
.values('activity_date').annotate(count=Count('id'))
for i in range(0, no_days, +1):
temp = start_date + datetime.timedelta(days=i)
count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
count = next((dct['count']
for dct in trackers
if dct['activity_date'] == temp.date()), 0)
activity.append([temp.strftime("%d %b %Y"), count])

return render(request, 'oppia/home-teacher.html',
Expand Down Expand Up @@ -239,7 +243,8 @@ def course_download_view(request, course_id):
content_type='application/zip')
binary_file.close()
response['Content-Length'] = os.path.getsize(file_to_download)
response['Content-Disposition'] = 'attachment; filename="%s"' % (course.filename)
response['Content-Disposition'] = 'attachment; filename="%s"' \
% (course.filename)
return response


Expand Down Expand Up @@ -297,17 +302,19 @@ def upload_step2(request, course_id, editing=False):
# add the tags
add_course_tags(form, course, request.user)
redirect = 'oppia_course' if editing else 'oppia_upload_success'
CoursePublishingLog(course=course,
new_version=course.version,
user=request.user,
action="upload_course_published",
data=_(u'Course published via file upload')).save()
CoursePublishingLog(
course=course,
new_version=course.version,
user=request.user,
action="upload_course_published",
data=_(u'Course published via file upload')).save()
return HttpResponseRedirect(reverse(redirect))
else:
form = UploadCourseStep2Form(initial={'tags': course.get_tags(),
'is_draft': course.is_draft, })

page_title = _(u'Upload Course - step 2') if not editing else _(u'Edit course')
page_title = _(u'Upload Course - step 2') \
if not editing else _(u'Edit course')
return render(request, 'course/form.html',
{'form': form,
'course_title': course.title,
Expand Down Expand Up @@ -535,8 +542,9 @@ def export_tracker_detail(request, course_id):
t.agent,
""))

response = HttpResponse(data.xls,
content_type='application/vnd.ms-excel;charset=utf-8')
response = HttpResponse(
data.xls,
content_type='application/vnd.ms-excel;charset=utf-8')
response['Content-Disposition'] = "attachment; filename=export.xls"

return response
Expand Down
6 changes: 4 additions & 2 deletions quiz/api/serializers.py
Expand Up @@ -57,7 +57,8 @@ def format_quiz(self, data):
question['question']['p'] = {}
for p in question['question']['props']:
try:
question['question']['p'][p['name']] = float(p['value'])
question['question']['p'][p['name']] \
= float(p['value'])
except ValueError:
question['question']['p'][p['name']] = p['value']

Expand All @@ -76,7 +77,8 @@ def format_quiz(self, data):
del question['question']['p']
try:
float(question['question']['props']['maxscore'])
qmaxscore = qmaxscore + float(question['question']['props']['maxscore'])
qmaxscore = qmaxscore \
+ float(question['question']['props']['maxscore'])
except ValueError:
pass

Expand Down
9 changes: 6 additions & 3 deletions quiz/api/validation.py
Expand Up @@ -10,7 +10,8 @@ def is_valid(self, bundle, request=None):
return {'__all__': 'no data.'}
errors = {}
quiz = bundle.obj.quiz
if not bundle.request.user.is_staff and quiz.owner.id != bundle.request.user.id:
if not bundle.request.user.is_staff \
and quiz.owner.id != bundle.request.user.id:
errors['error_message'] = _(u"You are not the owner of this quiz")
return errors

Expand All @@ -22,7 +23,8 @@ def is_valid(self, bundle, request=None):
errors = {}
question = bundle.obj.question
if question.owner.id != bundle.request.user.id:
errors['error_message'] = _(u"You are not the owner of this question")
errors['error_message'] = \
_(u"You are not the owner of this question")
return errors


Expand All @@ -33,7 +35,8 @@ def is_valid(self, bundle, request=None):
errors = {}
response = bundle.obj.response
if response.owner.id != bundle.request.user.id:
errors['error_message'] = _(u"You are not the owner of this response")
errors['error_message'] = \
_(u"You are not the owner of this response")
return errors


Expand Down
12 changes: 8 additions & 4 deletions quiz/management/commands/remove_duplicate_quiz_attempts.py
Expand Up @@ -23,7 +23,9 @@ def handle(self, *args, **options):
Remove quizattempts with no UUID
"""
result = QuizAttempt.objects.filter(instance_id=None).delete()
self.stdout.write(_(u"\n\n%d quiz attempts removed that had no instance_id\n" % result[0]))
self.stdout.write(
_(u"\n\n%d quiz attempts removed that had no instance_id\n"
% result[0]))

"""
Remove proper duplicate quizattempts - using max id
Expand All @@ -43,8 +45,9 @@ def handle(self, *args, **options):
.exclude(id=exclude['max_id']) \
.delete()
self.stdout.write(_(u"%d duplicate quiz attempt(s) removed for \
instance_id %s based on max id" % (deleted[0],
quiz_attempt['instance_id'])))
instance_id %s based on max id"
% (deleted[0],
quiz_attempt['instance_id'])))

"""
Remember to run summary cron from start
Expand All @@ -53,6 +56,7 @@ def handle(self, *args, **options):
self.stdout.write(_(u"Since duplicates have been found and \
removed, you should now run `update_summaries` \
to ensure the dashboard graphs are accurate."))
accept = raw_input(_(u"Would you like to run `update_summaries` now? [Yes/No]"))
accept = raw_input(_(u"Would you like to run `update_summaries` \
now? [Yes/No]"))
if accept == 'y':
call_command('update_summaries', fromstart=True)

0 comments on commit c85084b

Please sign in to comment.