### Python3 Example Question for CodeRunner Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html An example of a simple Python3 question to be created within the CodeRunner Moodle question type. It includes the question prompt and expected outputs for given inputs, suitable for testing and demonstrating functionality. ```text Question: Write a function _sqr(n)_ that returns the square of its parameter _n_. Test Cases: Test Expected print(sqr(-7)) 49 print(sqr(5)) 25 print(sqr(-1)) 1 print(sqr(0)) 0 print(sqr(-100)) 10000 ``` -------------------------------- ### Python Example: Hello World Randomization Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html A Python example demonstrating how to randomize the output of a 'Hello world' program by using Twig template parameters for the name. This requires setting specific template parameters and enabling Twig processing within CodeRunner. ```json { "name": "{{ random(["Bob", "Carol", "Ted", "Alice"]) }}" } ``` ```python print("Hello {{name}}") ``` -------------------------------- ### Python Template Parameter Example Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html Demonstrates using Python with Twig for conditional code execution based on template parameters. It shows how to conditionally add a docstring and dynamically set pylint options and error messages. ```python import subprocess import os import sys import re def code_ok(prog_to_test): {% if QUESTION.parameters.isfunction %} prog_to_test = "'''Dummy module docstring'''\n" + prog_to_test {% endif %} try: source = open('source.py', 'w') source.write(prog_to_test) source.close() env = os.environ.copy() env['HOME'] = os.getcwd() pylint_opts = [] {% for option in QUESTION.parameters.pylintoptions %} pylint_opts.append('{{option}}') {% endfor %} cmd = ['pylint', 'source.py'] + pylint_opts result = subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT, env=env) except Exception as e: result = e.output # Have to remove pylint's annoying config file output message before # checking for a clean run. [--quiet option in pylint 2.0 fixes this]. result = re.sub('Using config file.*', '', result).strip() if result: print("{{QUESTION.parameters.errormessage | e('py')}}", file=sys.stderr) print(result, file=sys.stderr) return False ``` -------------------------------- ### Table UI Configuration Example Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This JSON object demonstrates the configuration parameters for the Table UI plug-in. It specifies the number of rows and columns, header labels, and enables dynamic row addition. This UI is used in question types like `python3_program_testing`. ```json { "num_rows": 3, "num_columns": 2, "column_headers": ["Test", "Result"], "dynamic_rows": true } ``` -------------------------------- ### C Per-Test Template Example for Student Submission Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This C code demonstrates a per-test template used in the Moodle Coderunner. It shows how student code is integrated into a program that includes a specific test case. The template wraps the student's function and a main function to execute a given test, printing the result. ```c #include // --- Student's answer is inserted here ---- int main() { printf("%d\n", sqr(-11)); return 0; } ``` -------------------------------- ### Clone CodeRunner and Adaptive Behaviour Plugins using Git Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This snippet demonstrates how to install the CodeRunner question type and adaptive behaviour plugins by cloning their respective repositories directly into the Moodle installation directory using git. Ensure you are in the top-level folder of your Moodle install before running these commands. Correct ownership and access rights may be required after cloning. ```shell git clone https://github.com/trampgeek/moodle-qtype_coderunner.git question/type/coderunner git clone https://github.com/trampgeek/moodle-qbehaviour_adaptive_adapted_for_coderunner.git question/behaviour/adaptive_adapted_for_coderunner ``` -------------------------------- ### Example Expanded C Code from Combinator Template Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This C code illustrates the expansion of the combinator template when used with three test cases. It shows how the `STUDENT_ANSWER` and `TEST.testcode` are integrated, and how the `SEPARATOR` is placed between the outputs of each test. The braces `{}` create local scope for each test's execution. ```c #include #include #include #include #include #include #define SEPARATOR "##" int sqr(int n) { return n * n; } int main() { { printf("%d\n", sqr(-9)); printf("%s\n", SEPARATOR); } { printf("%d\n", sqr(11)); printf("%s\n", SEPARATOR); } { printf("%d\n", sqr(-13)); return 0; } } ``` -------------------------------- ### Run CodeRunner Unit Tests with PHPUnit Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html These commands initiate the CodeRunner unit tests using PHPUnit. Ensure PHPUnit is installed and configured. Replace 'www-data' with your web server user (e.g., 'apache') if necessary. Tests may show skipped/failed for uninstalled language sandboxes, which can typically be ignored. ```shell cd sudo php admin/tool/phpunit/cli/init.php sudo -u www-data vendor/bin/phpunit --verbose --testsuite="qtype_coderunner test suite" or sudo -u www-data vendor/bin/phpunit --verbose --testsuite="qtype_coderunner_testsuite" ``` -------------------------------- ### Twig Templating for Dynamic Test Cases Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This example demonstrates parameterizing test cases using Twig. By referencing template parameters like 'functionname', the test code can adapt to the dynamically generated question content, ensuring consistency between the question and its evaluation. ```python {{ functionname }}([11, 23, 15, -7]) ``` -------------------------------- ### JSON Output Example with Abort for Per-Test Grading Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This JSON object demonstrates how to abort further testing after a specific test case. The 'abort': true attribute, along with 'fraction': 0.0 and a message in 'got', will mark the test as failed and stop subsequent tests. ```json { "fraction":0.0, "got":"Invalid submission!", "abort":true } ``` -------------------------------- ### Moodle Prototype Usage Script Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html Displays an index of question prototype usage within a specific category. This script is located at `/question/type/coderunner/prototypeusageindex.php`. ```php ``` -------------------------------- ### Moodle Bulk Test Script Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html Tests sample answers on all questions within a selected category and reports successes and failures. This script is located at `/question/type/coderunner/bulktestindex.php` and is intended for use with the Moodle master branch. ```php ``` -------------------------------- ### Example HTML for CodeRunner UI Input Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html A basic HTML input element used within the CodeRunner question type. The 'name' attribute ('crui_input') is significant for serialization, and the 'coderunner-ui-element' class indicates it's managed by the UI. This example is a text input for collecting user-entered data. ```html ``` -------------------------------- ### C Function Template for Squaring a Number Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This C template demonstrates how to set up a question where the student needs to complete a function. It shows how to define the student's answer block and how to format the output using printf. The `{{ TEST.testcode }}` placeholder is used to insert specific test cases. ```c #include #include #include int sqr(int n) { {{ STUDENT_ANSWER }} } int main() { printf("%d\n", {{ TEST.testcode }}); return 0; } ``` -------------------------------- ### Table UI Data Serialization Example Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html The serialisation of the Table UI is a JSON array of arrays, representing the data within each cell. An empty string is used if all cells are empty, simplifying the representation. ```json [["cell_0_0", "cell_0_1"], ["cell_1_0", "cell_1_1"]] ``` -------------------------------- ### Twig Escaper Usage Examples Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html Illustrates various Twig escaper functions used to safely render student submissions within templates. These include Python, Java, C, Matlab, JavaScript, and HTML escaper functions. ```twig {{ STUDENT_ANSWER | e('py') }} ``` ```twig {{ STUDENT_ANSWER | e('java') }} ``` ```twig {{ STUDENT_ANSWER | e('c') }} ``` ```twig student_answer = sprintf('{{ STUDENT_ANSWER | e('matlab')}}'); ``` ```twig {{ STUDENT_ANSWER | e('js') }} ``` ```twig {{ STUDENT_ANSWER | e('html') }} ``` -------------------------------- ### Example JSON Serialization of Student Answer Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This JSON object represents the serialized student answer for a CodeRunner HTML UI. It contains an attribute for each 'name' used in the HTML. The value is a list of strings, corresponding to the DOM order of elements with that name. This example shows a single text input named 'crui_input' with the student's input 'floodle'. ```json {"crui_input":["floodle"]} ``` -------------------------------- ### Python: Create Question Instance for Display Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This function initializes a question for display to a student. It gathers user information, locates the question prototype, generates a random seed, processes template parameters (including merging prototype and question parameters), and optionally performs Twig expansion. Finally, it saves the question instance. Dependencies include 'get_current_moodle_user_info', 'locate_prototype_question', 'make_new_random_seed', 'process_template_params', 'merge_json', and 'save_question_instance'. ```python def create_question_instance(question): """ Initialise a question for display""" # Set up the environment question.student = get_current_moodle_user_info() question.prototype = locate_prototype_question(question.prototype_name) question.random_seed = make_new_random_seed() # Process the question and prototype template parameters question.template_params = process_template_params(question) prototype_params = process_template_params(question.prototype) question.template_params = merge_json(prototype_params, question.template_params) if question.twigall: # Twig expand question text, sample answer, answer preload, penalty_regime, # all test case fields and global extra. The just-computed # template parameters provide (most of) the twig environment. set_twig_environment(question.random_seed, question.student, question.template_params) for each twiggable attribute of question: question.attribute = twig_expand(question.attribute) save_question_instance(question) ``` -------------------------------- ### Table UI Locked Cells Specification Example Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This JSON array defines specific cells within the Table UI that should be locked and disabled for user input. This is useful when pre-defining some cell values, ensuring they are not accidentally altered by the student. ```json "locked_cells": [[0, 0], [1, 0]] ``` -------------------------------- ### Twig Template Parameter for Function Name Randomization Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This example shows how Twig can be used within template parameters to randomize the value of a 'functionname' variable. This allows for generating different versions of a question dynamically. The output is a JSON string that is then decoded. ```json { "functionname": "{{ random(["find_first", "get_first", "pick_first"]) }}" } ``` -------------------------------- ### Python Template for Pylint Code Analysis Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This Python template demonstrates an advanced use case where the student's code is written to a file and then analysed using an external tool (pylint). It includes a helper function `code_ok` to perform the pylint check and handle potential exceptions. The `{{ STUDENT_ANSWER | e('py') }}` syntax ensures the student's code is properly escaped for Python execution. ```python import subprocess import os import sys def code_ok(prog_to_test): """Check prog_to_test with pylint. Return True if OK or False if not. Any output from the pylint check will be displayed by CodeRunner """ try: source = open('source.py', 'w') source.write(prog_to_test) source.close() env = os.environ.copy() env['HOME'] = os.getcwd() cmd = ['pylint', 'source.py'] result = subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT, env=env) except Exception as e: result = e.output if result.strip(): print("pylint doesn't approve of your program", file=sys.stderr) print(result, file=sys.stderr) print("Submission rejected", file=sys.stderr) return False else: return True __student_answer__ = """{{ STUDENT_ANSWER | e('py') }}""" if code_ok(__student_answer__): __student_answer__ += '\n' + """{{ TEST.testcode | e('py') }}""" exec(__student_answer__) ``` -------------------------------- ### Example C Program Expansion with Student Code Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/authorguide.md This example demonstrates how the C function template is expanded when a student provides code for a function named `sqr` that calculates the square of an integer. The template inserts the student's function definition and then populates the main function with calls to `sqr` for each specified test case, printing the results. ```c #include #include #include #include #include #include #define SEPARATOR "##" int sqr(int n) { return n * n; } int main() { { printf("%d\n", sqr(-11)); } printf("%s\n", SEPARATOR); { printf("%d\n", sqr(9)); } return 0; } ``` -------------------------------- ### Python Code Execution with Student Answer Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This Python snippet demonstrates how the Coderunner question type executes student-submitted code. It first checks the validity of the student's answer using 'code_ok' and then concatenates it with test code before execution via 'exec'. Dependencies include the 'code_ok' function and potentially Jinja2 for templating. ```python else: return True __student_answer__ = """{{ STUDENT_ANSWER | e('py') }}""" if code_ok(__student_answer__): __student_answer__ += '\n' + """{{ TEST.testcode | e('py') }}""" exec(__student_answer__) ``` -------------------------------- ### JSON Output Example for Per-Test Grading Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This JSON object represents the expected output from a per-test template grader. It defines the grading fraction and provides feedback. The 'fraction' field is crucial for awarding marks, and 'got' provides a custom message for the results table. ```json { "fraction":0.5, "got": "Half the answers were right!" } ``` -------------------------------- ### C Function Preload Example for Moodle CodeRunner Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/docs/index.md This C code snippet shows how to use the 'Preload' capability in Moodle CodeRunner to pre-fill the student's answer box. This is useful for providing context or a starting point for the student's solution, such as a function signature with a comment indicating where to insert the code. ```c // A function to return the square of its parameter n int sqr(int n) { // *** Replace this line with your code ``` -------------------------------- ### C Code Expansion with Twig Template Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This C code demonstrates how a student's answer and test code are integrated using Twig placeholders within a template. The expanded code is then compiled and run in a sandbox environment. Dependencies include the Twig template engine and standard C libraries. ```c #include #include #include {{ STUDENT_ANSWER }} int main() { {{ TEST.testcode }}; return 0; } ``` -------------------------------- ### Python Example for Generating Per-Test JSON Output Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This Python code snippet shows how to generate the JSON output required for a per-test template grader using Python's `json.dumps` function. It converts a Python dictionary, including boolean values, into a JSON string with correct literals. ```python import json # Example for aborting tests output_data = {"fraction":0.0, "got":"Invalid submission!", "abort":True} json_output = json.dumps(output_data) print(json_output) # Example for partial success output_data_partial = {"fraction":0.5, "got": "Half the answers were right!"} json_output_partial = json.dumps(output_data_partial) print(json_output_partial) ``` -------------------------------- ### Pseudocode for Running a Single Test Case Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This pseudocode describes how an individual test case is executed. It involves expanding the question template with the specific test case parameters, running the generated program on the Jobe sandbox, and then grading the outcome of that single execution. ```pseudocode def run_single_test_case(question, test): question.template_params['TEST'] = test program_to_run = twig_expand(question.template, question.template_params) run_result = run_job_on_jobe(program_to_run, question.run_language) return grade_test(run_result) ``` -------------------------------- ### Implementing New Question Types with Python Prototype Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html A description of a prototype question `prototype_c_via_python.xml` which demonstrates how to define a new question type by scripting the compilation and execution process in Python. This serves as a template for supporting non-built-in languages. ```xml C program via Python prototype Write a C program that prints <b>&lt;Your Name&gt;</b> If the program printed <b>&lt;Your Name&gt;</b> then it is correct. 1.0000000 0.3333333 0 10 <#languages> <#question\_languages> python prototype_c_via_python.py python prototype_c_via_python.py $@FILE@$ YOURNAME ``` -------------------------------- ### Ace Editor Gapfiller UI Gap Specifier Example Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html Demonstrates how to specify a gap in the Ace editor for the gapfiller UI. The format {[20-40]} indicates a gap with a default width of 20 and a maximum width of 40 characters. If the second number is omitted, the field width can expand arbitrarily. This is used when the source text is provided via the 'ui_source' parameter. ```text {[20-40]} ``` -------------------------------- ### Initialize PHPUnit Environment Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/docs/index.md Command to initialize the PHPUnit environment for testing Moodle modules, specifically for CodeRunner. This sets up the necessary testing framework within the Moodle installation. ```bash cd sudo php admin/tool/phpunit/cli/init.php ``` -------------------------------- ### C Function Template Example for Moodle CodeRunner Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/docs/index.md This C code snippet demonstrates a basic question template for Moodle CodeRunner. It includes the standard library includes, a function definition with a placeholder for student code, and a main function to print the result of a test case. The `{{ STUDENT_ANSWER }}` and `{{ TEST.testcode }}` are placeholders that CodeRunner replaces with student input and test code, respectively. ```c #include #include #include int sqr(int n) { {{ STUDENT_ANSWER }} } int main() { printf("%d\n", {{ TEST.testcode }}); return 0; } ``` -------------------------------- ### Compile and Run C Program using Python Source: https://github.com/trampgeek/moodle-qtype_coderunner/blob/master/site/index.html This Python snippet demonstrates how to compile and execute a student-submitted C program. It handles compilation errors and captures program output or runtime errors. Dependencies include the 'subprocess' and 'sys' modules. ```python import subprocess import sys # Write the student code to a file prog.c student_answer = """{{ STUDENT_ANSWER | e('py') }}""" with open("prog.c", "w") as src: print(student_answer, file=src) # Compile {% if QUESTION.parameters.cflags is defined %} cflags = """{{ QUESTION.parameters.cflags | e('py') }}""" {% else %} cflags = "-std=c99 -Wall -Werror" {% endif %} return_code = subprocess.call("gcc {0} -o prog prog.c".format(cflags).split()) if return_code != 0: print("** Compilation failed. Testing aborted **", file=sys.stderr) # If compile succeeded, run the code. if return_code == 0: try: output = subprocess.check_output(["./prog"], universal_newlines=True) print(output) except subprocess.CalledProcessError as e: if e.returncode > 0: if e.output: print(e.output) else: if e.output: print(e.output, file=sys.stderr) if e.returncode < 0: print("Task failed with signal", -e.returncode, file=sys.stderr) print("** Further testing aborted **", file=sys.stderr) ```