Плагин vpl moodle руководство

—D. Thiebaut (talk) 11:51, 19 September 2014 (EDT)


The tutorials below are intended for instructors teaching programming languages, and interested in setting up Moodle VPL modules to automatically test student programs.

The modules are listed in chronological order, most recent at the end. Because VPL is a complex system to master, the
early tutorials may not be built using the best approach, but provide functionality. The later modules use more sophisticated features of VPL.

Feel freel to send me your own modules or discoveries, at dthiebaut@smith.edu, and I will be happy to include them here.

Reference Material

  • A video I created to help explain how I use VPL for my courses.

(Supporting Files for Video )

  • Juan Carlos Rodríguez-del-Pino, Enrique Rubio-Royo, Zenón, and J. HernándezFigueroa, A Virtual Programming Lab for Moodle with automatic assessment and anti-plagiarism features, Proc. WorldComp12, July 2012, Las Vegas, USA. (pdf)
  • Automatic Evaluation of Computer Programs using Moodle’s Virtual Programming Lab (VPL) Module, D. Thiebaut, accepted for presentation at CCSCNE 2015.
  • YouTube video 1: setting up a simple VPL module Part 1 (for use at CCSCNE2015)
  • YouTube video 2: setting up a simple VPL module, Part 2 (for use at CCSCNE2015)

Setting up a VPL module for Python

Moodle Virtual-Programming-Lab (VPL)

Tutorial Language Description

Moodle/VPL Server Setup

This tutorial provides rough directions for setting up two virtual servers that will host Moodle on one of them, and the VPL jail server on the other. This setup is used by the tutorials below on the use of VPL to test student programs.

Moodle VPL Example 1: Hello World!

Python

This tutorial illustrates how to setup VPL to test a simple Python 3 program that prints the string «Hello World!» to the console.

Moodle VPL Example 2: Min of 3 Numbers

Python

This tutorial illustrates how to setup VPL to test a simple Python 3 program that receives 3 numbers from the console and prints the smallest of the 3. The program is tested 3 times, with 3 different sets of input numbers.

Moodle VPL Example 3: Rock-Paper-Scissors

Python

This tutorial shows the settings for a VPL activity that would test a Python program that plays the game of Rock-Paper-Scissors. The program tested is expected to get its input as pairs of letters (PP, RS, PS, etc), indicates the winner of each round, and stops when one player is 3 points above the other.

Moodle VPL Example 4: Gremlins in my File!

Python

This tutorial illustrates how to setup a VPL activity that tests a student program that reads a text file, modifies it, and stores the new content back in the original file. This requires an additional python program that sets up the environment for the first one to run, provides it the information it needs, and captures its output.

Moodle VPL Example 5: Print a 2D chessboard

Python

This tutorial illustrates how to setup a VPL activity that tests a student program that asks the user for an integer and then prints a 2D chessboard (alternating black & white cells) with that dimension. The size of a cell is a 3×3 character on the screen.

Moodle VPL Example 6: Display a rectangle of stars

Assembly
Nasm

This tutorial illustrates the setup of a VPL activity to test an assembly language program that displays a fixed string (rectangle of stars).

Moodle VPL Example 7: Assign a grade inversely proportional to the size of the executable

Assembly
Nasm

This tutorial illustrates how to setup a VPL activity that will test the size of the executable version of an assembly language program. This can easily be adapted to other languages.

Moodle VPL Example 8: A Hello World Program in Java

Java

This tutorial illustrates how to setup a VPL activity to test a simple Hello World program in Java.

Moodle VPL Example 9: A Multi-File Java Program with A Data File

Java

This tutorial illustrates the setting of a VPL activity that evaluates a 2-class Java project that gets its input from a data file. The project is tested with 4 different data files; one provided by the students, 3 provided by the instructor.

Moodle VPL Example 10: Evaluation Using A Custom Python Program

Python

This tutorial illustrates how to evaluate student work using a custom Python program. Such evaluation allows for more complex testing than enabled by the VPL .cases file.

Moodle VPL Example 11: Testing a Java Class Using another Class as Tester.

Java

This tutorial sets up an environment to test different methods of a Java class provided by the students, and uses a derived class provided by the instructor to activate the student classes.

Moodle VPL Example 12: Using a Java Tester for testing Student Java Program.

Java

This tutorial shows how to setup a more sophisticated testing environment for evaluating and grading Java program.

Moodle VPL Example 13: Testing 2 classes, one Holding a Data Structure, the Other Holding a Test Class.

Java

This VPL module tests two Java classes, one inherited from the other. The test checks that one class does not access directly a member array of the super class (look for presence of [ ] brackets in code). Different grades are given depending on various stages of success.

Moodle VPL Example 14: Testing Student List Class and Verifying Functionality.

Java

This VPL module tests a data structure provided by the student using a class provided by the instructor. The instructor class tests various methods. The grade is proportional to the number of correct output lines.

Moodle VPL Example 15: Looping through Tests in vpl_evaluate.sh. Testing Exceptions.

Java

This VPL module tests how a program uses exceptions to parse a simple text file containing numbers. The vpl_evaluate.sh script generates 3 tests, and runs through all 3 of them. Vpl_evaluate.sh skips non digits and non minus characters when comparing the output of the submitted program to the expected output.

Moodle VPL Example 16: Catching Programs Stuck in Infinite Loops.

Java

This VPL module is an extension of the previous module (#15), and catches java programs that hang in infinite loops.

Moodle VPL Example 17: Verifying that ASM Program Contains Key Functions.

Assembly
Nasm

This VPL module tests that an assembly program actually declares and calls 3 key functions.

Moodle VPL Example 18: Test Function of Student Program Multiple Times.

Assembly
Nasm

This VPL module tests a function in the student program and calls it several times to see if it performs correctly. The _start label of the student program is invalidated, and the student program is linked with a test program that calls the student function as an extern.

Moodle VPL Example 19: Feed Different Tests on Command Line.

Java

This VPL module tests a Java program that outputs 0, 1, or several numbers depending on an input provided on the program’s command line.

Moodle VPL Example 20: Test Elapsed Time of Student Program

Java

This VPL module tests a Java program and verify that its execution is greater than some predefined amount of time. Otherwise the program may be short-circuiting the execution and outputting a preprocessed answer.

Moodle VPL Example 21: A Java Test Program that Evaluates Student’s Submitted Class and Methods

Java

This VPL module uses a Java test program that energizes the student’s submitted class, activating various methods, and generates OK or FAIL strings for each test given. The vpl_evaluate.sh script simply counts the # of OK strings generated and gives grade proportional to it.

Moodle VPL Example 22: Test functions in the student programs, checks stack and register invariance, and verifies that solution provided is recursive.

Assembly
Nasm

This VPL module requires the student to submit a program that contains only global assembly language functions. The module uses a test program in assembly that calls the functions with a given set of parameters, and tests whether the returned values are correct or not. The test program also verifies that none of the Pentium registers are modified. The testing script also ensures that the student program uses recursion for his/her solution.

Moodle VPL Example 23: Test a Python program that performs basic input/output operations.

Python

This VPL module is written mostly in Python. vpl_evaluates simply calls a python program that tests the student’s python code. The python test first attempts to run the student program as a subprocess to catch possible errors or crash. If this is successful, then the student code is imported and run, with its stdin and stdout redirected from and to files controlled by the test program.

Testing a Bash script

Bash

This setup tests a bash script submitted by students. The script acts as a teller machine, getting an integer on the command line and printing 4 integers out, corresponding to the number of $20-bills, number of $10-bills, number of $5-bills, and number of $1-bills.

Testing an Assembly Program with Time-Out

Assembly
Nasm

This setup tests a recursive program in assembly (binary search) that may time-out (possibly because of weird recursive coding.) The evaluate script will abort if the program takes longer than a specified amount of time. This uses a bash script for vpl_evaluate.sh and vpl_run.sh.

Testing a C Program

C

This setup tests a C program that is supposed to replicate some of the functionality of the Linux grep command. In particular, the C program should get its input from the command line and support the «-i» switch, for case-insensitive searching.

Tips & Tricks

A collection of notes, recommendations, tips, tricks, and modifications. For example, we describe how to strip comments from java or assembly language comments.

Testing a C Program and Setting the Grade Depending on Number of Correct Output Lines

C & Bash

A collection of notes, recommendations, tips, tricks, and modifications. For example, we describe how to strip comments from java or assembly language comments.

Testing a C-Sharp «Hello World» program

C#, Bash

This is just a rough tutorial assuming that you already know how to setup a VPL module.

  • Уроки Информатики
  • Учителям
  • Учителям информатики

Moodle. Системы тестирования программ обучающихся

Существенную помощь в организации самостоятельной работы в рамках обучения программированию может оказать использование специальных программных средств, позволяющих в автоматическом режиме проверять корректность разработанной программы. Подобный функционал возможно реализовать на одной из следующих площадках или с использование свободного программного обеспечения:

  • Соревнования Уральского федерального университета
  • Технокубок от компании mail.ru
  • Красноярская школа программиста
  • Соревнования по программированию 2.0 (Codeforces)
  • Contester 2.4
  • Яндекс Контест
  • Dudge
  • PCMS2
  • DOMjudge
  • Система Московского центра непрерывного математического образования

Данные системы является самодостаточными и разворачивается на сервере или с ними можно работать зарегистрировавшись в системе. Работа с системой как со стороны администратора, так и со стороны пользователей, в роли которых выступают обучающиеся и преподаватели, осуществляется через веб-интерфейсы. Такая технология обеспечивает дополнительные возможности в организации обучения. Обучаемый может работать с системой из любой точки мира, в которой обеспечен доступ к сети Интернет, и в то же время все действия обучаемого фиксируются на сервере и доступны для преподавателя.

Однако для данных систем есть несколько ограничений и проблем в использовании:

  • Дополнительная регистрация
  • Отслеживание выполнения
  • Оценивание
  • Сервер недоступен или медленно проверяет из-за большого количества участников

Среди множества дополнений moodle есть два модуля, схожих по функционалу, а в некоторых моментах и превосходящие указанные выше системы. Первый является полноценным этапом курса с возможностью тонкой настройки и проверки и называется «Virtual Programming lab for Moodle» (сокращенно VPL). Второй является тестовым заданием и может быть включен в состав тестов и называется CodeRunner. Данные дополнения moodle позволяют использовать функционал вышеописанных систем без связанных с ними проблем.

В первую очередь данные дополнения ориентированы на изучение программирования, на работу с классом и использования как автоматически создаваемых, так и настраиваемых вариантов задач, в отличие от тестирующих систем предназначенных прежде всего для проведения олимпиадных соревнований по информатике.

Virtual Programming lab for Moodle

 Virtual Programming Lab — это модуль учебного курса moodle, который позволяет создавать и проверять задания на программирование и имеет следующие характерные особенности:

  • Редактирование исходного кода программы в браузере с подсветкой кода;
  • Запуск интерактивных программ в браузере;
  • Тестирование готовых программ;
  • Позволяет искать сходство между файлами учащихся;
  • Позволяет установить ограничения редактирования, и избежать вставки внешнего текста.

Данный модуль используется для тестирования программ среднего уровня, а также при обучении работы с черепашкой Python.

Метод проверки правильности представленной программы в системе достаточно простой. Создается система тестов, каждый из которых содержит входные данные и выходные данные, которые должны быть выданы правильно работающей программой. Обучаемый через веб-интерфейс пишет текст программы. Программа компилируется на сервере и запускается на выполнение с входными данными, представленными в каждом из тестов. Выходные данные сравниваются с эталоном с помощью специальной подпрограммы, называемой чекером. В системе реализованы компиляторы для подавляющего большинства популярных в настоящее время языков программирования — Ada, Bash script, C, C++, Fortran, Java, Pascal, Prolog, SQL, Scheme, Python и т. д.

vpl moodle

Есть возможность установки ограничений на время исполнения и используемую память. Есть возможность создания заданий с несколькими вариантами, а также настройки позволяющие открывать или скрывать от учеников входные и выходные данные тестовых заданий на валидацию программы учащегося с эталонной. Проверка работоспособности программы учащегося возможна в браузере. Это достаточно компактная IDE работающая на любом компьютере с выходом в интернет.

vpl moodle

Пример из практики

Условие Задачи 1

В файле files.csv записаны сведения о файлах. Всего в списке 280 записей, каждая из которых содержит

  • имя файла; 
  • размер файла в Кбайтах; 
  • тип файла (аудио, видео, изображение, презентация, текстовый, электронная таблица);
  • дату создания файла;
  • дату последнего изменения файла;
  • и уровень доступа. 

Все элементы в каждой строке разделены запятыми.

Напишите программу, которая читает данные из файла в массив структур (записей) и выводит на экран

а) количество файлов каждого типа;

б) список 10 самых больших файлов, отсортированный по именам файлов (для каждого вывести имя файла и размер);

в) список презентаций ограниченного доступа, которые изменялись в 2012 году; список нужно отсортировать в алфавитном порядке по именам файлов;

г) список видео размером больше 100 Мбайт, созданных во второй половине 2011 года; список нужно отсортировать по убыванию размеров файлов.

Файл files прикреплен к заданию, но учащийся его не видит. 

Проверка производится с помощью специальной программы:

import os
from subprocess import Popen, PIPE

checkGrade = 0
answerData = {}
answer = {"а:":"20 23 83 31 94 29", 
"б:":"addition.avi 872791 earthquake.avi 394928 flesh.avi 657246 garden.avi 585151 head.avi 687945 kitten.avi 877704 quartz.avi 439667 rhythm.avi 314300 route.avi 338731 stem.avi 865410",
"в:":"eyes.ppt fall.ppt good-bye.ppt month.ppt rod.ppt tray.ppt",
"г:":"kitten.avi route.avi rhythm.avi face.avi"
}


def comment(s):
    #s=s.decode('utf-8')
    '''formats strings to create VPL comments'''
    if len(s.split("n"))>2:
        for d in s.split("n"):
            print('Comment :=>> ' + str(d))
    else:
        print('Comment :=>> ' + str(s))

def grade(num):
    '''formats a number to create a VPL grade'''
    print('Grade :=>> ' + str(num))


with Popen('python3 main.py', shell=True, stdout=PIPE,stderr=PIPE) as proc:
    res=proc.communicate()
    if proc.returncode:
        comment(res[1])
    else:
        for d in res[0].decode('utf-8').strip().split("n"):
            listD = d.split()
            ans = " ".join(listD[1:])
            key = listD[0]
            answerData[key] = ans
        for key in answerData:
            if key in answer:
                if answer[key].replace(' ','') == answerData[key].strip().replace(' ',''):
                    checkGrade += 1
                    print('Comment :=>> ' + 'Выполнено задание '+key)
        
moodle_max_grade = float(os.environ["VPL_GRADEMAX"])
check = int(checkGrade/4*100)
print('Comment :=>> ' + "Вы выполнили задание на " + str(check)+ "%")
check = moodle_max_grade*(check/100)
grade(check)

Которая так же не видна учащимся.

Условие Задачи 2.

В одной фирме решили организовать локальную сеть, но инженер Вася не ходил на лекции по основам организации сети и забыли купить маршрутизатор. Однако его дедушка, знающий военный инженер связист, рассказал ему что 30 лет назад они соединяли все компьютеры в одну сеть используя один кабель. Такая топология сети называлась «Шина». Вася решил организовать сеть по топологии Шина, а для этого ему нужно проложить как можно меньше кабеля, чтобы уложиться в бюджет и организовать сеть без маршрутизатора. Помогите Васе рассчитать минимальную длину кабеля, которую нужно заказать в магазине.

Проверка производится на основе стандартных средств модуля по параметрам заданным в специальном файле:

ase=#1
grade reduction=100%
input=3 3
1 2 1
2 3 2
3 1 3
output=3
....
Case=#4
grade reduction=100%
input=8 8
1 2 1
2 4 3
4 3 7
3 6 9
5 6 6
6 7 4
7 8 2
8 1 1
output=24

Есть небольшая возможность указывать учащимся варианты, но она достаточно простая и требует дополнительно описывать программу теста. Вариант теста храниться в глобальной переменной VPL_VARIATION0

CodeRunner

CodeRunner — это бесплатный модуль с открытым исходным кодом для Moodle, который может запускать программный код на разных языках программирования, представленный учащимися в качестве ответа. Он предназначен главным образом для использования в курсах компьютерного программирования, хотя он может использоваться для оценки любого вопроса, ответ на который является текстом. Обычно используется в адаптивном режиме тестов Moodle; учащиеся пишут свой код  на каждый вопрос по программированию и сразу же получают результаты тестирования кода. Затем они могут исправить свой код и отправить повторно, как правило, с небольшим штрафом в 10% и есть возможность установки этого значения.

coderunner moodle

Тестовые задания помеченные светло-зеленым цветом не видны учащемуся.

В настоящее время поддерживает Python2, Python3, C, C++, Java, PHP, JavaScript (NodeJS), Octave и Matlab. Архитектура позволяет добавлять и другие языки программирования, например Pascal.

Данная система уже используется во множестве зарубежных учебных учреждениях, а также в школе 179 г. Москвы и Инженерный лицей НГТУ в г. Санкт Петербург.

Тонкая настройка вопроса позволяет запретить использовать некоторые встроенные функции языка программирования или проверять только определенные функции или процедуры написанные учащимся.

coderunner moodle

Важной особенностью модуля CodeRunner является возможность встраивать его в тестовое задание как один из вопросов теста, что значительно повышает возможности формирования алгоритмического мышления учащихся.

Тип вопросов CodeRunner поддерживает возможность генерации мультивариантных вопросы для каждого учащегося путем использования механизмов шаблона Twig.

Пример из практики

Условие Задачи 1.

Условие задачи задано шаблоном Twig:

На вход программы поступает неизвестное количество целых чисел, ввод заканчивается нулём. Требуется написать программу, которая подсчитает кол-во чисел оканчивающихся на {{ dN }}

Параметры Twig:

{
{% set index = random(2) %}
    "text":  "{{ ["двухзначных","трехзначных","четырехзначных"][index] }}",
    "uravnen": "{{ ["9<n<100","99<n<1000","999<n<10000"][index] }}",
    "nRange1": "{{ ["1","50","800"][index] }}",
    "nRange2": "{{ ["200","300","3000"][index] }}",
    "dN": "{{ 3 + random(6) }}"
}

Программа проверки решения:

import subprocess
import random
import json

random.seed()

student_ans = """{{ STUDENT_ANSWER | e('py') }}"""
test_program = """{{ QUESTION.answer | e('py') }}"""


def someStreamCreatingProcess(stream1, stream2):
    for i in range(200):
        x = str(random.randint({{ nRange1 }}, {{ nRange2 }}))+"n"
        stream1.write(bytes(x, encoding='utf-8'))
        stream2.write(bytes(x, encoding='utf-8'))
    stream1.write(bytes("0n", encoding='utf-8'))
    stream2.write(bytes("0n", encoding='utf-8'))
    stream1.close()
    stream2.close()


with open('student.py', 'w') as fout:
    fout.write(student_ans)
with open('test.py', 'w') as fout:
    fout.write(test_program)


subpr1 = subprocess.Popen(["python3", "student.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subpr2 = subprocess.Popen(["python3", "test.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
someStreamCreatingProcess(stream1=subpr1.stdin, stream2=subpr2.stdin)
chek = subpr1.wait()
err = subpr1.stderr.read()
out1 = subpr1.stdout.read()
out2 = subpr2.stdout.read()
if err:
    mark = 0
    result = {'got': str(err.strip().decode()), 'fraction': mark}
else:
    if out1 == out2:
        mark = 1
        great = "Супер! У тебя все получилось"
        result = {'got': great, 'fraction': mark}
    else:
        mark = 0
        result = {'got': str(out1.strip().decode()), 'expected': str(out2.strip().decode()), 'fraction': mark}

print(json.dumps(result))

Эталонная программа:

n = int(input())
g = 0
while n != 0:
    if {{ uravnen }} and n%10 == {{ dN }}:
        g = g+1
    n = int(input())
print(g)

Условие Задачи 2.

Известно что список a содержит только целочисленные элементы, количество этих элементов неизвестно. Необходимо написать программу, которая в заданном списке найдет максимальный по значению элемент.

Программа проверки решения:

# -*- coding: utf-8 -*-
__saved_input__ = input
def input(prompt=''):
    s = __saved_input__(prompt)
    print(s)
    return s


import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
__student_answer__ = """{{ STUDENT_ANSWER | e('py') }}"""


if "max(" not in __student_answer__.replace(' ', ''):
    pass
else:
    print("Запрещено использовать функцию max")
    sys.exit(0)
    
SEPARATOR = "#<ab@17943918#@>#"

{% for TEST in TESTCASES %}
{{ TEST.extra }}
{{ TEST.testcode }}
{{ STUDENT_ANSWER }}
{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}

В данном случае проверка производится путем запуска программы учащегося на нескольких тестовых значениях. Результат программы учащегося сравнивается с эталонным:

Вишенка на торте для инженерных классов. Arduino и CodeRunner.

Возможности Moodle и модуля CodeRunner позволяют также внедрить мини курс по изучению микроконтроллеров на базе платформы Arduino.

Тонкая настройка вопроса позволила описать стандартные функции и операторы Arduino IDE и импортировать их перед запуском программы учащегося. Сопоставление производится путем простого алгоритма, в котором сравниваются данные полученные на эталонном алгоритме и алгоритме учащегося.

arduino moodle

В данном примере в вопрос встроена виртуальная плата Arduino с сайта Tincercad, на которой можно испытать свой код даже без наличия реальной платы на руках.

Ответ учащийся заносит в поле ответа, проверка так же автоматическая, как и в случае с задачами на программирование.

Полная документация на английском языке для описанных выше модулей находится тут  Coderunner и тут VPL

Все статьи раздела

  • Коменты VK
  • Анонимные коменты, G+ или Facebook
  • Forums
  • Documentation
  • Downloads
  • Demo
  • Tracker
  • Development
  • Translation
  • Search



  • Search

  • Moodle Sites

    Moodle.com

    Learn about Moodle’s products, like Moodle LMS or Moodle Worplace, or find a Moodle Certified Service Provider.


    MoodleNet

    Our social network to share and curate open educational resources.


    Moodle Academy

    Courses and programs to develop your skills as a Moodle educator, administrator, designer or developer.

Maintained by Juan Carlos Rodríguez-del-Pino

VPL is an activity module to manage programming assignments

Latest release: 7 months

2024 sites

2k downloads

138 fans

Current versions available: 4

  • Description
  • Versions
  • Stats
  • Translations

VPL Logo

Virtual Programming Lab for Moodle

VPL- Virtual Programming Lab is a activity module that manage programming assignments and whose salient features are:

  • Enable to edit the programs source code in the browser
  • Students can run interactively programs in the browser
  • You can run tests to review the programs.
  • Allows searching for similarity between files.
  • Allows setting editing restrictions and avoiding external text pasting.

Sets

Useful links

Screenshots

Contributors

Please login to view contributors details and/or to contact them

Awards

This article introduces the reader to the Moodle plugins, CodeRunner and Virtual Programming Lab (VPL).

A learning management system is a tool used to create and manage educational and training programs. Moodle is a very popular learning management system; in fact, it is so popular that people may not even know of an alternative to it, off hand. Moodle is free and open source software licensed under the GNU General Purpose License. It has been developed using PHP and it can be used to create additional study material for academic subjects as well as to enable blended learning. The term ‘subject’ might be a bit misleading. In many parts of the world, like in Europe or the USA, the term used to refer to the same unit of study is ‘course’, which, in the Indian context means a collection of subjects. For example, in our country, a degree course in physics might have a subject called astrophysics.

Blended learning is an educational strategy in which traditional classroom methods are combined with online digital media to make the learning process more effective. An example of blended learning is a flipped classroom where the instructional materials are provided outside the classroom as online resources and discussions, while traditional homework is done inside the classroom. The arrival of Moodle has made the creation of course material that follows the blended learning model very easy.

In this article, we will focus on a lesser-known feature of Moodle called plugins. Since there are a large number of plugins available for use with Moodle, let’s discuss just two that are extremely useful to academicians who work as programming language instructors. These are CodeRunner and Virtual Programming Lab (VPL). Both allow the instructor to evaluate programming assignments very easily. CodeRunner is relatively simple and is available as a question type. VPL is a more complicated plugin, which offers features like interactive program editing, reviewing, plagiarism checking, etc.

Figure 1: CodeRunner plugin installation
Figure 2: CodeRunner question types

Installing Moodle

The first step is to have a Web server solution stack package installed in your system. We are using XAMPP in our systems, so let us look at how it can be used to configure and run Moodle—but remember that you can use any other Web server of your choice to get the same effects. XAMPP is free and open source software consisting of the Apache HTTP server, MariaDB database, and interpreters for PHP and Perl. The installation of XAMPP is straightforward and after completing it, execute the command sudo /opt/lampp/lampp start on a terminal to start the XAMPP server. Now open a Web browser and type http://localhost on the address bar to check if XAMPP is working properly. If the XAMPP page loads correctly, proceed with the installation of Moodle. You can download the installation file from the official website of Moodle at https://download.moodle.org/. The latest version of Moodle 3.5 in different compression and archiving file formats is available for download at this location.

After downloading the installation file called moodle-3.5.tgz, extract and copy it into the directory /opt/lampp/htdocs with admin privileges. Next, create a database for Moodle in phpMyAdmin, which is available with XAMPP. Open a Web browser and type http://localhost/phpmyadmin on the address bar to access phpMyAdmin. On the browser, click the option New to create a new database. Select the option Create database and name it ‘moodle’. Using a Web browser, go to http://localhost/moodle. Open the Moodle configuration pages. While going through the Moodle installation process, name the database moodle—the name of the database we have created in phpMyAdmin. Setting MariaDB as the default database is beneficial if you are using XAMPP.

During the installation, you will be asked to provide certain paths and other options, yet on the whole, you will be able to complete the installation without much difficulty —just make sure that you have admin privileges. Following these steps will only enable you to install Moodle in your local system. To make your Moodle installation available publicly, you need to purchase a domain name and server space from a Web hosting company and configure the cPanel — a Web-based hosting control panel offered by many hosting providers to website owners, allowing them to manage their websites from a Web based interface. You can then upload and extract the Moodle folder in the cPanel to make it available publicly.

The other option is to obtain just a domain name and configure Moodle in Google or Amazon cloud services and link that server’s IP address to your own domain name. Before discussing CodeRunner and Virtual Programming Lab (VPL), let’s create a course in Moodle. Courses are the spaces that allow Moodle users to create and provide learning materials to their students. Moodle directly provides options to create new courses and the operation is simple. In this article, we have created just a single course called Programming to make our discussion easy to follow.

It is not possible to include a large number of images in a single article so we have prepared a separate document titled Configuration.pdf which is available for download at opensourceforu.com/article_source_code/July18moodle.zip. The document consists of a detailed set of screenshots involving the configuration of Moodle as well as the configuration and use of the two plugins, CodeRunner and VPL. Please download and go through this document if you get confused with any of the steps involved in the configuration of Moodle, CodeRunner or VPL.

Figure 3: CodeRunner environment for program execution
Figure 4: Automatic evaluation by CodeRunner

Installing CodeRunner

Now it is time to install the first plugin called CodeRunner, which is going to help programming language instructors a lot. Unlike other normal plugins in Moodle, CodeRunner and VPL involve a two-step installation process. First, we have to install the actual plugin and then install sandbox servers to run programs to be tested by CodeRunner and VPL. Sandbox servers are needed to prevent system crashes when students experiment with code, either due to the unintentional use of bad code or malicious code. Either way, it is not at all safe to allow third party programs to be executed by your own local compiler. Sandbox servers allow the third party programs to use only a restricted set of resources of the host machine and thus protect the system from any harm.

Moodle allows the course managers to set questions, the answers for which can be one among several question types. Some of the more commonly used question types of Moodle include multiple choices, short answers, numerical, descriptions, essays, matching, etc. CodeRunner offers question types that allow programming course content managers to set programming questions in which the student’s answer is code in some programming language. This code can then be automatically graded by running and testing it against test cases provided by the course manager. CodeRunner can be used to conduct programming tests in languages like C, C++, Java, Python, JavaScript, PHP, MATLAB, etc. To install the CodeRunner plugin, you have to log in to your Moodle server as the administrator. The plugin can be installed directly from the Moodle plugins directory. To do this, select the menu item Dashboard>Site administration>Plugins>Install plugins. We have installed the plugin CodeRunner from a zip file provided by the Moodle plugins directory. Figure 1 shows the CodeRunner plugin installation.

Figure 5: Adding a VPL activity

Setting up a sandbox server for CodeRunner

The sandbox server for CodeRunner is called Jobe server. There are two options available while deploying the Jobe server or any other sandbox server. You can use the address of the default Jobe server provided online or you can set up your own Jobe server on your local system. In this article, we have used the default Jobe server available online at jobe2.cosc.canterbury.ac.nz provided by the University of Canterbury, New Zealand to test CodeRunner programs, and installed a local sandbox server to test VPL so that the reader will be able to use sandbox servers online as well as locally. There is another reason why we do this. If you install more than one sandbox server in your local system, there will be a conflict because both the servers will use the same port address. Then you will have to manually change the port address for one of the servers. The advantage of using an online sandbox server is its ease of deployment whereas the disadvantage is that it is slow. If a large number of users take the test at the same time, the online sandbox server might deny service.

So, what we suggest is, experiment with both CodeRunner and VPL sandbox servers online, fix the plugin you like and set up the sandbox server of your choice locally so that faster execution is possible when a large number of students are taking the test. You can provide the address of the online Jobe server by taking the CodeRunner settings. The document Configure.pdf provides screenshots showing how to use the Jobe server installed in the local system as well as an online Jobe server.

Using CodeRunner

There are two different aspects to using plugins like CodeRunner. A programming language trainer will use CodeRunner to set an online programming test, whereas a student enrolled in that course will appear for this test to evaluate his or her level of knowledge. So, the two aspects of CodeRunner are setting up the test and taking the test.

We have already created a course titled Programming in Moodle. You should log in as an admin user, course designer or teacher, depending on the privileges provided by the admin user to create a CodeRunner test in Moodle. Here, in this example, we are logging in as the admin user to simplify things. The course called Programming will have a topic called Topic1, by default. Now, you need to create a quiz on Topic1 and add questions to it.

The questions can be first added to a question bank and then to the quiz. In our case, the name of the quiz is C to which we are adding a question type of CodeRunner. The question type option of CodeRunner allows a user to set the programming language in which the student is supposed to write the answer program. For this example, we have used c_function as the CodeRunner question type and thereby forced the student to write the answer as a C function. The other possible choices for CodeRunner question types include c_program, cpp_ function, cpp_program, java_ class, java_method, java_program, php, python2, python3, etc. Figure 2 shows the drop-down menu showing the question types of CodeRunner.

After setting this up, you need to provide details like the question name, question text, etc, so that the students get a clear idea regarding the answer they have to provide. Our question for this example is very simple — write a C programming language function to find the square of a number entered through the keyboard. The next task is to provide test cases for automatic evaluation of the program provided by a student. For example, if the input is -11, the answer should be 121 and if the input is 5, the answer should be 25. It is better to give a large number of test cases to make sure that the program provided by the student is in fact correct. You should provide test cases involving corner cases to achieve this.

Now, you need to fix details regarding the grading and feedback for the test. Options like deferred feedback, adaptive mode, etc, can be used to modify the behaviour of the test. In our example, we have created only one question in the quiz called C to make things simpler, but remember there are no restrictions regarding the number of questions in a quiz. Now that we have created a test, student or guest users can attend this test depending on the privileges given to them. A user with proper authorisation can log in and attend this test. Figure 3 shows the environment provided by CodeRunner to write and execute answer programs. You will observe that some of the test cases are provided as examples to show the expected output.

Once the student users are fine with the program, they can test it with CodeRunner. There are options provided by CodeRunner to reduce the grade for a question with each unsuccessful attempt. Figure 4 shows the output obtained after automatic evaluation of the program with test cases by CodeRunner. From the figure, it is clear that we have provided four test cases and the program has passed all four of those test cases. This is how CodeRunner can be used to set up automated programming tests. Remember, this article only provides a light introduction to CodeRunner, but for more details and advanced features, you can refer to the Moodle plugins directory.

Figue 6: VPL environment for program execution

Installing Virtual Programming Lab (VPL)

Now that we are familiar with the use of CodeRunner, it is time to introduce Virtual Programming Lab (VPL), which is much more powerful than CodeRunner. However, if both plugins can evaluate programming assignments by running the code provided by a student, what is the benefit of the additional features provided by VPL? Let us go through two academic scenarios to understand the need for the stronger features provided by VPL.

First, let us consider a student enrolled in an online course covering a new programming language, say, Rust. He has probably paid a fee and is willing to spend a lot of time to learn a new programming language. Usually, such online courses have programming assignments to test the knowledge level of the student. The student can write a program and test it to understand whether he has learned that topic or not. But is he going to copy the answer from some other source, say, the Internet? Most probably not. His aim is to learn a new programming language and plagiarising the program will not help him in any manner. In this scenario, the features of CodeRunner are sufficient and VPL might be overkill.

Now consider the second scenario in which you have to conduct an online exam, the marks for which will be considered for the final grade of a student. The academic community strongly disapproves of the practice of plagiarism but, in this scenario, some students might be tempted to get solutions online. In this case, the plugin should have additional features to check whether students have copied their programs from some other source. In this case, CodeRunner is not the best solution whereas VPL provides an option to check for plagiarism. VPL offers many such features that we should discuss. VPL is an activity module that can be used to create and conduct programming assignments in online programming courses.

As mentioned earlier, the installation of VPL is a two-step process. First, we have to install the plugin and then a sandbox server. The execution server that provides a sandbox for VPL is called a jail server, which is installed in your local machine. First log in to your Moodle server as the administrator, and you can install the plugin directly from the Moodle plugins directory. To do this, select the menu item Dashboard>Site administration>Plugins>Install plugins. The VPL plugin is also installed from a zip file provided by the Moodle plugins directory. The installation file for the jail server can be downloaded from http://vpl.dis.ulpgc.es/index.php/home/download. The latest version available for download is VPL Jail Execution System 2.2.2 and the name of this installation file is vpl-jail-system-2.2.2.tar.gz. Extract this file in your system and open a terminal inside the directory vpl-jail-system-2.2.2. In this directory, there is an installation shell script named install-vpl-sh. The installation can be completed by running this shell script, by executing the command ./install-vpl-sh on the terminal.

The detailed installation screenshots are given in the document Configure.pdf. If jail server is operating properly, it must respond with a page showing the text OK, if the URL http://server_name[:port ]/OK is typed in the address bar of a Web browser.

Using Virtual Programming Lab

Let’s use VPL to set up an online programming test. Here again, we have to see how a teacher can set up a test using VPL and how a student can attend that test. To set up a test, you should log in as either an admin user, course designer or teacher, depending on the privileges provided by the admin user. In this example, we are again logging in as the admin user to simplify things. The course Programming created in Moodle has a topic called Topic1. The option Add an activity or resource allows us to add new VPL activity to Topic1. Figure 5 shows how VPL can be added as an activity.

Now, details regarding the program to be answered have to be provided — the program’s name, its description, etc. Just like for CodeRunner, for VPL too, we need to set up a test with a single question, which in this case is,“Find the square of a number entered through the keyboard.”

The other advantage of VPL over CodeRunner is that in the case of the latter, the solution program should be written in a specific programming language preset by the teacher. VPL does not have this restriction. Depending on the extension of the program, the required compiler will be selected by the jail server to do the compilation. For example, a file with an extension .py will be treated as a Python program and another file with an extension .c will be treated as a C program automatically by the jail server. The programming languages supported by VPL include Ada, C, C++, Fortran, Java, Pascal, Prolog, SQL, Scheme, etc.

After this, test cases should be provided to conduct automatic code evaluation. The more the test cases, the better, because you will be able to make the evaluation more rigorous. You also need to provide submission and grading related parameters for the test, like how many submissions are allowed, the deadline for submissions, etc. Now the test is ready; so let us attend it. Also remember that just like CodeRunner, any number of questions can be added in a VPL activity. Participants can log in as students or guest users to attempt this, depending on the privileges given to them. After logging in, the participants can either upload their program or use the editor, like in CodeRunner. Figure 6 shows the program execution environment of VPL.

For this article, we have used a Python script called a.py, which finds the square of a given number. This program can be executed directly from the VPL environment. The jail server automatically detects a.py as a Python script by the extension py. On execution, the jail server will automatically check the script and give the result shown in Figure 7. From the figure, it is clear that there was only a single test case provided for evaluating the script and it has passed that test. So, in this manner, VPL can be used to create and conduct online programming tests. Only the bare minimum features of VPL are discussed here; for a more detailed discussion, please refer to the Moodle plugins directory.

Figure 7: Automatic evaluation by VPL

Additional features of VPL

Earlier we have seen how VPL allows us to check for plagiarism. We also saw how the jail server will automatically assign compilers to test programs written in different languages. But plagiarism checking and automatic compiler selection are not the only attractive features provided by VPL. Just like in CodeRunner, VPL also allows users to edit the program source code in the browser. Another feature that is available with both CodeRunner and VPL is the ability to run programs interactively in the browser. One major difference between CodeRunner and VPL is that VPL allows you to upload program files written offline for verification. This is a very useful feature when the assignment involves large programs that might take a lot of time to complete. Another advantage of VPL is that it allows you to run tests to review the programs rather than the final submission for grading. In CodeRunner, incorrect submissions may lead to a reduction in the score for that program. VPL also allows users to set editing restrictions on the programming environment like disabling external text pasting. These features and the plagiarism-checking capability of VPL make it a powerful tool in the hands of online technology content providers.

We hope that the article will create a general awareness regarding Moodle plugins and motivate a lot of people to explore the hundreds of Moodle plugins available online. Exploring and adopting Moodle and its plugins will lead to a better teaching-learning process, and education will then become edutainment.

If you teach computer science and use Moodle as your LMS, good news: you can now have student submit snippets of code easily using the new Virtual Programming Lab created by ULPGC (University of Las Palmas de Gran Canaria, Spain).

How to assess computer programming skills in Moodle

According to creator Juan Carlos Rodríguez-del-Pino,

VPL is a activity module that manage programming assignments and whose salient features are:

  • Enable to edit the programs source code in the browser
  • Students can run interactively programs in the browser
  • You can run tests to review the programs
  • Allows searching for similarity between files
  • Allows setting editing restrictions and avoiding external text pasting

The module allows code editing, running tests and more, all within Moodle. It appears that the main thrust of the module is also increasing the opportunities for learning within the Moodle classroom, as it pertains to code and software development.

As of writing, VPL supports nearly 20 programming languages, from Java and Python down to Haskell and Prolog. The environment will let you run complete programs, its performance depending on the server resources available. It is able to provide basic automated checks to ensure code submitted by students runs smoothly.

8 Things Every Educator Should Know About Python

Real reasons for virtual environments

Rodríguez-del-Pino expands:

The programming assignments of the early courses can present particular difficulties for the student and require frequent monitoring by the teacher. Often, until the work is assessed, students don’t know if it is correct or not. This mode of operation meets the evaluative aspect, but does not provide the student to learn from their mistakes, which lost a significant part of the learning potential associated with the making of an assignment. More over, the evaluation may require considerable time and effort by the teacher due to the number of students, the number of submits required and their complexity.

The availability of a teaching tool to facilitate monitoring and personalized guidance in a continuous learning process allows to reduce the initial difficulties faced by the student. For teachers, the possibility of automating much of the assessment allows them to perform other productive tasks.”

The main website has information in both Spanish and English and is a great resource for seeing what the module can do.  Demo the module, or check out these screenshots:

Installing VPL on Moodle LMS

To set up VPL on your Moodle site, you need to install the VPL plugin, which you can do in one click from the Moodle Plugin Directory.

Then you will also need a “VPL-Jail-System,” a special application with full server functionality, but outside of the production server scope. This will prevent any “accidental” misconfiguration of the real server from the VPL.

Resources & References

VPL is compatible with Moodle 2.7 to 3.9

  • VPL — Main page at the Universidad de Las Palmas de Gran Canaria, Spain website
  • VPL General documentation
  • Download the VPL plugin at moodle.org/plugins/mod_vpl and the VPL-Jail-System here
  • In addition, the VPL Question plugin lets you embed the environment in the Moodle Quiz activity
  • Find installation instructions here
  • Try out a demo here
  • Submit questions and issues to Rodríguez-del-Pino directly in the Moodle Forum

What Is A Virtual Moodle Development Environment?

VPL plugin is used so that student can make and compile program online.

VPL stands for Virtual programming language. Generally, it is an activity module for Moodle that manage programming assignments.

Steps to install VPL Plugin

  • Download the plugin from here.
  • Extract the plugin in moodle/mod directory
  • Change the permission. by using$chmod -R 755 vpl or
    $chmod -R 777 vpl
  • Then open localhost/moodle in browser.
  • and go to dashbord>check for plugin dashboard.

That’s it your plugin is integrated with moodle.

This will give the output. But it is for a couple of days. We have to install Jail server which I will discuss in my next post.

Stay Awsome.

Any queries comment below. 🙂

Published
May 29, 2016May 29, 2016

Понравилась статья? Поделить с друзьями:
  • Руководство чтением основные задачи руководства чтением
  • Румалайя гель инструкция по применению цена отзывы
  • Камаз руководство по ремонту pdf
  • Студенту медицинского вуза руководство
  • Мануал по ремонту двигателя камаз 740