Skip to content

Commit

Permalink
Add flake8-quotes to the linter
Browse files Browse the repository at this point in the history
Also fix all existing quoting issues
  • Loading branch information
Riolku authored and leduythuccs committed Sep 18, 2021
1 parent 60ec53e commit fee01b5
Show file tree
Hide file tree
Showing 43 changed files with 149 additions and 144 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ exclude =
./dmoj/local_settings.py, # belongs to the user
./dmoj/local_urls.py, # belongs to the user
./.ci.settings.py, # is actually a fragment to be included by settings.py
fc_*
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
with:
python-version: 3.7
- name: Install flake8
run: pip install flake8 flake8-import-order flake8-future-import flake8-commas flake8-logging-format
run: pip install flake8 flake8-import-order flake8-future-import flake8-commas flake8-logging-format flake8-quotes
- name: Lint with flake8
run: |
flake8 --version
Expand Down
2 changes: 1 addition & 1 deletion dmoj/throttle_discord_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def emit(self, record):
exc_info = (None, record.getMessage(), None)

reporter = ExceptionReporter(request, is_email=True, *exc_info)
message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
message = '%s\n\n%s' % (self.format(no_exc_record), reporter.get_traceback_text())
self.send_webhook(subject, message)

def send_webhook(self, subject, message):
Expand Down
2 changes: 1 addition & 1 deletion dmoj_install_pymysql.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import pymysql

pymysql.install_as_MySQLdb()
pymysql.version_info = (1, 3, 13, "final", 0)
pymysql.version_info = (1, 3, 13, 'final', 0)
4 changes: 2 additions & 2 deletions judge/admin/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class GenerateKeyTextInput(TextInput):
def render(self, name, value, attrs=None, renderer=None):
text = super(TextInput, self).render(name, value, attrs)
return mark_safe(text + format_html(
'''\
"""\
<a href="#" onclick="return false;" class="button" id="id_{0}_regen">Regenerate</a>
<script type="text/javascript">
django.jQuery(document).ready(function ($) {{
Expand All @@ -56,7 +56,7 @@ def render(self, name, value, attrs=None, renderer=None):
}});
}});
</script>
''', name))
""", name))


class JudgeAdminForm(ModelForm):
Expand Down
8 changes: 4 additions & 4 deletions judge/contest_format/atcoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ class AtCoderContestFormat(DefaultContestFormat):
name = gettext_lazy('AtCoder')
config_defaults = {'penalty': 5}
config_validators = {'penalty': lambda x: x >= 0}
'''
"""
penalty: Number of penalty minutes each incorrect submission adds. Defaults to 5.
'''
"""

@classmethod
def validate(cls, config):
Expand Down Expand Up @@ -51,7 +51,7 @@ def update_participation(self, participation):
format_data = {}

with connection.cursor() as cursor:
cursor.execute('''
cursor.execute("""
SELECT MAX(cs.points) as `score`, (
SELECT MIN(csub.date)
FROM judge_contestsubmission ccs LEFT OUTER JOIN
Expand All @@ -62,7 +62,7 @@ def update_participation(self, participation):
judge_contestsubmission cs ON (cs.problem_id = cp.id AND cs.participation_id = %s) LEFT OUTER JOIN
judge_submission sub ON (sub.id = cs.submission_id)
GROUP BY cp.id
''', (participation.id, participation.id))
""", (participation.id, participation.id))

for score, time, prob in cursor.fetchall():
time = from_database_time(time)
Expand Down
4 changes: 2 additions & 2 deletions judge/contest_format/ecoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ class ECOOContestFormat(DefaultContestFormat):
name = gettext_lazy('ECOO')
config_defaults = {'cumtime': False, 'first_ac_bonus': 10, 'time_bonus': 5}
config_validators = {'cumtime': lambda x: True, 'first_ac_bonus': lambda x: x >= 0, 'time_bonus': lambda x: x >= 0}
'''
"""
cumtime: Specify True if cumulative time is to be used in breaking ties. Defaults to False.
first_ac_bonus: The number of points to award if a solution gets AC on its first non-IE/CE run. Defaults to 10.
time_bonus: Number of minutes to award an extra point for submitting before the contest end.
Specify 0 to disable. Defaults to 5.
'''
"""

@classmethod
def validate(cls, config):
Expand Down
8 changes: 4 additions & 4 deletions judge/contest_format/icpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ class ICPCContestFormat(DefaultContestFormat):
name = gettext_lazy('ICPC')
config_defaults = {'penalty': 20}
config_validators = {'penalty': lambda x: x >= 0}
'''
"""
penalty: Number of penalty minutes each incorrect submission adds. Defaults to 20.
'''
"""

@classmethod
def validate(cls, config):
Expand Down Expand Up @@ -52,7 +52,7 @@ def update_participation(self, participation):
format_data = {}

with connection.cursor() as cursor:
cursor.execute('''
cursor.execute("""
SELECT MAX(cs.points) as `points`, (
SELECT MIN(csub.date)
FROM judge_contestsubmission ccs LEFT OUTER JOIN
Expand All @@ -63,7 +63,7 @@ def update_participation(self, participation):
judge_contestsubmission cs ON (cs.problem_id = cp.id AND cs.participation_id = %s) LEFT OUTER JOIN
judge_submission sub ON (sub.id = cs.submission_id)
GROUP BY cp.id
''', (participation.id, participation.id))
""", (participation.id, participation.id))

for points, time, prob in cursor.fetchall():
time = from_database_time(time)
Expand Down
8 changes: 4 additions & 4 deletions judge/contest_format/ioi.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@
class IOIContestFormat(LegacyIOIContestFormat):
name = gettext_lazy('IOI')
config_defaults = {'cumtime': False}
'''
"""
cumtime: Specify True if time penalties are to be computed. Defaults to False.
'''
"""

def update_participation(self, participation):
cumtime = 0
score = 0
format_data = {}

with connection.cursor() as cursor:
cursor.execute('''
cursor.execute("""
SELECT q.prob,
MIN(q.date) as `date`,
q.batch_points
Expand Down Expand Up @@ -64,7 +64,7 @@ def update_participation(self, participation):
ON p.prob = q.prob AND (p.batch = q.batch OR p.batch is NULL AND q.batch is NULL)
WHERE p.max_batch_points = q.batch_points
GROUP BY q.prob, q.batch
''', (participation.id, participation.id))
""", (participation.id, participation.id))

for problem_id, time, subtask_points in cursor.fetchall():
problem_id = str(problem_id)
Expand Down
4 changes: 2 additions & 2 deletions judge/contest_format/legacy_ioi.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
class LegacyIOIContestFormat(DefaultContestFormat):
name = gettext_lazy('IOI (pre-2016)')
config_defaults = {'cumtime': False}
'''
"""
cumtime: Specify True if time penalties are to be computed. Defaults to False.
'''
"""

@classmethod
def validate(cls, config):
Expand Down
14 changes: 7 additions & 7 deletions judge/custom_translations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@

# Translate Password validation
ngettext(
"This password is too short. It must contain at least %(min_length)d character.",
"This password is too short. It must contain at least %(min_length)d characters.",
'This password is too short. It must contain at least %(min_length)d character.',
'This password is too short. It must contain at least %(min_length)d characters.',
)
ngettext(
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
'Your password must contain at least %(min_length)d character.',
'Your password must contain at least %(min_length)d characters.',
)
_("The password is too similar to the %(verbose_name)s.")
_('The password is too similar to the %(verbose_name)s.')
_("Your password can't be too similar to your other personal information.")
_("This password is entirely numeric.")
_('This password is entirely numeric.')
_("Your password can't be entirely numeric.")

# NavBar
_("PRoblems")
_('PRoblems')
_('posted {time}')

# Comment
Expand Down
8 changes: 4 additions & 4 deletions judge/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def clean(self):
def check_file(self):
content = self.files.get('statement_file', None)
if content is not None and content.size > settings.PDF_STATEMENT_MAX_FILE_SIZE:
raise forms.ValidationError(_("File size is too big! Maximum file size is %s") %
raise forms.ValidationError(_('File size is too big! Maximum file size is %s') %
filesizeformat(settings.PDF_STATEMENT_MAX_FILE_SIZE))
return content

Expand Down Expand Up @@ -248,7 +248,7 @@ def check_submission(self):

if (source != '' and content is not None) or (source == '' and content is None) or \
(source != '' and lang_obj.file_only) or (content == '' and not lang_obj.file_only):
raise forms.ValidationError(_("Source code/file is missing or redundant. Please try again"))
raise forms.ValidationError(_('Source code/file is missing or redundant. Please try again'))

if content:
max_file_size = lang_obj.file_size_limit * 1024 * 1024
Expand All @@ -260,7 +260,7 @@ def check_submission(self):
% {'lang': language, 'lang_ext': lang_obj.extension, 'ext': ext})

elif content.size > max_file_size:
raise forms.ValidationError(_("File size is too big! Maximum file size is %s")
raise forms.ValidationError(_('File size is too big! Maximum file size is %s')
% filesizeformat(max_file_size))

def __init__(self, *args, judge_choices=(), **kwargs):
Expand Down Expand Up @@ -490,7 +490,7 @@ def clean(self) -> None:
continue
order = form.cleaned_data.get('order')
if order and order in orders:
raise ValidationError(_("Problems must have distinct order."))
raise ValidationError(_('Problems must have distinct order.'))
orders.append(order)


Expand Down
4 changes: 2 additions & 2 deletions judge/highlight_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ def _make_pre_code(code):


def _wrap_code(inner):
yield 0, "<code>"
yield 0, '<code>'
for tup in inner:
yield tup
yield 0, "</code>"
yield 0, '</code>'


try:
Expand Down
8 changes: 4 additions & 4 deletions judge/jinja2/markdown/test_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@

from . import fragment_tree_to_str, fragments_to_tree, get_cleaner, markdown

MATHML_N = '''\
MATHML_N = """\
<math xmlns="http://www.w3.org/1998/Math/MathML">
<semantics>
<mi>N</mi>
<annotation encoding="application/x-tex">N</annotation>
</semantics>
</math>
'''
"""

MATHML_CHUDNOVSKY = r'''
MATHML_CHUDNOVSKY = r"""
<math xmlns="http://www.w3.org/1998/Math/MathML"
alttext="{\displaystyle {\frac {1}{\pi }}=12\sum _{k=0}^{\infty }{\frac {(-1)^{k}(6k)!(545140134k+13591409)}{(3k)!(k!)^{3}\left(640320\right)^{3k+3/2}}}}">
<semantics>
Expand Down Expand Up @@ -101,7 +101,7 @@
<annotation encoding="application/x-tex">{\displaystyle {\frac {1}{\pi }}=12\sum _{k=0}^{\infty }{\frac {(-1)^{k}(6k)!(545140134k+13591409)}{(3k)!(k!)^{3}\left(640320\right)^{3k+3/2}}}}</annotation>
</semantics>
</math>
''' # noqa: E501
""" # noqa: E501


class TestMarkdown(SimpleTestCase):
Expand Down
4 changes: 2 additions & 2 deletions judge/management/commands/adduser.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ def add_arguments(self, parser):
help='default language ID for user')

parser.add_argument('--superuser', action='store_true', default=False,
help="if specified, creates user with superuser privileges")
help='if specified, creates user with superuser privileges')
parser.add_argument('--staff', action='store_true', default=False,
help="if specified, creates user with staff privileges")
help='if specified, creates user with staff privileges')

def handle(self, *args, **options):
usr = User(username=options['name'], email=options['email'], is_active=True)
Expand Down
10 changes: 5 additions & 5 deletions judge/management/commands/makedmojmessages.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ def add_arguments(self, parser):
parser.add_argument('--no-wrap', action='store_true', dest='no_wrap',
default=False, help="Don't break long message lines into several lines.")
parser.add_argument('--no-obsolete', action='store_true', dest='no_obsolete',
default=False, help="Remove obsolete message strings.")
default=False, help='Remove obsolete message strings.')
parser.add_argument('--keep-pot', action='store_true', dest='keep_pot',
default=False, help="Keep .pot file after making messages. Useful when debugging.")
default=False, help='Keep .pot file after making messages. Useful when debugging.')

def handle(self, *args, **options):
locale = options.get('locale')
Expand Down Expand Up @@ -97,7 +97,7 @@ def handle(self, *args, **options):
# Build po files for each selected locale
for locale in locales:
if self.verbosity > 0:
self.stdout.write("processing locale %s\n" % locale)
self.stdout.write('processing locale %s\n' % locale)
for potfile in potfiles:
self.write_po_file(potfile, locale)
finally:
Expand All @@ -108,10 +108,10 @@ def find_files(self, root):
return []

def _emit_message(self, potfile, string):
potfile.write('''
potfile.write("""
msgid "%s"
msgstr ""
''' % string.replace('\\', r'\\').replace('\t', '\\t').replace('\n', '\\n').replace('"', '\\"'))
""" % string.replace('\\', r'\\').replace('\t', '\\t').replace('\n', '\\n').replace('"', '\\"'))

def process_files(self, file_list):
with io.open(os.path.join(self.default_locale_path, 'dmoj-user.pot'), 'w', encoding='utf-8') as potfile:
Expand Down
2 changes: 1 addition & 1 deletion judge/management/commands/runmoss.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def handle(self, *args, **options):
for problem in Contest.objects.get(key=contest).problems.order_by('code'):
print('========== %s / %s ==========' % (problem.code, problem.name))
for dmoj_lang, moss_lang in self.LANG_MAPPING:
print("%s: " % dmoj_lang, end=' ')
print('%s: ' % dmoj_lang, end=' ')
subs = Submission.objects.filter(
contest__participation__virtual__in=(ContestParticipation.LIVE, ContestParticipation.SPECTATE),
contest__participation__contest__key=contest,
Expand Down
8 changes: 4 additions & 4 deletions judge/migrations/0085_submission_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ class Migration(migrations.Migration):
],
),
migrations.RunSQL(
['''INSERT INTO judge_submissionsource (source, submission_id)
SELECT source, id AS 'submission_id' FROM judge_submission;'''],
['''UPDATE judge_submission sub
["""INSERT INTO judge_submissionsource (source, submission_id)
SELECT source, id AS 'submission_id' FROM judge_submission;"""],
["""UPDATE judge_submission sub
INNER JOIN judge_submissionsource src ON sub.id = src.submission_id
SET sub.source = src.source;'''],
SET sub.source = src.source;"""],
elidable=True,
),
migrations.RemoveField(
Expand Down
4 changes: 2 additions & 2 deletions judge/migrations/0089_submission_to_contest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ class Migration(migrations.Migration):
name='contest_object',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='judge.Contest', verbose_name='contest'),
),
migrations.RunSQL('''
migrations.RunSQL("""
UPDATE `judge_submission`
INNER JOIN `judge_contestsubmission`
ON (`judge_submission`.`id` = `judge_contestsubmission`.`submission_id`)
INNER JOIN `judge_contestparticipation`
ON (`judge_contestsubmission`.`participation_id` = `judge_contestparticipation`.`id`)
SET `judge_submission`.`contest_object_id` = `judge_contestparticipation`.`contest_id`
''', migrations.RunSQL.noop),
""", migrations.RunSQL.noop),
]
6 changes: 3 additions & 3 deletions judge/migrations/0090_fix_contest_visibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ class Migration(migrations.Migration):
]

operations = [
migrations.RunSQL('''
migrations.RunSQL("""
UPDATE `judge_contest`
SET `judge_contest`.`is_private` = 0, `judge_contest`.`is_organization_private` = 1
WHERE `judge_contest`.`is_private` = 1
''', '''
""", """
UPDATE `judge_contest`
SET `judge_contest`.`is_private` = `judge_contest`.`is_organization_private`
'''),
"""),
]
4 changes: 2 additions & 2 deletions judge/models/contest.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class Contest(models.Model):
max_length=1, help_text=_('Scoreboard visibility through the duration '
'of the contest'), choices=SCOREBOARD_VISIBILITY)
use_clarifications = models.BooleanField(verbose_name=_('no comments'),
help_text=_("Use clarification system instead of comments."),
help_text=_('Use clarification system instead of comments.'),
default=True)
push_announcements = models.BooleanField(verbose_name=_('push announcements'),
help_text=_('Notify users when there are new announcements.'),
Expand Down Expand Up @@ -564,7 +564,7 @@ class ContestProblem(models.Model):
'or leave blank for no limit.'),
default=None, null=True, blank=True,
validators=[MinValueOrNoneValidator(1, _('Why include a problem you '
'can\'t submit to?'))])
"can't submit to?"))])

class Meta:
unique_together = ('problem', 'contest')
Expand Down
2 changes: 1 addition & 1 deletion judge/models/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def generate_api_token(self):

def generate_scratch_codes(self):
def generate_scratch_code():
return "".join(secrets.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") for _ in range(16))
return ''.join(secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') for _ in range(16))
codes = [generate_scratch_code() for _ in range(settings.DMOJ_SCRATCH_CODES_COUNT)]
self.scratch_codes = json.dumps(codes)
self.save(update_fields=['scratch_codes'])
Expand Down
Loading

0 comments on commit fee01b5

Please sign in to comment.