Skip to content
base.py 45.1 KiB
Newer Older
from __future__ import annotations
Andreas Klöckner's avatar
Andreas Klöckner committed

__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, Any
Andreas Klöckner's avatar
Andreas Klöckner committed

import django.forms as forms
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.conf import settings
from django.forms import ValidationError as FormValidationError
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_lazy as _, gettext_noop
Andreas Klöckner's avatar
Andreas Klöckner committed

from course.constants import MAX_EXTRA_CREDIT_FACTOR
from course.validation import (
    AttrSpec,
    ValidationContext,
    ValidationError,
    validate_struct,
)
Andreas Klöckner's avatar
Andreas Klöckner committed
from relate.utils import Struct, StyledForm, string_concat


if TYPE_CHECKING:
    # FIXME There seem to be some cyclic imports that prevent importing these
    # outright.
    from course.models import Course, FlowSession
    from relate.utils import Repo_ish
Andreas Klöckner's avatar
Andreas Klöckner committed
__doc__ = """
Stub Docs of Internals
======================

.. class:: Repo_ish

    See ``relate.utils.Repo_ish``.

.. class:: Course

    See ``course.models.Course``.

.. class:: FlowSession

    See ``course.models.FlowSession``.

Page Interface
==============

Andreas Klöckner's avatar
Andreas Klöckner committed
.. autoclass:: PageContext
.. autoclass:: PageBehavior

.. autoclass:: AnswerFeedback

.. exception:: InvalidPageData

Base Classes For Pages
======================

Andreas Klöckner's avatar
Andreas Klöckner committed
.. autoclass:: PageBase
.. autoclass:: PageBaseWithTitle
.. autoclass:: PageBaseWithHumanTextFeedback
.. autoclass:: PageBaseWithCorrectAnswer

Automatic Feedback
==================

.. autofunction:: get_auto_feedback
Andreas Klöckner's avatar
Andreas Klöckner committed
"""

    """
    .. attribute:: course
    .. attribute:: repo
    .. attribute:: commit_sha
    .. attribute:: flow_session

        May be None.

    .. attribute:: page_uri
    .. attribute:: request
    Note that this is different from :class:`course.utils.FlowPageContext`,
    which is used internally by the flow views.
    """

Andreas Klöckner's avatar
Andreas Klöckner committed
            commit_sha: bytes,
Andreas Klöckner's avatar
Andreas Klöckner committed
            in_sandbox: bool = False,
            request: django.http.HttpRequest | None = None,
        self.course = course
        self.repo = repo
        self.commit_sha = commit_sha
        self.flow_session = flow_session
        self.in_sandbox = in_sandbox
        self.page_uri = page_uri
        self.request = request
    """
    .. attribute:: show_correctness
    .. attribute:: show_answer
    .. attribute:: may_change_answer
    """

            show_correctness: bool,
            show_answer: bool,
            may_change_answer: bool,
            ) -> None:
        self.show_correctness = show_correctness
        self.show_answer = show_answer
        self.may_change_answer = may_change_answer

    def __bool__(self):
        # This is for compatibility: page_behavior used to be a bool argument
        # 'answer_is_final'.
        return not self.may_change_answer

    __nonzero__ = __bool__


def markup_to_html(
        page_context: PageContext,
        text: str,
        use_jinja: bool = True,
        reverse_func: Callable | None = None,
    from course.content import markup_to_html as mth

    return mth(
            page_context.course,
            page_context.repo,
            page_context.commit_sha,
            use_jinja=use_jinja,
            reverse_func=reverse_func)

class InvalidFeedbackPointsError(ValueError):
    pass


def round_point_count_to_quarters(
        value: float, atol: float = 1e-5) -> float | int:
    """
    If 'value' is close to an int, a half or quarter, return the close value,
    otherwise return the original value.
    """

    if abs(value - int(value)) < atol:
        return int(value)

    import math
    v = value * 4
    if abs(v - math.floor(v)) < _atol:
        v = math.floor(v)
Loading
Loading full blame...