Repository navigation
Initial implementation #1
Changes from 18 commits
4948958
43b1a87
43193a7
d14ad36
b11d2bf
04b9e98
dbe5469
d139a10
68a4359
d872ded
a3c5bff
781f858
82ff355
322a080
dc4a23a
4b9a5a1
d5032dd
f0d009c
29bb31c
072ab3e
5d2bc7d
28d5a46
bbc750c
7507f88
706d937
1777066
2c8ea90
812df3a
4de8375
41486ac
b8548d9
5125445
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| __pycache__/ | ||
| *.py[cod] | ||
| activetable_xblock.egg-info/** | ||
| .coverage |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| language: python | ||
| python: | ||
| - 2.7 | ||
| install: | ||
| - pip install -r test-requirements.txt | ||
| script: | ||
| - pep8 --max-line-length=100 activetable | ||
| - pylint activetable | ||
| - nosetests --with-coverage --cover-package=activetable tests/unit | ||
| notifications: | ||
| email: false |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| ActiveTable XBlock | ||
| ================== | ||
|
|
||
| This XBlock provides a tabular problem type, where students have to fill in some of the cells of a | ||
| table. | ||
|
|
||
|
|
||
| Running the tests | ||
| ----------------- | ||
|
|
||
| Install the test prerequisites: | ||
|
|
||
| pip install -r test-requirements | ||
|
|
||
| Run pep8: | ||
|
|
||
| pep8 --max-line-length=100 activetable | ||
|
|
||
| Run pylint: | ||
|
|
||
| pylint activetable | ||
|
|
||
| Run the unit tests: | ||
|
|
||
| nosetests --with-coverage --cover-package=activetable tests/unit | ||
|
|
||
|
|
||
| The table definition | ||
| -------------------- | ||
|
|
||
| The table definition is entered in a Python-like syntax (actually in a strict subset of Python). It | ||
| must be a list of lists, with all inner lists having the same lengths. The elements of the inner | ||
| lists correspond to the cells of the table. The first line contains the column headers and can only | ||
| contain string literals. All further lines represent the table body. Cells can be either string | ||
| literals, e.g. `'a string'`, numbers, e.g. `6.23`, or response cell declarations. There are two | ||
| types of response cells: | ||
|
|
||
| Numeric(answer=<correct_answer>, tolerance=<tolerance in percent>, | ||
| min_significant_digits=<number>, max_significant_digits=<number>) | ||
|
|
||
| A cell that expects a numeric answer. The tolerance is optional, and will default to the default | ||
| tolerance specified above. The restrictions for the number of significant digits are optional as | ||
| well. Significant digits are counted started from the first non-zero digit specified by the | ||
| student, and include trailing zeros. | ||
|
|
||
| String(answer='<correct answer>') | ||
|
|
||
| A cell that expects a string answer. | ||
|
|
||
| An example of a table definition: | ||
|
|
||
| [ | ||
| ['Event', 'Year'], | ||
| ['French Revolution', Numeric(answer=1789)], | ||
| ['Krakatoa volcano explosion', Numeric(answer=1883)], | ||
| ["Proof of Fermat's last theorem", Numeric(answer=1994)], | ||
| ] | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Now that we're using XBlocks, we can (and should) be designing these sorts of things with Child blocks if we can. This work of doing custom parsing is a lot to maintain when we have things like XBlock-utils to automate much of our form building. If we don't do this now, we're going to be stuck with it.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Kelketek The client explicitly requested to not turn this into a point-and-click interface. See Xavier's comments on the ticket for details. I think child XBlocks would be a bad fit for this anyway. Making every cell an XBlock would make creating tables really awkward, and it wouldn't be particularly efficient performance-wise either. What I could imagine is to design a tailored graphical interface in JavaScript, but, as mentioned above, we were explicitly asked not to do that.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Very well. |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """ActiveTable XBlock top-level package. | ||
|
|
||
| See activetable.activetable for more information. | ||
| """ | ||
| from .activetable import ActiveTableXBlock |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """An XBlock with a tabular problem type that requires students to fill in some cells.""" | ||
| from __future__ import absolute_import, division, unicode_literals | ||
|
|
||
| import textwrap | ||
|
|
||
| from xblock.core import XBlock | ||
| from xblock.fields import Dict, Float, Integer, Scope, String | ||
| from xblock.fragment import Fragment | ||
| from xblock.validation import ValidationMessage | ||
| from xblockutils.resources import ResourceLoader | ||
| from xblockutils.studio_editable import StudioEditableXBlockMixin | ||
|
|
||
| from .cells import NumericCell | ||
| from .parsers import ParseError, parse_table, parse_number_list | ||
|
|
||
| loader = ResourceLoader(__name__) # pylint: disable=invalid-name | ||
|
|
||
|
|
||
| class ActiveTableXBlock(StudioEditableXBlockMixin, XBlock): | ||
| """An XBlock with a tabular problem type that requires students to fill in some cells.""" | ||
|
|
||
| display_name = String( | ||
| display_name='Display Name', | ||
| help='The title Studio uses for the component.', | ||
| scope=Scope.settings, | ||
| default='ActiveTable problem' | ||
| ) | ||
| table_definition = String( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See the above comment about child blocks. I really think we should be using them here-- this methodology was built out of limitations that don't exist in XBlock. |
||
| display_name='Table definition', | ||
| help='The definition of the table in Python-like syntax.', | ||
| scope=Scope.content, | ||
| multiline_editor=True, | ||
| resettable_editor=False, | ||
| default=textwrap.dedent("""\ | ||
| [ | ||
| ['Column header 1', 'Column header 2'], | ||
| ['Enter "answer" here:', String(answer='answer')], | ||
| [42, Numeric(answer=42, tolerance=0.0)], | ||
| ] | ||
| """) | ||
| ) | ||
| help_text = String( | ||
| display_name='Help text', | ||
| help='The text that gets displayed when clicking the "+help" button. If you remove the ' | ||
| 'help text, the help feature is disabled.', | ||
| scope=Scope.content, | ||
| multiline_editor=True, | ||
| resettable_editor=False, | ||
| default='Fill in the cells highlighted in yellow with the correct answers. ' | ||
| 'When you are done, you can check your answers using the button below the table.', | ||
| ) | ||
| column_widths = String( | ||
| display_name='Column widths', | ||
| help='Set the width of the columns in pixels. The value should be a Python-like list of ' | ||
| 'numerical values. The total width of the table should not be more than 800. No value ' | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of "No value", say, "Omitting this value" |
||
| 'will result in equal-width columns with a total width of 800 pixels.', | ||
| scope=Scope.content, | ||
| ) | ||
| row_heights = String( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The row heights and column widths fields have a reset button next to them in the interface. However, this button does not seem to work. Clicking it makes the field appear empty, but saving it does not actually save an empty string-- it just reverts to whatever it was before you hit the button. Putting in a new value does get saved, though. |
||
| display_name='Row heights', | ||
| help='Set the heights of the rows in pixels. The value should be a Python-like list of ' | ||
| 'numerical values. Rows may grow higher than the specified value if the text in some cells ' | ||
| 'in the row is long enough to get wrapped in more than one line.', | ||
| scope=Scope.content, | ||
| ) | ||
| default_tolerance = Float( | ||
| display_name='Default tolerance', | ||
| help='The tolerance in pecent that is used for numerical response cells you did not ' | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "percent" |
||
| 'specify an explicit tolerance for.', | ||
| scope=Scope.content, | ||
| default=1.0, | ||
| ) | ||
| max_score = Float( | ||
| display_name='Maximum score', | ||
| help='The number of points students will be awarded when solving all fields correctly. ' | ||
| 'For partially correct attempts, the score will be pro-rated.', | ||
| scope=Scope.settings, | ||
| default=1.0, | ||
| ) | ||
|
|
||
| editable_fields = [ | ||
| 'display_name', | ||
| 'table_definition', | ||
| 'help_text', | ||
| 'column_widths', | ||
| 'row_heights', | ||
| 'default_tolerance', | ||
| 'max_score', | ||
| ] | ||
|
|
||
| # Dictionary mapping cell ids to the student answers. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are cell IDs stable while editing? Inserting a row in the table will make students' existing answers mismatched, right? Is this understood by the course team? Can we say something in the help text?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, cell IDs are really just strings like |
||
| answers = Dict(scope=Scope.user_state) | ||
| # Number of correct answers. | ||
| num_correct_answers = Integer(scope=Scope.user_state) | ||
| # The number of points awarded. | ||
| score = Float(scope=Scope.user_state) | ||
|
|
||
| has_score = True | ||
|
|
||
| def parse_fields(self): | ||
| """Parse the user-provided fields into more processing-friendly structured data.""" | ||
| if self.table_definition: | ||
| self.thead, self.tbody = parse_table(self.table_definition) | ||
| else: | ||
| self.thead = self.tbody = None | ||
| return | ||
| if self.column_widths: | ||
| self._column_widths = parse_number_list(self.column_widths) | ||
| else: | ||
| self._column_widths = [800 / len(self.thead)] * len(self.thead) | ||
| if self.row_heights: | ||
| self._row_heights = parse_number_list(self.row_heights) | ||
| else: | ||
| self._row_heights = [36] * (len(self.tbody) + 1) | ||
|
|
||
| def postprocess_table(self): | ||
| """Augment the parsed table definition with further information. | ||
|
|
||
| The additional information is taken from other content and student state fields. | ||
| """ | ||
| self.response_cells = {} | ||
| for row, height in zip(self.tbody, self._row_heights[1:]): | ||
| row['height'] = height | ||
| if row['index'] & 1: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This crossed my eyes for a moment. Maybe "% 2" instead?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't care, so I can go with |
||
| row['class'] = 'even' | ||
| else: | ||
| row['class'] = 'odd' | ||
| for cell in row['cells']: | ||
| cell.id = 'cell_{}_{}'.format(cell.index, row['index']) | ||
| if not cell.is_static: | ||
| self.response_cells[cell.id] = cell | ||
| cell.value = self.answers.get(cell.id) | ||
| cell.height = height - 2 | ||
| if isinstance(cell, NumericCell) and cell.abs_tolerance is None: | ||
| cell.set_tolerance(self.default_tolerance) | ||
| if cell.value is None: | ||
| cell.classes = 'active unchecked' | ||
| elif cell.check_response(cell.value): | ||
| cell.classes = 'active right-answer' | ||
| else: | ||
| cell.classes = 'active wrong-answer' | ||
|
|
||
| def student_view(self, context=None): | ||
| """Render the table.""" | ||
| self.parse_fields() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm surprised to see the fields being parsed each time. Not sure why that bothers me, but it seems like significant work that could be done just once.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The result of parsing is a hierachical structure of Python data types that are not JSON-serializable, so I don't see an easy way of doing the parsing only once. I initially added the parsing step to |
||
| self.postprocess_table() | ||
|
|
||
| context = dict( | ||
| help_text=self.help_text, | ||
| total_width=sum(self._column_widths) if self._column_widths else None, | ||
| column_widths=self._column_widths, | ||
| head_height=self._row_heights[0] if self._row_heights else None, | ||
| thead=self.thead, | ||
| tbody=self.tbody, | ||
| ) | ||
| html = loader.render_template('templates/html/activetable.html', context) | ||
|
|
||
| css_context = dict( | ||
| correct_icon=self.runtime.local_resource_url(self, 'public/img/correct-icon.png'), | ||
| incorrect_icon=self.runtime.local_resource_url(self, 'public/img/incorrect-icon.png'), | ||
| unanswered_icon=self.runtime.local_resource_url(self, 'public/img/unanswered-icon.png'), | ||
| ) | ||
| css = loader.render_template('templates/css/activetable.css', css_context) | ||
|
|
||
| frag = Fragment(html) | ||
| frag.add_css(css) | ||
| frag.add_javascript(loader.load_unicode('static/js/src/activetable.js')) | ||
| frag.initialize_js('ActiveTableXBlock', dict( | ||
| num_correct_answers=self.num_correct_answers, | ||
| num_total_answers=len(self.answers) if self.answers is not None else None, | ||
| score=self.score, | ||
| max_score=self.max_score, | ||
| )) | ||
| return frag | ||
|
|
||
| @XBlock.json_handler | ||
| def check_answers(self, data, unused_suffix=''): | ||
| """Check the answers given by the student. | ||
|
|
||
| This handler is called when the "Check" button is clicked. | ||
| """ | ||
| self.parse_fields() | ||
| self.postprocess_table() | ||
| correct = { | ||
| cell_id: self.response_cells[cell_id].check_response(value) | ||
| for cell_id, value in data.iteritems() | ||
| } | ||
| # Since the previous statement executed without error, the data is well-formed enough to be | ||
| # stored. We now know it's a dictionary and all the keys are valid cell ids. | ||
| self.answers = data | ||
| self.num_correct_answers = sum(correct.itervalues()) | ||
| self.score = self.num_correct_answers * self.max_score / len(correct) | ||
| self.runtime.publish(self, 'grade', dict(value=self.score, max_value=self.max_score)) | ||
| return dict( | ||
| correct=correct, | ||
| num_correct_answers=self.num_correct_answers, | ||
| num_total_answers=len(correct), | ||
| score=self.score, | ||
| max_score=self.max_score, | ||
| ) | ||
|
|
||
| def validate_field_data(self, validation, data): | ||
| """Validate the data entered by the user. | ||
|
|
||
| This handler is called when the "Save" button is clicked in Studio after editing the | ||
| properties of this XBlock. | ||
| """ | ||
| def add_error(msg): | ||
| """Add a validation error.""" | ||
| validation.add(ValidationMessage(ValidationMessage.ERROR, msg)) | ||
| try: | ||
| parse_table(data.table_definition) | ||
| except ParseError as exc: | ||
| add_error('Problem with table definition: ' + exc.message) | ||
| if data.column_widths: | ||
| try: | ||
| parse_number_list(data.column_widths) | ||
| except ParseError as exc: | ||
| add_error('Problem with column widths: ' + exc.message) | ||
| if data.row_heights: | ||
| try: | ||
| parse_number_list(data.row_heights) | ||
| except ParseError as exc: | ||
| add_error('Problem with row heights: ' + exc.message) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """Classes representing table cells. | ||
|
|
||
| These classes are used mainly as namespaces to dump all data associated with a cell. There is no | ||
| expectation that all attributes are set in __init__() or that attributes are controlled byt the | ||
| classes themselves. | ||
| """ | ||
| from __future__ import absolute_import, division, unicode_literals | ||
|
|
||
| import decimal | ||
|
|
||
|
|
||
| class Cell(object): | ||
| """Abstract base class for all cells.""" | ||
|
|
||
| def __eq__(self, other): | ||
| """Test for equality based on type and attribute values.""" | ||
| return type(self) is type(other) and vars(self) == vars(other) | ||
|
|
||
|
|
||
| class StaticCell(Cell): | ||
| """A static cell with a fixed value in the table body.""" | ||
|
|
||
| is_static = True | ||
|
|
||
| def __init__(self, value): | ||
| self.value = value | ||
|
|
||
|
|
||
| class NumericCell(Cell): | ||
| """A numeric response cell.""" | ||
|
|
||
| is_static = False | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It'd be nicer to move this to Cell, and let StaticCell be the only one that needs to override it. |
||
| placeholder = 'numeric response' | ||
|
|
||
| def __init__(self, answer, tolerance=None, | ||
| min_significant_digits=None, max_significant_digits=None): | ||
| """Set the correct answer and the allowed relative tolerance in percent.""" | ||
| self.answer = answer | ||
| self.abs_tolerance = None | ||
| self.set_tolerance(tolerance) | ||
| self.min_significant_digits = min_significant_digits | ||
| self.max_significant_digits = max_significant_digits | ||
|
|
||
| def set_tolerance(self, tolerance): | ||
| """Set the tolerance to the specified value, if it is not None.""" | ||
| if tolerance is not None: | ||
| self.abs_tolerance = abs(self.answer) * tolerance / 100.0 | ||
|
|
||
| def check_response(self, student_response): | ||
| """Return a Boolean value indicating whether the student response is correct.""" | ||
| try: | ||
| value = float(student_response) | ||
| except ValueError: | ||
| return False | ||
| if self.min_significant_digits or self.max_significant_digits: | ||
| # pylint: disable=no-member | ||
| digits = len(decimal.Decimal(student_response).as_tuple().digits) | ||
| # pylint: enable=no-member | ||
| if self.min_significant_digits and digits < self.min_significant_digits: | ||
| return False | ||
| if self.max_significant_digits and digits > self.max_significant_digits: | ||
| return False | ||
| return abs(value - self.answer) <= self.abs_tolerance | ||
|
|
||
|
|
||
| class StringCell(Cell): | ||
| """A string response cell.""" | ||
|
|
||
| is_static = False | ||
| placeholder = 'text response' | ||
|
|
||
| def __init__(self, answer): | ||
| """Set the correct answer.""" | ||
| self.answer = answer | ||
|
|
||
| def check_response(self, student_response): | ||
| """Return a Boolean value indicating whether the student response is correct.""" | ||
| return student_response == self.answer | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is the course team really OK with strict equality here? No .strip() or .lower() ?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My suspicion is that this feature hasn't received a lot of use in the JSInput version of this code (which also used exact string matching). It would be nice to use some configurable fuzzy matching here, but that's probably for a later version of the code. For now, I'll simply add |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
"String" is pretty geeky, wouldn't course teams be happier with "Text"?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@dseaton Are you fine with renaming
StringtoText, or would that cause any migration problems for you?