Commit de342676 by David Ormsbee

Merge branch 'master' into feature/victor/actual-askbot-removal

Conflicts:
	lms/envs/aws.py
parents 37afae92 26890b1f
......@@ -26,3 +26,4 @@ cms/static/sass/*.css
lms/lib/comment_client/python
nosetests.xml
cover_html/
.idea/
......@@ -7,3 +7,4 @@ python
yuicompressor
node
graphviz
mysql
# .coveragerc for cms
[run]
data_file = reports/cms/.coverage
source = cms
[report]
ignore_errors = True
[html]
directory = reports/cms/cover
[xml]
output = reports/cms/coverage.xml
......@@ -14,9 +14,7 @@ from path import path
# Nose Test Runner
INSTALLED_APPS += ('django_nose',)
NOSE_ARGS = ['--cover-erase', '--with-xunit', '--with-xcoverage', '--cover-html', '--cover-inclusive']
for app in os.listdir(PROJECT_ROOT / 'djangoapps'):
NOSE_ARGS += ['--cover-package', app]
NOSE_ARGS = ['--with-xunit']
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
TEST_ROOT = path('test_root')
......
......@@ -3,8 +3,7 @@ from staticfiles.storage import staticfiles_storage
from pipeline_mako import compressed_css, compressed_js
%>
<%def name='url(file)'>
<%
<%def name='url(file)'><%
try:
url = staticfiles_storage.url(file)
except:
......
import csv
import uuid
from collections import defaultdict, OrderedDict
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from student.models import TestCenterUser
class Command(BaseCommand):
CSV_TO_MODEL_FIELDS = OrderedDict([
("ClientCandidateID", "client_candidate_id"),
("FirstName", "first_name"),
("LastName", "last_name"),
("MiddleName", "middle_name"),
("Suffix", "suffix"),
("Salutation", "salutation"),
("Email", "email"),
# Skipping optional fields Username and Password
("Address1", "address_1"),
("Address2", "address_2"),
("Address3", "address_3"),
("City", "city"),
("State", "state"),
("PostalCode", "postal_code"),
("Country", "country"),
("Phone", "phone"),
("Extension", "extension"),
("PhoneCountryCode", "phone_country_code"),
("FAX", "fax"),
("FAXCountryCode", "fax_country_code"),
("CompanyName", "company_name"),
# Skipping optional field CustomQuestion
("LastUpdate", "user_updated_at"), # in UTC, so same as what we store
])
args = '<output_file>'
help = """
Export user information from TestCenterUser model into a tab delimited
text file with a format that Pearson expects.
"""
def handle(self, *args, **kwargs):
if len(args) < 1:
print Command.help
return
self.reset_sample_data()
with open(args[0], "wb") as outfile:
writer = csv.DictWriter(outfile,
Command.CSV_TO_MODEL_FIELDS,
delimiter="\t",
quoting=csv.QUOTE_MINIMAL,
extrasaction='ignore')
writer.writeheader()
for tcu in TestCenterUser.objects.order_by('id'):
record = dict((csv_field, getattr(tcu, model_field))
for csv_field, model_field
in Command.CSV_TO_MODEL_FIELDS.items())
record["LastUpdate"] = record["LastUpdate"].strftime("%Y/%m/%d %H:%M:%S")
writer.writerow(record)
def reset_sample_data(self):
def make_sample(**kwargs):
data = dict((model_field, kwargs.get(model_field, ""))
for model_field in Command.CSV_TO_MODEL_FIELDS.values())
return TestCenterUser(**data)
def generate_id():
return "edX{:012}".format(uuid.uuid4().int % (10**12))
# TestCenterUser.objects.all().delete()
samples = [
make_sample(
client_candidate_id=generate_id(),
first_name="Jack",
last_name="Doe",
middle_name="C",
address_1="11 Cambridge Center",
address_2="Suite 101",
city="Cambridge",
state="MA",
postal_code="02140",
country="USA",
phone="(617)555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Clyde",
last_name="Smith",
middle_name="J",
suffix="Jr.",
salutation="Mr.",
address_1="1 Penny Lane",
city="Honolulu",
state="HI",
postal_code="96792",
country="USA",
phone="555-555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Patty",
last_name="Lee",
salutation="Dr.",
address_1="P.O. Box 555",
city="Honolulu",
state="HI",
postal_code="96792",
country="USA",
phone="808-555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Jimmy",
last_name="James",
address_1="2020 Palmer Blvd.",
city="Springfield",
state="MA",
postal_code="96792",
country="USA",
phone="917-555-5555",
phone_country_code="1",
extension="2039",
fax="917-555-5556",
fax_country_code="1",
company_name="ACME Traps",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Yeong-Un",
last_name="Seo",
address_1="Duryu, Lotte 101",
address_2="Apt 55",
city="Daegu",
country="KOR",
phone="917-555-5555",
phone_country_code="011",
user_updated_at=datetime.utcnow()
),
]
for tcu in samples:
tcu.save()
\ No newline at end of file
import csv
import uuid
from collections import defaultdict, OrderedDict
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from student.models import TestCenterUser
def generate_id():
return "{:012}".format(uuid.uuid4().int % (10**12))
class Command(BaseCommand):
args = '<output_file>'
help = """
Export user information from TestCenterUser model into a tab delimited
text file with a format that Pearson expects.
"""
FIELDS = [
'AuthorizationTransactionType',
'AuthorizationID',
'ClientAuthorizationID',
'ClientCandidateID',
'ExamAuthorizationCount',
'ExamSeriesCode',
'EligibilityApptDateFirst',
'EligibilityApptDateLast',
'LastUpdate',
]
def handle(self, *args, **kwargs):
if len(args) < 1:
print Command.help
return
# self.reset_sample_data()
with open(args[0], "wb") as outfile:
writer = csv.DictWriter(outfile,
Command.FIELDS,
delimiter="\t",
quoting=csv.QUOTE_MINIMAL,
extrasaction='ignore')
writer.writeheader()
for tcu in TestCenterUser.objects.order_by('id')[:5]:
record = defaultdict(
lambda: "",
AuthorizationTransactionType="Add",
ClientAuthorizationID=generate_id(),
ClientCandidateID=tcu.client_candidate_id,
ExamAuthorizationCount="1",
ExamSeriesCode="6002x001",
EligibilityApptDateFirst="2012/12/15",
EligibilityApptDateLast="2012/12/30",
LastUpdate=datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S")
)
writer.writerow(record)
def reset_sample_data(self):
def make_sample(**kwargs):
data = dict((model_field, kwargs.get(model_field, ""))
for model_field in Command.CSV_TO_MODEL_FIELDS.values())
return TestCenterUser(**data)
# TestCenterUser.objects.all().delete()
samples = [
make_sample(
client_candidate_id=generate_id(),
first_name="Jack",
last_name="Doe",
middle_name="C",
address_1="11 Cambridge Center",
address_2="Suite 101",
city="Cambridge",
state="MA",
postal_code="02140",
country="USA",
phone="(617)555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Clyde",
last_name="Smith",
middle_name="J",
suffix="Jr.",
salutation="Mr.",
address_1="1 Penny Lane",
city="Honolulu",
state="HI",
postal_code="96792",
country="USA",
phone="555-555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Patty",
last_name="Lee",
salutation="Dr.",
address_1="P.O. Box 555",
city="Honolulu",
state="HI",
postal_code="96792",
country="USA",
phone="808-555-5555",
phone_country_code="1",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Jimmy",
last_name="James",
address_1="2020 Palmer Blvd.",
city="Springfield",
state="MA",
postal_code="96792",
country="USA",
phone="917-555-5555",
phone_country_code="1",
extension="2039",
fax="917-555-5556",
fax_country_code="1",
company_name="ACME Traps",
user_updated_at=datetime.utcnow()
),
make_sample(
client_candidate_id=generate_id(),
first_name="Yeong-Un",
last_name="Seo",
address_1="Duryu, Lotte 101",
address_2="Apt 55",
city="Daegu",
country="KOR",
phone="917-555-5555",
phone_country_code="011",
user_updated_at=datetime.utcnow()
),
]
for tcu in samples:
tcu.save()
\ No newline at end of file
import uuid
from datetime import datetime
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from student.models import TestCenterUser
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--client_candidate_id',
action='store',
dest='client_candidate_id',
help='ID we assign a user to identify them to Pearson'
),
make_option(
'--first_name',
action='store',
dest='first_name',
),
make_option(
'--last_name',
action='store',
dest='last_name',
),
make_option(
'--address_1',
action='store',
dest='address_1',
),
make_option(
'--city',
action='store',
dest='city',
),
make_option(
'--state',
action='store',
dest='state',
help='Two letter code (e.g. MA)'
),
make_option(
'--postal_code',
action='store',
dest='postal_code',
),
make_option(
'--country',
action='store',
dest='country',
help='Three letter country code (ISO 3166-1 alpha-3), like USA'
),
make_option(
'--phone',
action='store',
dest='phone',
help='Pretty free-form (parens, spaces, dashes), but no country code'
),
make_option(
'--phone_country_code',
action='store',
dest='phone_country_code',
help='Phone country code, just "1" for the USA'
),
)
args = "<student_username>"
help = "Create a TestCenterUser entry for a given Student"
@staticmethod
def is_valid_option(option_name):
base_options = set(option.dest for option in BaseCommand.option_list)
return option_name not in base_options
def handle(self, *args, **options):
username = args[0]
print username
our_options = dict((k, v) for k, v in options.items()
if Command.is_valid_option(k))
student = User.objects.get(username=username)
student.test_center_user = TestCenterUser(**our_options)
student.test_center_user.save()
......@@ -10,7 +10,7 @@ Portal servers that hold the canoncial user information and that user
information is replicated to slave Course server pools. Each Course has a set of
servers that serves only its content and has users that are relevant only to it.
We replicate the following tables into the Course DBs where the user is
We replicate the following tables into the Course DBs where the user is
enrolled. Only the Portal servers should ever write to these models.
* UserProfile
* CourseEnrollment
......@@ -43,33 +43,22 @@ import uuid
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django_countries import CountryField
from django.db.models.signals import post_save
from django.dispatch import receiver
from functools import partial
import comment_client as cc
from django_comment_client.models import Role, Permission
from django_comment_client.models import Role
import logging
from xmodule.modulestore.django import modulestore
#from cache_toolbox import cache_model, cache_relation
log = logging.getLogger(__name__)
class UserProfile(models.Model):
"""This is where we store all the user demographic fields. We have a
"""This is where we store all the user demographic fields. We have a
separate table for this rather than extending the built-in Django auth_user.
Notes:
* Some fields are legacy ones from the first run of 6.002, from which
* Some fields are legacy ones from the first run of 6.002, from which
we imported many users.
* Fields like name and address are intentionally open ended, to account
for international variations. An unfortunate side-effect is that we
......@@ -135,6 +124,72 @@ class UserProfile(models.Model):
def set_meta(self, js):
self.meta = json.dumps(js)
class TestCenterUser(models.Model):
"""This is our representation of the User for in-person testing, and
specifically for Pearson at this point. A few things to note:
* Pearson only supports Latin-1, so we have to make sure that the data we
capture here will work with that encoding.
* While we have a lot of this demographic data in UserProfile, it's much
more free-structured there. We'll try to pre-pop the form with data from
UserProfile, but we'll need to have a step where people who are signing
up re-enter their demographic data into the fields we specify.
* Users are only created here if they register to take an exam in person.
The field names and lengths are modeled on the conventions and constraints
of Pearson's data import system, including oddities such as suffix having
a limit of 255 while last_name only gets 50.
"""
# Our own record keeping...
user = models.ForeignKey(User, unique=True, default=None)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
# user_updated_at happens only when the user makes a change to their data,
# and is something Pearson needs to know to manage updates. Unlike
# updated_at, this will not get incremented when we do a batch data import.
user_updated_at = models.DateTimeField(db_index=True)
# Unique ID given to us for this User by the Testing Center. It's null when
# we first create the User entry, and is assigned by Pearson later.
candidate_id = models.IntegerField(null=True, db_index=True)
# Unique ID we assign our user for a the Test Center.
client_candidate_id = models.CharField(max_length=50, db_index=True)
# Name
first_name = models.CharField(max_length=30, db_index=True)
last_name = models.CharField(max_length=50, db_index=True)
middle_name = models.CharField(max_length=30, blank=True)
suffix = models.CharField(max_length=255, blank=True)
salutation = models.CharField(max_length=50, blank=True)
# Address
address_1 = models.CharField(max_length=40)
address_2 = models.CharField(max_length=40, blank=True)
address_3 = models.CharField(max_length=40, blank=True)
city = models.CharField(max_length=32, db_index=True)
# state example: HI -- they have an acceptable list that we'll just plug in
# state is required if you're in the US or Canada, but otherwise not.
state = models.CharField(max_length=20, blank=True, db_index=True)
# postal_code required if you're in the US or Canada
postal_code = models.CharField(max_length=16, blank=True, db_index=True)
# country is a ISO 3166-1 alpha-3 country code (e.g. "USA", "CAN", "MNG")
country = models.CharField(max_length=3, db_index=True)
# Phone
phone = models.CharField(max_length=35)
extension = models.CharField(max_length=8, blank=True, db_index=True)
phone_country_code = models.CharField(max_length=3, db_index=True)
fax = models.CharField(max_length=35, blank=True)
# fax_country_code required *if* fax is present.
fax_country_code = models.CharField(max_length=3, blank=True)
# Company
company_name = models.CharField(max_length=50, blank=True)
@property
def email(self):
return self.user.email
## TODO: Should be renamed to generic UserGroup, and possibly
# Given an optional field for type of group
......
......@@ -19,16 +19,19 @@ from django.core.context_processors import csrf
from django.core.mail import send_mail
from django.core.validators import validate_email, validate_slug, ValidationError
from django.db import IntegrityError
from django.http import HttpResponse, Http404
from django.http import HttpResponse, HttpResponseForbidden, Http404
from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string
from bs4 import BeautifulSoup
from django.core.cache import cache
from django_future.csrf import ensure_csrf_cookie
from django_future.csrf import ensure_csrf_cookie, csrf_exempt
from student.models import (Registration, UserProfile,
PendingNameChange, PendingEmailChange,
CourseEnrollment)
from certificates.models import CertificateStatuses, certificate_status_for_student
from xmodule.course_module import CourseDescriptor
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.modulestore.django import modulestore
......@@ -95,6 +98,19 @@ def course_from_id(course_id):
course_loc = CourseDescriptor.id_to_location(course_id)
return modulestore().get_instance(course_id, course_loc)
import re
day_pattern = re.compile('\s\d+,\s')
multimonth_pattern = re.compile('\s?\-\s?\S+\s')
def get_date_for_press(publish_date):
import datetime
# strip off extra months, and just use the first:
date = re.sub(multimonth_pattern, ", ", publish_date)
if re.search(day_pattern, date):
date = datetime.datetime.strptime(date, "%B %d, %Y")
else:
date = datetime.datetime.strptime(date, "%B, %Y")
return date
def press(request):
json_articles = cache.get("student_press_json_articles")
......@@ -107,6 +123,7 @@ def press(request):
json_articles = json.loads(content)
cache.set("student_press_json_articles", json_articles)
articles = [Article(**article) for article in json_articles]
articles.sort(key=lambda item: get_date_for_press(item.publish_date), reverse=True)
return render_to_response('static_templates/press.html', {'articles': articles})
......@@ -143,11 +160,20 @@ def dashboard(request):
show_courseware_links_for = frozenset(course.id for course in courses
if has_access(request.user, course, 'load'))
# TODO: workaround to not have to zip courses and certificates in the template
# since before there is a migration to certificates
if settings.MITX_FEATURES.get('CERTIFICATES_ENABLED'):
cert_statuses = { course.id: certificate_status_for_student(request.user, course.id) for course in courses}
else:
cert_statuses = {}
context = {'courses': courses,
'message': message,
'staff_access': staff_access,
'errored_courses': errored_courses,
'show_courseware_links_for' : show_courseware_links_for}
'show_courseware_links_for' : show_courseware_links_for,
'cert_statuses': cert_statuses,
}
return render_to_response('dashboard.html', context)
......@@ -206,13 +232,13 @@ def change_enrollment(request):
return {'success': False,
'error': 'enrollment in {} not allowed at this time'
.format(course.display_name)}
org, course_num, run=course_id.split("/")
org, course_num, run=course_id.split("/")
statsd.increment("common.student.enrollment",
tags=["org:{0}".format(org),
"course:{0}".format(course_num),
"run:{0}".format(run)])
enrollment, created = CourseEnrollment.objects.get_or_create(user=user, course_id=course.id)
return {'success': True}
......@@ -220,13 +246,13 @@ def change_enrollment(request):
try:
enrollment = CourseEnrollment.objects.get(user=user, course_id=course_id)
enrollment.delete()
org, course_num, run=course_id.split("/")
org, course_num, run=course_id.split("/")
statsd.increment("common.student.unenrollment",
tags=["org:{0}".format(org),
"course:{0}".format(course_num),
"run:{0}".format(run)])
return {'success': True}
except CourseEnrollment.DoesNotExist:
return {'success': False, 'error': 'You are not enrolled for this course.'}
......@@ -275,13 +301,13 @@ def login_user(request, error=""):
log.info("Login success - {0} ({1})".format(username, email))
try_change_enrollment(request)
statsd.increment("common.student.successful_login")
return HttpResponse(json.dumps({'success': True}))
log.warning("Login failed - Account not active for user {0}, resending activation".format(username))
reactivation_email_for_user(user)
not_activated_msg = "This account has not been activated. We have " + \
"sent another activation message. Please check your " + \
......@@ -483,9 +509,9 @@ def create_account(request, post_override=None):
log.debug('bypassing activation email')
login_user.is_active = True
login_user.save()
statsd.increment("common.student.account_created")
js = {'success': True}
return HttpResponse(json.dumps(js), mimetype="application/json")
......@@ -541,9 +567,9 @@ def password_reset(request):
''' Attempts to send a password reset e-mail. '''
if request.method != "POST":
raise Http404
# By default, Django doesn't allow Users with is_active = False to reset their passwords,
# but this bites people who signed up a long time ago, never activated, and forgot their
# but this bites people who signed up a long time ago, never activated, and forgot their
# password. So for their sake, we'll auto-activate a user for whome password_reset is called.
try:
user = User.objects.get(email=request.POST['email'])
......@@ -551,7 +577,7 @@ def password_reset(request):
user.save()
except:
log.exception("Tried to auto-activate user to enable password reset, but failed.")
form = PasswordResetForm(request.POST)
if form.is_valid():
form.save(use_https = request.is_secure(),
......@@ -589,7 +615,7 @@ def reactivation_email_for_user(user):
res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
return HttpResponse(json.dumps({'success': True}))
@ensure_csrf_cookie
def change_email_request(request):
......@@ -764,8 +790,8 @@ def accept_name_change_by_id(id):
@ensure_csrf_cookie
def accept_name_change(request):
''' JSON: Name change process. Course staff clicks 'accept' on a given name change
''' JSON: Name change process. Course staff clicks 'accept' on a given name change
We used this during the prototype but now we simply record name changes instead
of manually approving them. Still keeping this around in case we want to go
back to this approval method.
......@@ -774,3 +800,23 @@ def accept_name_change(request):
raise Http404
return accept_name_change_by_id(int(request.POST['id']))
# TODO: This is a giant kludge to give Pearson something to test against ASAP.
# Will need to get replaced by something that actually ties into TestCenterUser
@csrf_exempt
def test_center_login(request):
if not settings.MITX_FEATURES.get('ENABLE_PEARSON_HACK_TEST'):
raise Http404
client_candidate_id = request.POST.get("clientCandidateID")
# registration_id = request.POST.get("registrationID")
exit_url = request.POST.get("exitURL")
error_url = request.POST.get("errorURL")
if client_candidate_id == "edX003671291147":
user = authenticate(username=settings.PEARSON_TEST_USER,
password=settings.PEARSON_TEST_PASSWORD)
login(request, user)
return redirect('/courses/MITx/6.002x/2012_Fall/courseware/Final_Exam/Final_Exam_Fall_2012/')
else:
return HttpResponseForbidden()
# .coveragerc for common/lib/capa
[run]
data_file = reports/common/lib/capa/.coverage
source = common/lib/capa
[report]
ignore_errors = True
[html]
directory = reports/common/lib/capa/cover
[xml]
output = reports/common/lib/capa/coverage.xml
......@@ -38,6 +38,7 @@ import calc
from correctmap import CorrectMap
import eia
import inputtypes
import customrender
from util import contextualize_text, convert_files_to_filenames
import xqueue_interface
......@@ -47,23 +48,8 @@ import responsetypes
# dict of tagname, Response Class -- this should come from auto-registering
response_tag_dict = dict([(x.response_tag, x) for x in responsetypes.__all__])
# Different ways students can input code
entry_types = ['textline',
'schematic',
'textbox',
'imageinput',
'optioninput',
'choicegroup',
'radiogroup',
'checkboxgroup',
'filesubmission',
'javascriptinput',
'crystallography',
'chemicalequationinput',
'vsepr_input']
# extra things displayed after "show answers" is pressed
solution_types = ['solution']
solution_tags = ['solution']
# these get captured as student responses
response_properties = ["codeparam", "responseparam", "answer"]
......@@ -309,7 +295,7 @@ class LoncapaProblem(object):
answer_map.update(results)
# include solutions from <solution>...</solution> stanzas
for entry in self.tree.xpath("//" + "|//".join(solution_types)):
for entry in self.tree.xpath("//" + "|//".join(solution_tags)):
answer = etree.tostring(entry)
if answer:
answer_map[entry.get('id')] = contextualize_text(answer, self.context)
......@@ -487,7 +473,7 @@ class LoncapaProblem(object):
problemid = problemtree.get('id') # my ID
if problemtree.tag in inputtypes.registered_input_tags():
if problemtree.tag in inputtypes.registry.registered_tags():
# If this is an inputtype subtree, let it render itself.
status = "unsubmitted"
msg = ''
......@@ -513,7 +499,7 @@ class LoncapaProblem(object):
'hint': hint,
'hintmode': hintmode,}}
input_type_cls = inputtypes.get_class_for_tag(problemtree.tag)
input_type_cls = inputtypes.registry.get_class_for_tag(problemtree.tag)
the_input = input_type_cls(self.system, problemtree, state)
return the_input.get_html()
......@@ -521,9 +507,15 @@ class LoncapaProblem(object):
if problemtree in self.responders:
return self.responders[problemtree].render_html(self._extract_html)
# let each custom renderer render itself:
if problemtree.tag in customrender.registry.registered_tags():
renderer_class = customrender.registry.get_class_for_tag(problemtree.tag)
renderer = renderer_class(self.system, problemtree)
return renderer.get_html()
# otherwise, render children recursively, and copy over attributes
tree = etree.Element(problemtree.tag)
for item in problemtree:
# render child recursively
item_xhtml = self._extract_html(item)
if item_xhtml is not None:
tree.append(item_xhtml)
......@@ -560,11 +552,12 @@ class LoncapaProblem(object):
response_id += 1
answer_id = 1
input_tags = inputtypes.registry.registered_tags()
inputfields = tree.xpath("|".join(['//' + response.tag + '[@id=$id]//' + x
for x in (entry_types + solution_types)]),
for x in (input_tags + solution_tags)]),
id=response_id_str)
# assign one answer_id for each entry_type or solution_type
# assign one answer_id for each input type or solution type
for entry in inputfields:
entry.attrib['response_id'] = str(response_id)
entry.attrib['answer_id'] = str(answer_id)
......
......@@ -68,7 +68,7 @@ class CorrectMap(object):
correct_map is saved by LMS as a plaintext JSON dump of the correctmap dict. This
means that when the definition of CorrectMap (e.g. its properties) are altered,
an existing correct_map dict not coincide with the newest CorrectMap format as
an existing correct_map dict will not coincide with the newest CorrectMap format as
defined by self.set.
For graceful migration, feed the contents of each correct map to self.set, rather than
......
"""
This has custom renderers: classes that know how to render certain problem tags (e.g. <math> and
<solution>) to html.
These tags do not have state, so they just get passed the system (for access to render_template),
and the xml element.
"""
from registry import TagRegistry
import logging
import re
import shlex # for splitting quoted strings
import json
from lxml import etree
import xml.sax.saxutils as saxutils
from registry import TagRegistry
log = logging.getLogger('mitx.' + __name__)
registry = TagRegistry()
#-----------------------------------------------------------------------------
class MathRenderer(object):
tags = ['math']
def __init__(self, system, xml):
'''
Render math using latex-like formatting.
Examples:
<math>$\displaystyle U(r)=4 U_0 $</math>
<math>$r_0$</math>
We convert these to [mathjax]...[/mathjax] and [mathjaxinline]...[/mathjaxinline]
TODO: use shorter tags (but this will require converting problem XML files!)
'''
self.system = system
self.xml = xml
mathstr = re.sub('\$(.*)\$', r'[mathjaxinline]\1[/mathjaxinline]', xml.text)
mtag = 'mathjax'
if not r'\displaystyle' in mathstr:
mtag += 'inline'
else:
mathstr = mathstr.replace(r'\displaystyle', '')
self.mathstr = mathstr.replace('mathjaxinline]', '%s]' % mtag)
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
# TODO: why are there nested html tags here?? Why are there html tags at all, in fact?
html = '<html><html>%s</html><html>%s</html></html>' % (
self.mathstr, saxutils.escape(self.xml.tail))
try:
xhtml = etree.XML(html)
except Exception as err:
if self.system.DEBUG:
msg = '<html><div class="inline-error"><p>Error %s</p>' % (
str(err).replace('<', '&lt;'))
msg += ('<p>Failed to construct math expression from <pre>%s</pre></p>' %
html.replace('<', '&lt;'))
msg += "</div></html>"
log.error(msg)
return etree.XML(msg)
else:
raise
return xhtml
registry.register(MathRenderer)
#-----------------------------------------------------------------------------
class SolutionRenderer(object):
'''
A solution is just a <span>...</span> which is given an ID, that is used for displaying an
extended answer (a problem "solution") after "show answers" is pressed.
Note that the solution content is NOT rendered and returned in the HTML. It is obtained by an
ajax call.
'''
tags = ['solution']
def __init__(self, system, xml):
self.system = system
self.id = xml.get('id')
def get_html(self):
context = {'id': self.id}
html = self.system.render_template("solutionspan.html", context)
return etree.XML(html)
registry.register(SolutionRenderer)
class TagRegistry(object):
"""
A registry mapping tags to handlers.
(A dictionary with some extra error checking.)
"""
def __init__(self):
self._mapping = {}
def register(self, cls):
"""
Register cls as a supported tag type. It is expected to define cls.tags as a list of tags
that it implements.
If an already-registered type has registered one of those tags, will raise ValueError.
If there are no tags in cls.tags, will also raise ValueError.
"""
# Do all checks and complain before changing any state.
if len(cls.tags) == 0:
raise ValueError("No tags specified for class {0}".format(cls.__name__))
for t in cls.tags:
if t in self._mapping:
other_cls = self._mapping[t]
if cls == other_cls:
# registering the same class multiple times seems silly, but ok
continue
raise ValueError("Tag {0} already registered by class {1}."
" Can't register for class {2}"
.format(t, other_cls.__name__, cls.__name__))
# Ok, should be good to change state now.
for t in cls.tags:
self._mapping[t] = cls
def registered_tags(self):
"""
Get a list of all the tags that have been registered.
"""
return self._mapping.keys()
def get_class_for_tag(self, tag):
"""
For any tag in registered_tags(), returns the corresponding class. Otherwise, will raise
KeyError.
"""
return self._mapping[tag]
......@@ -81,7 +81,7 @@ class LoncapaResponse(object):
by __init__
- check_hint_condition : check to see if the student's answers satisfy a particular
condition for a hint to be displayed
condition for a hint to be displayed
- render_html : render this Response as HTML (must return XHTML-compliant string)
- __unicode__ : unicode representation of this Response
......@@ -149,6 +149,7 @@ class LoncapaResponse(object):
# for convenience
self.answer_id = self.answer_ids[0]
# map input_id -> maxpoints
self.maxpoints = dict()
for inputfield in self.inputfields:
# By default, each answerfield is worth 1 point
......@@ -280,17 +281,14 @@ class LoncapaResponse(object):
(correctness, npoints, msg) for each answer_id.
Arguments:
- student_answers : dict of (answer_id,answer) where answer = student input (string)
- old_cmap : previous CorrectMap (may be empty); useful for analyzing or
recording history of responses
- student_answers : dict of (answer_id, answer) where answer = student input (string)
'''
pass
@abc.abstractmethod
def get_answers(self):
'''
Return a dict of (answer_id,answer_text) for each answer for this question.
Return a dict of (answer_id, answer_text) for each answer for this question.
'''
pass
......
<form class="choicegroup capa_inputtype" id="inputtype_${id}">
<div class="indicator_container">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}"></span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}"></span>
% elif state == 'incomplete':
% elif status == 'incomplete':
<span class="incorrect" id="status_${id}"></span>
% endif
</div>
......
......@@ -6,13 +6,13 @@
>${value|h}</textarea>
<div class="grader-status">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}">Unanswered</span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}">Correct</span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}">Incorrect</span>
% elif state == 'queued':
% elif status == 'queued':
<span class="processing" id="status_${id}">Queued</span>
<span style="display:none;" class="xqueue" id="${id}" >${queue_len}</span>
% endif
......@@ -21,7 +21,7 @@
<div style="display:none;" name="${hidden}" inputid="input_${id}" />
% endif
<p class="debug">${state}</p>
<p class="debug">${status}</p>
</div>
<span id="answer_${id}"></span>
......
<% doinline = "inline" if inline else "" %>
<section id="textinput_${id}" class="textinput ${doinline}" >
<section id="inputtype_${id}" class="capa_inputtype" >
<div id="holder" style="width:${width};height:${height}"></div>
<div class="script_placeholder" data-src="/static/js/raphael.js"></div><div class="script_placeholder" data-src="/static/js/sylvester.js"></div><div class="script_placeholder" data-src="/static/js/underscore-min.js"></div>
<div class="script_placeholder" data-src="/static/js/raphael.js"></div>
<div class="script_placeholder" data-src="/static/js/sylvester.js"></div>
<div class="script_placeholder" data-src="/static/js/underscore-min.js"></div>
<div class="script_placeholder" data-src="/static/js/crystallography.js"></div>
% if state == 'unsubmitted':
<div class="unanswered ${doinline}" id="status_${id}">
% elif state == 'correct':
<div class="correct ${doinline}" id="status_${id}">
% elif state == 'incorrect':
<div class="incorrect ${doinline}" id="status_${id}">
% elif state == 'incomplete':
<div class="incorrect ${doinline}" id="status_${id}">
% if status == 'unsubmitted':
<div class="unanswered" id="status_${id}">
% elif status == 'correct':
<div class="correct" id="status_${id}">
% elif status == 'incorrect':
<div class="incorrect" id="status_${id}">
% elif status == 'incomplete':
<div class="incorrect" id="status_${id}">
% endif
% if hidden:
<div style="display:none;" name="${hidden}" inputid="input_${id}" />
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value}"
<input type="text" name="input_${id}" id="input_${id}" value="${value|h}"
% if size:
size="${size}"
% endif
......@@ -29,13 +29,13 @@
/>
<p class="status">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
unanswered
% elif state == 'correct':
% elif status == 'correct':
correct
% elif state == 'incorrect':
% elif status == 'incorrect':
incorrect
% elif state == 'incomplete':
% elif status == 'incomplete':
incomplete
% endif
</p>
......@@ -45,7 +45,7 @@
% if msg:
<span class="message">${msg|n}</span>
% endif
% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden:
% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']:
</div>
% endif
</section>
<section id="filesubmission_${id}" class="filesubmission">
<div class="grader-status file">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}">Unanswered</span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}">Correct</span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}">Incorrect</span>
% elif state == 'queued':
% elif status == 'queued':
<span class="processing" id="status_${id}">Queued</span>
<span style="display:none;" class="xqueue" id="${id}" >${queue_len}</span>
% endif
<p class="debug">${state}</p>
<p class="debug">${status}</p>
<input type="file" name="input_${id}" id="input_${id}" value="${value}" multiple="multiple" data-required_files="${required_files}" data-allowed_files="${allowed_files}"/>
<input type="file" name="input_${id}" id="input_${id}" value="${value}" multiple="multiple" data-required_files="${required_files|h}" data-allowed_files="${allowed_files|h}"/>
</div>
<div class="message">${msg|n}</div>
</section>
......@@ -4,13 +4,13 @@
<img src="/static/green-pointer.png" id="cross_${id}" style="position: absolute;top: ${gy}px;left: ${gx}px;" />
</div>
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}"></span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}"></span>
% elif state == 'incomplete':
% elif status == 'incomplete':
<span class="incorrect" id="status_${id}"></span>
% endif
</span>
......@@ -2,7 +2,7 @@
<input type="hidden" name="input_${id}" id="input_${id}" class="javascriptinput_input"/>
<div class="javascriptinput_data" data-display_class="${display_class}"
data-problem_state="${problem_state}" data-params="${params}"
data-submission="${value}" data-evaluation="${evaluation}">
data-submission="${value|h}" data-evaluation="${msg|h}">
</div>
<div class="script_placeholder" data-src="/static/js/${display_file}"></div>
<div class="javascriptinput_container"></div>
......
......@@ -18,13 +18,13 @@
<textarea style="display:none" id="input_${id}_fromjs" name="input_${id}_fromjs"></textarea>
% endif
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}"></span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}"></span>
% elif state == 'incomplete':
% elif status == 'incomplete':
<span class="incorrect" id="status_${id}"></span>
% endif
% if msg:
......
......@@ -12,13 +12,13 @@
<span id="answer_${id}"></span>
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="unanswered" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'correct':
% elif status == 'correct':
<span class="correct" id="status_${id}"></span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="incorrect" id="status_${id}"></span>
% elif state == 'incomplete':
% elif status == 'incomplete':
<span class="incorrect" id="status_${id}"></span>
% endif
</form>
......@@ -12,13 +12,13 @@
</script>
<span id="answer_${id}"></span>
% if state == 'unsubmitted':
% if status == 'unsubmitted':
<span class="ui-icon ui-icon-bullet" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'correct':
% elif status == 'correct':
<span class="ui-icon ui-icon-check" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'incorrect':
% elif status == 'incorrect':
<span class="ui-icon ui-icon-close" style="display:inline-block;" id="status_${id}"></span>
% elif state == 'incomplete':
% elif status == 'incomplete':
<span class="ui-icon ui-icon-close" style="display:inline-block;" id="status_${id}"></span>
% endif
</span>
......
###
### version of textline.html which does dynamic math
###
<section class="text-input-dynamath capa_inputtype" id="inputtype_${id}">
% if preprocessor is not None:
<div class="text-input-dynamath_data" data-preprocessor="${preprocessor['class_name']}"/>
<div class="script_placeholder" data-src="${preprocessor['script_src']}"/>
% endif
% if state == 'unsubmitted':
<div class="unanswered" id="status_${id}">
% elif state == 'correct':
<div class="correct" id="status_${id}">
% elif state == 'incorrect':
<div class="incorrect" id="status_${id}">
% elif state == 'incomplete':
<div class="incorrect" id="status_${id}">
% endif
% if hidden:
<div style="display:none;" name="${hidden}" inputid="input_${id}" />
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value}" class="math" size="${size if size else ''}"
% if hidden:
style="display:none;"
% endif
/>
<p class="status">
% if state == 'unsubmitted':
unanswered
% elif state == 'correct':
correct
% elif state == 'incorrect':
incorrect
% elif state == 'incomplete':
incomplete
% endif
</p>
<p id="answer_${id}" class="answer"></p>
<div id="display_${id}" class="equation">`{::}`</div>
</div>
<textarea style="display:none" id="input_${id}_dynamath" name="input_${id}_dynamath"> </textarea>
% if msg:
<span class="message">${msg|n}</span>
% endif
</section>
<% doinline = "inline" if inline else "" %>
<section id="textinput_${id}" class="textinput ${doinline}" >
% if state == 'unsubmitted':
<section id="inputtype_${id}" class="${'text-input-dynamath' if do_math else ''} capa_inputtype ${doinline}" >
% if preprocessor is not None:
<div class="text-input-dynamath_data" data-preprocessor="${preprocessor['class_name']}"/>
<div class="script_placeholder" data-src="${preprocessor['script_src']}"/>
% endif
% if status == 'unsubmitted':
<div class="unanswered ${doinline}" id="status_${id}">
% elif state == 'correct':
% elif status == 'correct':
<div class="correct ${doinline}" id="status_${id}">
% elif state == 'incorrect':
% elif status == 'incorrect':
<div class="incorrect ${doinline}" id="status_${id}">
% elif state == 'incomplete':
% elif status == 'incomplete':
<div class="incorrect ${doinline}" id="status_${id}">
% endif
% if hidden:
<div style="display:none;" name="${hidden}" inputid="input_${id}" />
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value}"
% if size:
size="${size}"
% endif
% if hidden:
style="display:none;"
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value|h}"
% if do_math:
class="math"
% endif
% if size:
size="${size}"
% endif
% if hidden:
style="display:none;"
% endif
/>
<p class="status">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
unanswered
% elif state == 'correct':
% elif status == 'correct':
correct
% elif state == 'incorrect':
% elif status == 'incorrect':
incorrect
% elif state == 'incomplete':
% elif status == 'incomplete':
incomplete
% endif
</p>
<p id="answer_${id}" class="answer"></p>
<p id="answer_${id}" class="answer"></p>
% if do_math:
<div id="display_${id}" class="equation">`{::}`</div>
<textarea style="display:none" id="input_${id}_dynamath" name="input_${id}_dynamath">
</textarea>
% endif
% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']:
</div>
% endif
% if msg:
<span class="message">${msg|n}</span>
% endif
% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden:
</div>
% endif
</section>
<% doinline = "inline" if inline else "" %>
<section id="textinput_${id}" class="textinput ${doinline}" >
<section id="inputtype_${id}" class="capa_inputtype" >
<table><tr><td height='600'>
<div id="vsepr_div_${id}" style="position:relative;" data-molecules="${molecules}" data-geometries="${geometries}">
<canvas id="vsepr_canvas_${id}" width="${width}" height="${height}">
......@@ -13,36 +11,28 @@
<div class="script_placeholder" data-src="/static/js/vsepr/vsepr.js"></div>
% if state == 'unsubmitted':
<div class="unanswered ${doinline}" id="status_${id}">
% elif state == 'correct':
<div class="correct ${doinline}" id="status_${id}">
% elif state == 'incorrect':
<div class="incorrect ${doinline}" id="status_${id}">
% elif state == 'incomplete':
<div class="incorrect ${doinline}" id="status_${id}">
% endif
% if hidden:
<div style="display:none;" name="${hidden}" inputid="input_${id}" />
% if status == 'unsubmitted':
<div class="unanswered" id="status_${id}">
% elif status == 'correct':
<div class="correct" id="status_${id}">
% elif status == 'incorrect':
<div class="incorrect" id="status_${id}">
% elif status == 'incomplete':
<div class="incorrect" id="status_${id}">
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value}"
% if size:
size="${size}"
% endif
% if hidden:
style="display:none;"
% endif
<input type="text" name="input_${id}" id="input_${id}" value="${value|h}"
style="display:none;"
/>
<p class="status">
% if state == 'unsubmitted':
% if status == 'unsubmitted':
unanswered
% elif state == 'correct':
% elif status == 'correct':
correct
% elif state == 'incorrect':
% elif status == 'incorrect':
incorrect
% elif state == 'incomplete':
% elif status == 'incomplete':
incomplete
% endif
</p>
......@@ -52,7 +42,7 @@
% if msg:
<span class="message">${msg|n}</span>
% endif
% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden:
% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']:
</div>
% endif
</section>
......@@ -4,13 +4,23 @@ import os
from mock import Mock
import xml.sax.saxutils as saxutils
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
def tst_render_template(template, context):
"""
A test version of render to template. Renders to the repr of the context, completely ignoring
the template name. To make the output valid xml, quotes the content, and wraps it in a <div>
"""
return '<div>{0}</div>'.format(saxutils.escape(repr(context)))
test_system = Mock(
ajax_url='courses/course_id/modx/a_location',
track_function=Mock(),
get_module=Mock(),
render_template=Mock(),
render_template=tst_render_template,
replace_urls=Mock(),
user=Mock(),
filestore=fs.osfs.OSFS(os.path.join(TEST_DIR, "test_files")),
......
from lxml import etree
import unittest
import xml.sax.saxutils as saxutils
from . import test_system
from capa import customrender
# just a handy shortcut
lookup_tag = customrender.registry.get_class_for_tag
def extract_context(xml):
"""
Given an xml element corresponding to the output of test_system.render_template, get back the
original context
"""
return eval(xml.text)
def quote_attr(s):
return saxutils.quoteattr(s)[1:-1] # don't want the outer quotes
class HelperTest(unittest.TestCase):
'''
Make sure that our helper function works!
'''
def check(self, d):
xml = etree.XML(test_system.render_template('blah', d))
self.assertEqual(d, extract_context(xml))
def test_extract_context(self):
self.check({})
self.check({1, 2})
self.check({'id', 'an id'})
self.check({'with"quote', 'also"quote'})
class SolutionRenderTest(unittest.TestCase):
'''
Make sure solutions render properly.
'''
def test_rendering(self):
solution = 'To compute unicorns, count them.'
xml_str = """<solution id="solution_12">{s}</solution>""".format(s=solution)
element = etree.fromstring(xml_str)
renderer = lookup_tag('solution')(test_system, element)
self.assertEqual(renderer.id, 'solution_12')
# our test_system "renders" templates to a div with the repr of the context
xml = renderer.get_html()
context = extract_context(xml)
self.assertEqual(context, {'id' : 'solution_12'})
class MathRenderTest(unittest.TestCase):
'''
Make sure math renders properly.
'''
def check_parse(self, latex_in, mathjax_out):
xml_str = """<math>{tex}</math>""".format(tex=latex_in)
element = etree.fromstring(xml_str)
renderer = lookup_tag('math')(test_system, element)
self.assertEqual(renderer.mathstr, mathjax_out)
def test_parsing(self):
self.check_parse('$abc$', '[mathjaxinline]abc[/mathjaxinline]')
self.check_parse('$abc', '$abc')
self.check_parse(r'$\displaystyle 2+2$', '[mathjax] 2+2[/mathjax]')
# NOTE: not testing get_html yet because I don't understand why it's doing what it's doing.
# .coveragerc for common/lib/xmodule
[run]
data_file = reports/common/lib/xmodule/.coverage
source = common/lib/xmodule
[report]
ignore_errors = True
[html]
directory = reports/common/lib/xmodule/cover
[xml]
output = reports/common/lib/xmodule/coverage.xml
......@@ -28,6 +28,7 @@ setup(
"problem = xmodule.capa_module:CapaDescriptor",
"problemset = xmodule.seq_module:SequenceDescriptor",
"section = xmodule.backcompat_module:SemanticSectionDescriptor",
"selfassessment = xmodule.self_assessment_module:SelfAssessmentDescriptor",
"sequential = xmodule.seq_module:SequenceDescriptor",
"slides = xmodule.backcompat_module:TranslateCustomTagDescriptor",
"vertical = xmodule.vertical_module:VerticalDescriptor",
......
......@@ -30,15 +30,17 @@ TIMEDELTA_REGEX = re.compile(r'^((?P<days>\d+?) day(?:s?))?(\s)?((?P<hours>\d+?)
def only_one(lst, default="", process=lambda x: x):
"""
If lst is empty, returns default
If lst has a single element, applies process to that element and returns it
Otherwise, raises an exeception
If lst has a single element, applies process to that element and returns it.
Otherwise, raises an exception.
"""
if len(lst) == 0:
return default
elif len(lst) == 1:
return process(lst[0])
else:
raise Exception('Malformed XML')
raise Exception('Malformed XML: expected at most one element in list.')
def parse_timedelta(time_str):
......@@ -292,11 +294,11 @@ class CapaModule(XModule):
# check button is context-specific.
# Put a "Check" button if unlimited attempts or still some left
if self.max_attempts is None or self.attempts < self.max_attempts-1:
if self.max_attempts is None or self.attempts < self.max_attempts-1:
check_button = "Check"
else:
# Will be final check so let user know that
check_button = "Final Check"
check_button = "Final Check"
reset_button = True
save_button = True
......@@ -527,26 +529,20 @@ class CapaModule(XModule):
# Problem queued. Students must wait a specified waittime before they are allowed to submit
if self.lcp.is_queued():
current_time = datetime.datetime.now()
prev_submit_time = self.lcp.get_recentmost_queuetime()
prev_submit_time = self.lcp.get_recentmost_queuetime()
waittime_between_requests = self.system.xqueue['waittime']
if (current_time-prev_submit_time).total_seconds() < waittime_between_requests:
msg = 'You must wait at least %d seconds between submissions' % waittime_between_requests
return {'success': msg, 'html': ''} # Prompts a modal dialog in ajax callback
return {'success': msg, 'html': ''} # Prompts a modal dialog in ajax callback
try:
old_state = self.lcp.get_state()
lcp_id = self.lcp.problem_id
correct_map = self.lcp.grade_answers(answers)
except StudentInputError as inst:
# TODO (vshnayder): why is this line here?
#self.lcp = LoncapaProblem(self.definition['data'],
# id=lcp_id, state=old_state, system=self.system)
log.exception("StudentInputError in capa_module:problem_check")
return {'success': inst.message}
except Exception, err:
# TODO: why is this line here?
#self.lcp = LoncapaProblem(self.definition['data'],
# id=lcp_id, state=old_state, system=self.system)
if self.system.DEBUG:
msg = "Error checking problem: " + str(err)
msg += '\nTraceback:\n' + traceback.format_exc()
......@@ -678,10 +674,10 @@ class CapaDescriptor(RawDescriptor):
'problems/' + path[8:],
path[8:],
]
def __init__(self, *args, **kwargs):
super(CapaDescriptor, self).__init__(*args, **kwargs)
weight_string = self.metadata.get('weight', None)
if weight_string:
self.weight = float(weight_string)
......
......@@ -133,7 +133,7 @@ class CourseDescriptor(SequenceDescriptor):
Returns True if the current time is after the specified course end date.
Returns False if there is no end date specified.
"""
if self.end_date is None:
if self.end is None:
return False
return time.gmtime() > self.end
......@@ -247,7 +247,12 @@ class CourseDescriptor(SequenceDescriptor):
@property
def start_date_text(self):
return time.strftime("%b %d, %Y", self.start)
displayed_start = self._try_parse_time('advertised_start') or self.start
return time.strftime("%b %d, %Y", displayed_start)
@property
def end_date_text(self):
return time.strftime("%b %d, %Y", self.end)
# An extra property is used rather than the wiki_slug/number because
# there are courses that change the number for different runs. This allows
......@@ -276,6 +281,21 @@ class CourseDescriptor(SequenceDescriptor):
return self.metadata.get('discussion_link', None)
@property
def forum_posts_allowed(self):
try:
blackout_periods = [(parse_time(start), parse_time(end))
for start, end
in self.metadata.get('discussion_blackouts', [])]
now = time.gmtime()
for start, end in blackout_periods:
if start <= now <= end:
return False
except:
log.exception("Error parsing discussion_blackouts for course {0}".format(self.id))
return True
@property
def hide_progress_tab(self):
"""TODO: same as above, intended to let internal CS50 hide the progress tab
until we get grade integration set up."""
......@@ -283,6 +303,16 @@ class CourseDescriptor(SequenceDescriptor):
return self.metadata.get('hide_progress_tab') == True
@property
def end_of_course_survey_url(self):
"""
Pull from policy. Once we have our own survey module set up, can change this to point to an automatically
created survey for each class.
Returns None if no url specified.
"""
return self.metadata.get('end_of_course_survey_url')
@property
def title(self):
return self.display_name
......
......@@ -355,6 +355,34 @@ div.video {
}
}
a.quality_control {
background: url(../images/hd.png) center no-repeat;
border-right: 1px solid #000;
@include box-shadow(1px 0 0 #555, inset 1px 0 0 #555);
color: #797979;
display: block;
float: left;
line-height: 46px; //height of play pause buttons
margin-left: 0;
padding: 0 lh(.5);
text-indent: -9999px;
@include transition();
width: 30px;
&:hover {
background-color: #444;
color: #fff;
text-decoration: none;
}
&.active {
background-color: #F44;
color: #0ff;
text-decoration: none;
}
}
a.hide-subtitles {
background: url('../images/cc.png') center no-repeat;
color: #797979;
......
......@@ -1995,7 +1995,7 @@ cktsim = (function() {
// set up each schematic entry widget
function update_schematics() {
// set up each schematic on the page
var schematics = document.getElementsByClassName('schematic');
var schematics = $('.schematic');
for (var i = 0; i < schematics.length; ++i)
if (schematics[i].getAttribute("loaded") != "true") {
try {
......@@ -2036,7 +2036,7 @@ function add_schematic_handler(other_onload) {
// ask each schematic input widget to update its value field for submission
function prepare_schematics() {
var schematics = document.getElementsByClassName('schematic');
var schematics = $('.schematic');
for (var i = schematics.length - 1; i >= 0; i--)
schematics[i].schematic.update_value();
}
......@@ -3339,23 +3339,28 @@ schematic = (function() {
}
// add method to canvas to compute relative coords for event
HTMLCanvasElement.prototype.relMouseCoords = function(event){
// run up the DOM tree to figure out coords for top,left of canvas
var totalOffsetX = 0;
var totalOffsetY = 0;
var currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft;
totalOffsetY += currentElement.offsetTop;
}
while (currentElement = currentElement.offsetParent);
// now compute relative position of click within the canvas
this.mouse_x = event.pageX - totalOffsetX;
this.mouse_y = event.pageY - totalOffsetY;
this.page_x = event.pageX;
this.page_y = event.pageY;
try {
if (HTMLCanvasElement)
HTMLCanvasElement.prototype.relMouseCoords = function(event){
// run up the DOM tree to figure out coords for top,left of canvas
var totalOffsetX = 0;
var totalOffsetY = 0;
var currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft;
totalOffsetY += currentElement.offsetTop;
}
while (currentElement = currentElement.offsetParent);
// now compute relative position of click within the canvas
this.mouse_x = event.pageX - totalOffsetX;
this.mouse_y = event.pageY - totalOffsetY;
this.page_x = event.pageX;
this.page_y = event.pageY;
}
}
catch (err) { // ignore
}
///////////////////////////////////////////////////////////////////////////////
......@@ -4091,48 +4096,52 @@ schematic = (function() {
// add dashed lines!
// from http://davidowens.wordpress.com/2010/09/07/html-5-canvas-and-dashed-lines/
CanvasRenderingContext2D.prototype.dashedLineTo = function(fromX, fromY, toX, toY, pattern) {
// Our growth rate for our line can be one of the following:
// (+,+), (+,-), (-,+), (-,-)
// Because of this, our algorithm needs to understand if the x-coord and
// y-coord should be getting smaller or larger and properly cap the values
// based on (x,y).
var lt = function (a, b) { return a <= b; };
var gt = function (a, b) { return a >= b; };
var capmin = function (a, b) { return Math.min(a, b); };
var capmax = function (a, b) { return Math.max(a, b); };
var checkX = { thereYet: gt, cap: capmin };
var checkY = { thereYet: gt, cap: capmin };
if (fromY - toY > 0) {
checkY.thereYet = lt;
checkY.cap = capmax;
}
if (fromX - toX > 0) {
checkX.thereYet = lt;
checkX.cap = capmax;
}
this.moveTo(fromX, fromY);
var offsetX = fromX;
var offsetY = fromY;
var idx = 0, dash = true;
while (!(checkX.thereYet(offsetX, toX) && checkY.thereYet(offsetY, toY))) {
var ang = Math.atan2(toY - fromY, toX - fromX);
var len = pattern[idx];
offsetX = checkX.cap(toX, offsetX + (Math.cos(ang) * len));
offsetY = checkY.cap(toY, offsetY + (Math.sin(ang) * len));
if (dash) this.lineTo(offsetX, offsetY);
else this.moveTo(offsetX, offsetY);
idx = (idx + 1) % pattern.length;
dash = !dash;
}
};
try {
if (CanvasRenderingContext2D)
CanvasRenderingContext2D.prototype.dashedLineTo = function(fromX, fromY, toX, toY, pattern) {
// Our growth rate for our line can be one of the following:
// (+,+), (+,-), (-,+), (-,-)
// Because of this, our algorithm needs to understand if the x-coord and
// y-coord should be getting smaller or larger and properly cap the values
// based on (x,y).
var lt = function (a, b) { return a <= b; };
var gt = function (a, b) { return a >= b; };
var capmin = function (a, b) { return Math.min(a, b); };
var capmax = function (a, b) { return Math.max(a, b); };
var checkX = { thereYet: gt, cap: capmin };
var checkY = { thereYet: gt, cap: capmin };
if (fromY - toY > 0) {
checkY.thereYet = lt;
checkY.cap = capmax;
}
if (fromX - toX > 0) {
checkX.thereYet = lt;
checkX.cap = capmax;
}
this.moveTo(fromX, fromY);
var offsetX = fromX;
var offsetY = fromY;
var idx = 0, dash = true;
while (!(checkX.thereYet(offsetX, toX) && checkY.thereYet(offsetY, toY))) {
var ang = Math.atan2(toY - fromY, toX - fromX);
var len = pattern[idx];
offsetX = checkX.cap(toX, offsetX + (Math.cos(ang) * len));
offsetY = checkY.cap(toY, offsetY + (Math.sin(ang) * len));
if (dash) this.lineTo(offsetX, offsetY);
else this.moveTo(offsetX, offsetY);
idx = (idx + 1) % pattern.length;
dash = !dash;
}
};
}
catch (err) { //noop
}
// given a range of values, return a new range [vmin',vmax'] where the limits
// have been chosen "nicely". Taken from matplotlib.ticker.LinearLocator
function view_limits(vmin,vmax) {
......
class @SelfAssessment
constructor: (element) ->
@el = $(element).find('section.self-assessment')
@id = @el.data('id')
@ajax_url = @el.data('ajax-url')
@state = @el.data('state')
@allow_reset = @el.data('allow_reset')
# valid states: 'initial', 'assessing', 'request_hint', 'done'
# Where to put the rubric once we load it
@errors_area = @$('.error')
@answer_area = @$('textarea.answer')
@rubric_wrapper = @$('.rubric-wrapper')
@hint_wrapper = @$('.hint-wrapper')
@message_wrapper = @$('.message-wrapper')
@submit_button = @$('.submit-button')
@reset_button = @$('.reset-button')
@reset_button.click @reset
@find_assessment_elements()
@find_hint_elements()
@rebind()
# locally scoped jquery.
$: (selector) ->
$(selector, @el)
rebind: () =>
# rebind to the appropriate function for the current state
@submit_button.unbind('click')
@submit_button.show()
@reset_button.hide()
@hint_area.attr('disabled', false)
if @state == 'initial'
@answer_area.attr("disabled", false)
@submit_button.prop('value', 'Submit')
@submit_button.click @save_answer
else if @state == 'assessing'
@answer_area.attr("disabled", true)
@submit_button.prop('value', 'Submit assessment')
@submit_button.click @save_assessment
else if @state == 'request_hint'
@answer_area.attr("disabled", true)
@submit_button.prop('value', 'Submit hint')
@submit_button.click @save_hint
else if @state == 'done'
@answer_area.attr("disabled", true)
@hint_area.attr('disabled', true)
@submit_button.hide()
if @allow_reset
@reset_button.show()
else
@reset_button.hide()
find_assessment_elements: ->
@assessment = @$('select.assessment')
find_hint_elements: ->
@hint_area = @$('textarea.hint')
save_answer: (event) =>
event.preventDefault()
if @state == 'initial'
data = {'student_answer' : @answer_area.val()}
$.postWithPrefix "#{@ajax_url}/save_answer", data, (response) =>
if response.success
@rubric_wrapper.html(response.rubric_html)
@state = 'assessing'
@find_assessment_elements()
@rebind()
else
@errors_area.html(response.error)
else
@errors_area.html('Problem state got out of sync. Try reloading the page.')
save_assessment: (event) =>
event.preventDefault()
if @state == 'assessing'
data = {'assessment' : @assessment.find(':selected').text()}
$.postWithPrefix "#{@ajax_url}/save_assessment", data, (response) =>
if response.success
@state = response.state
if @state == 'request_hint'
@hint_wrapper.html(response.hint_html)
@find_hint_elements()
else if @state == 'done'
@message_wrapper.html(response.message_html)
@allow_reset = response.allow_reset
@rebind()
else
@errors_area.html(response.error)
else
@errors_area.html('Problem state got out of sync. Try reloading the page.')
save_hint: (event) =>
event.preventDefault()
if @state == 'request_hint'
data = {'hint' : @hint_area.val()}
$.postWithPrefix "#{@ajax_url}/save_hint", data, (response) =>
if response.success
@message_wrapper.html(response.message_html)
@state = 'done'
@allow_reset = response.allow_reset
@rebind()
else
@errors_area.html(response.error)
else
@errors_area.html('Problem state got out of sync. Try reloading the page.')
reset: (event) =>
event.preventDefault()
if @state == 'done'
$.postWithPrefix "#{@ajax_url}/reset", {}, (response) =>
if response.success
@answer_area.html('')
@rubric_wrapper.html('')
@hint_wrapper.html('')
@message_wrapper.html('')
@state = 'initial'
@rebind()
@reset_button.hide()
else
@errors_area.html(response.error)
else
@errors_area.html('Problem state got out of sync. Try reloading the page.')
......@@ -22,7 +22,7 @@ class @VideoCaption extends Subview
"""
@$('.video-controls .secondary-controls').append """
<a href="#" class="hide-subtitles" title="Turn off captions">Captions</a>
"""
"""#"
@$('.subtitles').css maxHeight: @$('.video-wrapper').height() - 5
@fetchCaption()
......@@ -144,7 +144,7 @@ class @VideoCaption extends Subview
@el.removeClass('closed')
@scrollCaption()
$.cookie('hide_captions', hide_captions, expires: 3650, path: '/')
captionHeight: ->
if @el.hasClass('fullscreen')
$(window).height() - @$('.video-controls').height()
......
......@@ -16,7 +16,7 @@ class @VideoControl extends Subview
<a href="#" class="add-fullscreen" title="Fill browser">Fill Browser</a>
</div>
</div>
"""
"""#"
unless onTouchBasedDevice()
@$('.video_control').addClass('play').html('Play')
......
......@@ -9,6 +9,7 @@ class @VideoPlayer extends Subview
bind: ->
$(@control).bind('play', @play)
.bind('pause', @pause)
$(@qualityControl).bind('changeQuality', @handlePlaybackQualityChange)
$(@caption).bind('seek', @onSeek)
$(@speedControl).bind('speedChange', @onSpeedChange)
$(@progressSlider).bind('seek', @onSeek)
......@@ -25,6 +26,7 @@ class @VideoPlayer extends Subview
render: ->
@control = new VideoControl el: @$('.video-controls')
@qualityControl = new VideoQualityControl el: @$('.secondary-controls')
@caption = new VideoCaption
el: @el
youtubeId: @video.youtubeId('1.0')
......@@ -41,10 +43,12 @@ class @VideoPlayer extends Subview
rel: 0
showinfo: 0
enablejsapi: 1
modestbranding: 1
videoId: @video.youtubeId()
events:
onReady: @onReady
onStateChange: @onStateChange
onPlaybackQualityChange: @onPlaybackQualityChange
@caption.hideCaptions(@['video'].hide_captions)
addToolTip: ->
......@@ -53,7 +57,7 @@ class @VideoPlayer extends Subview
my: 'top right'
at: 'top center'
onReady: =>
onReady: (event) =>
unless onTouchBasedDevice()
$('.video-load-complete:first').data('video').player.play()
......@@ -68,6 +72,13 @@ class @VideoPlayer extends Subview
when YT.PlayerState.ENDED
@onEnded()
onPlaybackQualityChange: (event, value) =>
quality = @player.getPlaybackQuality()
@qualityControl.onQualityChange(quality)
handlePlaybackQualityChange: (event, value) =>
@player.setPlaybackQuality(value)
onUnstarted: =>
@control.pause()
@caption.pause()
......
class @VideoQualityControl extends Subview
initialize: ->
@quality = null;
bind: ->
@$('.quality_control').click @toggleQuality
render: ->
@el.append """
<a href="#" class="quality_control" title="HD">HD</a>
"""#"
onQualityChange: (value) ->
@quality = value
if @quality in ['hd720', 'hd1080', 'highres']
@el.addClass('active')
else
@el.removeClass('active')
toggleQuality: (event) =>
event.preventDefault()
if @quality in ['hd720', 'hd1080', 'highres']
newQuality = 'large'
else
newQuality = 'hd720'
$(@).trigger('changeQuality', newQuality)
\ No newline at end of file
......@@ -17,7 +17,7 @@ class @VideoVolumeControl extends Subview
<div class="volume-slider"></div>
</div>
</div>
"""
"""#"
@slider = @$('.volume-slider').slider
orientation: "vertical"
range: "min"
......
......@@ -113,3 +113,7 @@ class RoundTripTestCase(unittest.TestCase):
def test_full_roundtrip(self):
self.check_export_roundtrip(DATA_DIR, "full")
def test_selfassessment_roundtrip(self):
#Test selfassessment xmodule to see if it exports correctly
self.check_export_roundtrip(DATA_DIR,"self_assessment")
......@@ -176,6 +176,33 @@ class ImportTestCase(unittest.TestCase):
self.assertEqual(chapter_xml.tag, 'chapter')
self.assertFalse('graceperiod' in chapter_xml.attrib)
def test_is_pointer_tag(self):
"""
Check that is_pointer_tag works properly.
"""
yes = ["""<html url_name="blah"/>""",
"""<html url_name="blah"></html>""",
"""<html url_name="blah"> </html>""",
"""<problem url_name="blah"/>""",
"""<course org="HogwartsX" course="Mathemagics" url_name="3.14159"/>"""]
no = ["""<html url_name="blah" also="this"/>""",
"""<html url_name="blah">some text</html>""",
"""<problem url_name="blah"><sub>tree</sub></problem>""",
"""<course org="HogwartsX" course="Mathemagics" url_name="3.14159">
<chapter>3</chapter>
</course>
"""]
for xml_str in yes:
print "should be True for {0}".format(xml_str)
self.assertTrue(is_pointer_tag(etree.fromstring(xml_str)))
for xml_str in no:
print "should be False for {0}".format(xml_str)
self.assertFalse(is_pointer_tag(etree.fromstring(xml_str)))
def test_metadata_inherit(self):
"""Make sure that metadata is inherited properly"""
......@@ -311,3 +338,17 @@ class ImportTestCase(unittest.TestCase):
system = self.get_system(False)
self.assertRaises(etree.XMLSyntaxError, system.process_xml, bad_xml)
def test_selfassessment_import(self):
'''
Check to see if definition_from_xml in self_assessment_module.py
works properly. Pulls data from the self_assessment directory in the test data directory.
'''
modulestore = XMLModuleStore(DATA_DIR, course_dirs=['self_assessment'])
sa_id = "edX/sa_test/2012_Fall"
location = Location(["i4x", "edX", "sa_test", "selfassessment", "SampleQuestion"])
sa_sample = modulestore.get_instance(sa_id, location)
#10 attempts is hard coded into SampleQuestion, which is the url_name of a selfassessment xml tag
self.assertEqual(sa_sample.metadata['attempts'], '10')
......@@ -32,6 +32,7 @@ class VideoModule(XModule):
self.position = 0
self.show_captions = xmltree.get('show_captions', 'true')
self.source = self._get_source(xmltree)
self.track = self._get_track(xmltree)
if instance_state is not None:
state = json.loads(instance_state)
......@@ -40,13 +41,25 @@ class VideoModule(XModule):
def _get_source(self, xmltree):
# find the first valid source
source = None
for element in xmltree.findall('source'):
return self._get_first_external(xmltree, 'source')
def _get_track(self, xmltree):
# find the first valid track
return self._get_first_external(xmltree, 'track')
def _get_first_external(self, xmltree, tag):
"""
Will return the first valid element
of the given tag.
'valid' means has a non-empty 'src' attribute
"""
result = None
for element in xmltree.findall(tag):
src = element.get('src')
if src:
source = src
result = src
break
return source
return result
def handle_ajax(self, dispatch, get):
'''
......@@ -85,6 +98,7 @@ class VideoModule(XModule):
'id': self.location.html_id(),
'position': self.position,
'source': self.source,
'track' : self.track,
'display_name': self.display_name,
# TODO (cpennington): This won't work when we move to data that isn't on the filesystem
'data_dir': self.metadata['data_dir'],
......
......@@ -25,7 +25,7 @@ def name_to_pathname(name):
def is_pointer_tag(xml_obj):
"""
Check if xml_obj is a pointer tag: <blah url_name="something" />.
No children, one attribute named url_name.
No children, one attribute named url_name, no text.
Special case for course roots: the pointer is
<course url_name="something" org="myorg" course="course">
......@@ -40,7 +40,10 @@ def is_pointer_tag(xml_obj):
expected_attr = set(['url_name', 'course', 'org'])
actual_attr = set(xml_obj.attrib.keys())
return len(xml_obj) == 0 and actual_attr == expected_attr
has_text = xml_obj.text is not None and len(xml_obj.text.strip()) > 0
return len(xml_obj) == 0 and actual_attr == expected_attr and not has_text
def get_metadata_from_xml(xml_object, remove=True):
meta = xml_object.find('meta')
......
<problem display_name="S3E2: Lorentz Force">
<startouttext/>
<p>Consider a hypothetical magnetic field pointing out of your computer screen. Now imagine an electron traveling from right to leftin the plane of your screen. A diagram of this situation is show below.</p>
<center><img width="400" src="/static/images/LSQimages/LSQ_W01_8.png"/></center>
<p>a. The magnitude of the force experienced by the electron is proportional the product of which of the following? (Select all that apply.)</p>
<endouttext/>
<choiceresponse>
<checkboxgroup>
<choice correct="true"><text>Magnetic field strength</text></choice>
<choice correct="false"><text>Electric field strength</text></choice>
<choice correct="true"><text>Electric charge of the electron</text></choice>
<choice correct="false"><text>Radius of the electron</text></choice>
<choice correct="false"><text>Mass of the electron</text></choice>
<choice correct="true"><text>Velocity of the electron</text></choice>
</checkboxgroup>
</choiceresponse>
<startouttext/>
<p>b. The direction of the force experienced by the electron is _______.</p>
<endouttext/>
<choiceresponse>
<checkboxgroup>
<choice correct="false"><text>up, in the plane of the screen.</text></choice>
<choice correct="true"><text>down, in the plane of the screen.</text></choice>
<choice correct="false"><text>into the plane of the screen.</text></choice>
<choice correct="false"><text>out of the plane of the screen.</text></choice>
<choice correct="false"><text>towards the right, in the plane of the screen.</text></choice>
<choice correct="false"><text>towards the left, in the plane of the screen.</text></choice>
</checkboxgroup>
</choiceresponse>
</problem>
<?xml version="1.0"?>
<problem display_name="L4 Problem 1">
<text>
<p>
<b class="bfseries">Part 1: Function Types</b>
</p>
<p>
For each of the following functions, specify the type of its <b class="bfseries">output</b>. You can assume each function is called with an appropriate argument, as specified by its docstring. </p>
<p>
If the output can be either an int or a float, select num, which isn't a real Python type, but which we'll use to indicate that either basic numeric type is legal. </p>
<p>
In fact, in Python, booleans True and False can be operated on as if they were the integers 1 and 0; but it is ugly and confusing to take advantage of this fact, and we will resolutely pretend that it isn't true. </p> <!-- so why even mention it? -->
<p>
<section class="hints">
<div class="collapsible">
<header>
<a href="#" id="id41">What are those lines under the function definitions?</a>
</header>
<section id="id41">
<p>
In this and future problems, you'll see function definitions that look like this: </p>
<pre>
def a(x):
'''
x: int or float.
'''
return x + 1
</pre>
<p>
What are those three lines between <code>def a(x):</code> and <code>return x + 1</code>? These lines are called the <i class="it">docstring</i> of the function. A docstring is a special type of comment that is used to document what your function is doing. Typically, docstrings will explain what the function expects the type(s) of the argument(s) to be, and what the function is returning. </p>
<p>
In Python, docstrings appear immediately after the <code>def</code> line of a function, before the body. Docstrings start and end with triple quotes - this can be triple single quotes or triple double quotes, it doesn't matter as long as they match. To sum up this general form: </p>
<pre>
def myFunction(argument):
"""
Docstring goes here. Explain what type argument(s) should have, and what your function
is going to return.
"""
&lt; Code for your function (the body of the function) goes here &gt;
</pre>
<p>
As you begin coding your own functions, we strongly encourage you to document all your functions by using properly-formatted docstrings! </p>
</section>
</div>
</section>
</p>
<ol class="enumerate">
<li>
<pre>
def a(x):
'''
x: int or float.
'''
return x + 1
</pre>
<p>
Indicate the type of the output that the function <code>a</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="num"/></optionresponse> </p>
</li>
<li>
<pre>
def b(x):
'''
x: int or float.
'''
return x + 1.0
</pre>
<p>
Indicate the type of the output that the function <code>b</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="float"/></optionresponse> </p>
</li>
<li>
<pre>
def c(x, y):
'''
x: int or float.
y: int or float.
'''
return x + y
</pre>
<p>
Indicate the type of the output that the function <code>c</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="num"/></optionresponse> </p>
</li>
<li>
<pre>
def d(x, y):
'''
x: Can be of any type.
y: Can be of any type.
'''
return x &gt; y
</pre>
<p>
Indicate the type of the output that the function <code>d</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="boolean"/></optionresponse> </p>
</li>
<li>
<pre>
def e(x, y, z):
'''
x: Can be of any type.
y: Can be of any type.
z: Can be of any type.
'''
return x &gt;= y and x &lt;= z
</pre>
<p>
Indicate the type of the output that the function <code>e</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="boolean"/></optionresponse> </p>
</li>
<li>
<pre>
def f(x, y):
'''
x: int or float.
y: int or float
'''
x + y - 2
</pre>
<p>
Indicate the type of the output that the function <code>f</code> will yield. <optionresponse><optioninput options="('NoneType','num','int','float','boolean')" correct="NoneType"/></optionresponse> </p>
</li>
</ol>
<p>
<b class="bfseries">Part 2: Transcript</b>
</p>
<p>
Below is a transcript of a session with the Python shell. Assume the functions from Part 1 (above) have been defined. Provide the type and value of the expressions being evaluated. If evaluating an expression would cause an error, select NoneType and write 'error' in the box. If the value of an expression is a function, select function as the type and write 'function' in the box. </p>
<ol class="enumerate">
<li>
<p>
<code>a(6)</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="int"/>
</optionresponse>
<stringresponse answer="7">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>a(-5.3)</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="float"/>
</optionresponse>
<stringresponse answer="-4.3">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>a(a(a(6)))</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="int"/>
</optionresponse>
<stringresponse answer="9">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>c(a(1), b(1))</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="float"/>
</optionresponse>
<stringresponse answer="4.0">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>d('apple', 11.1)</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="boolean"/>
</optionresponse>
<stringresponse answer="True">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>e(a(3), b(4), c(3, 4))</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="boolean"/>
</optionresponse>
<stringresponse answer="False">
<textline size="50"/>
</stringresponse>
</p>
</li>
<li>
<p>
<code>f</code>
<optionresponse>
<optioninput options="('NoneType','num','int','float','boolean','function')" correct="function"/>
</optionresponse>
<stringresponse answer="function">
<textline size="50"/>
</stringresponse>
</p>
</li>
</ol>
</text>
</problem>
<problem display_name="S3E3: Deflection of a Proton">
<startouttext/>
<p>Suppose you were to pass a hydroge ion (H+) through an electric field and measure the deflection of the ion. How would its deflection compare to the deflection of an electron passed through the same electric field? </p>
<endouttext/>
<multiplechoiceresponse direction="vertical" randomize="yes">
<choicegroup type="MultipleChoice">
<choice location="random" correct="false" name="1"><text>The ion would deflect identically as both species have the same charge.</text></choice>
<choice location="random" correct="false" name="2"><text>The ion would deflect by an amount identical in magnitude but opposite in direction because the charges are of opposite sign but equal in magnitude.</text></choice>
<choice location="random" correct="false" name="3"><text>The deflection will be in the same direction but smaller in magnitude due to the larger mass of the ion.</text></choice>
<choice location="random" correct="true" name="4"><text>The deflection will be smaller in magnitude due to the increased mass of the ion, as well as in the opposite direction due to the opposite sign of the charge.</text></choice>
</choicegroup>
</multiplechoiceresponse>
</problem>
\ No newline at end of file
<problem display_name="S2E2: Hydrogen Combustion">
<text>
<p>Gaseous hydrogen can be reacted with gaseous oxygen in the presence of a flame to produce water vapor according to the following reaction:</p>
[mathjax] \text{ a } \text{H}_{2 } + \text{ b }\text{O}_{2 } = \text{ c }\text{H}_{2 }\text{O }[/mathjax]
<p>Balance the equation i.e., specify the values of <i> a, b, </i> and <i>c</i>. Use the lowest whole number coefficients.</p>
<p>a =</p>
<numericalresponse answer="2">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline correct_answer="2" math="1" />
</numericalresponse>
<p>b =
<numericalresponse answer="1">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline math="1" />
</numericalresponse> </p>
<p>c =
<numericalresponse answer="2">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline math="1" />
</numericalresponse> </p>
</text>
</problem>
<problem>
<text>
<p>Metallothermic production of zirconium (Zr) would involve the reaction of sodium (Na) with zirconium tetrachloride (ZrCl<sub>4</sub>).</p>
<p><b>(a)</b> Write a balanced chemical equation.</p>
<!-- chemformularesponse
[mathjax] \text{a ZrCl}_{4 } + \text{ b }\text{Na} -> \text{ c }\text{NaCl } + \text{ d } \text{Zr} [/mathjax]
ratio of (a, b, c, d) = (1, 4, 4, 1)
-->
<customresponse>
<chemicalequationinput size="50"/>
<answer type="loncapa/python">
if chemcalc.chemical_equations_equal(submission[0], 'ZrCl4 + 4 Na -&gt; 4 NaCl + Zr'):
correct = ['correct']
else:
correct = ['incorrect']
</answer>
</customresponse>
<p><b>(b)</b> Write the balanced chemical equation using lowest whole numbers.</p>
<!-- chemformularesponse
as above, with (a, b, c, d) = (1, 4, 4, 1)
-->
<customresponse>
<chemicalequationinput size="50"/>
<answer type="loncapa/python">
if chemcalc.chemical_equations_equal(submission[0], 'ZrCl4 + 4 Na -&gt; 4 NaCl + Zr', exact=True):
correct = ['correct']
else:
correct = ['incorrect']
</answer>
</customresponse>
<p><b>(c)</b> Calculate the amount of zirconium produced (in kg) if a reactor were charged with 111 kg [mathjaxinline]\text{ZrCl}_4[/mathjaxinline] and 11.1 kg [mathjaxinline]\text{Na}[/mathjaxinline].
<numericalresponse answer="11.0">
<responseparam type="tolerance" default="5%" name="tol" description="Numerical Tolerance" />
<textline math="1" />
</numericalresponse> </p>
<br/>
<solution>
<p><b>SOLUTION:</b></p>
<p><b>(b)</b>[mathjax] \text{ZrCl}_{4 } + \mathbf{4 }\text{Na} = \mathbf{4 }\text{NaCl } + \mathbf{1 } \text{Zr} [/mathjax] </p>
<p><b>(c)</b></p>
<p>[mathjaxinline]111\text{kg ZrCl}_4 = 111000/[91.22 + (4 \times 35.45)] = 476 \text{ moles ZrCl}_4[/mathjaxinline] </p>
<p>[mathjaxinline]11.1\text{ kg Na} = 11100/22.99 = 483\text{ moles C}[/mathjaxinline]</p>
<p>stoichiometry of reaction further dictates that on a molar basis there needs to be 4 x amount of [mathjaxinline]\text{Na}[/mathjaxinline] as there is [mathjaxinline]\text{ZrCl}_4[/mathjaxinline], but calculations show there to be a shortfall of [mathjaxinline]\text{Na}[/mathjaxinline] </p>
<p>[mathjaxinline]\therefore[/mathjaxinline] reaction yield is contrained by [mathjaxinline]\text{Na}[/mathjaxinline] present </p>
<p>stoichiometry of reaction further dictates that if [mathjaxinline]\text{Na}[/mathjaxinline] controls the yield, then the amount of [mathjaxinline]\text{Zr}[/mathjaxinline] produced = 1/4 x molar quantity of [mathjaxinline]\text{Na}[/mathjaxinline] = 1/4 x 483 moles = 121 </p>
[mathjaxinline]121 \text{ moles Zr} \times 91.22\text{ g / mol } \mathbf{= 11.0 \text{ kg Zr} }[/mathjaxinline]<br/>
</solution>
</text>
</problem>
<problem>
<choiceresponse>
<checkboxgroup>
<choice correct="false">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</checkboxgroup>
</choiceresponse>
<choiceresponse>
<checkboxgroup>
<choice correct="false">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</checkboxgroup>
</choiceresponse>
<choiceresponse>
<checkboxgroup>
<choice correct="false">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</checkboxgroup>
</choiceresponse>
</problem>
<problem>
<choiceresponse>
<radiogroup>
<choice correct="false">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</radiogroup>
</choiceresponse>
<choiceresponse>
<radiogroup>
<choice correct="false">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="true">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</radiogroup>
</choiceresponse>
</problem>
<problem>
<text>
<h2>Code response</h2>
<p>
</p>
<text>
Write a program to compute the square of a number
<coderesponse tests="repeat:2,generate">
<textbox rows="10" cols="70" mode="python"/>
<codeparam>
<initial_display>def square(x):</initial_display>
<answer_display>answer</answer_display>
<grader_payload>grader stuff</grader_payload>
</codeparam>
</coderesponse>
</text>
<text>
Write a program to compute the square of a number
<coderesponse tests="repeat:2,generate">
<textbox rows="10" cols="70" mode="python"/>
<codeparam>
<initial_display>def square(x):</initial_display>
<answer_display>answer</answer_display>
<grader_payload>grader stuff</grader_payload>
</codeparam>
</coderesponse>
</text>
</text>
</problem>
<problem>
<text>
<h2>Code response</h2>
<p>
</p>
<text>
Write a program to compute the square of a number
<coderesponse tests="repeat:2,generate">
<textbox rows="10" cols="70" mode="python"/>
<answer><![CDATA[
initial_display = """
def square(n):
"""
answer = """
def square(n):
return n**2
"""
preamble = """
import sys, time
"""
test_program = """
import random
import operator
def testSquare(n = None):
if n is None:
n = random.randint(2, 20)
print 'Test is: square(%d)'%n
return str(square(n))
def main():
f = os.fdopen(3,'w')
test = int(sys.argv[1])
rndlist = map(int,os.getenv('rndlist').split(','))
random.seed(rndlist[0])
if test == 1: f.write(testSquare(0))
elif test == 2: f.write(testSquare(1))
else: f.write(testSquare())
f.close()
main()
sys.exit(0)
"""
]]>
</answer>
</coderesponse>
</text>
<text>
Write a program to compute the cube of a number
<coderesponse tests="repeat:2,generate">
<textbox rows="10" cols="70" mode="python"/>
<answer><![CDATA[
initial_display = """
def cube(n):
"""
answer = """
def cube(n):
return n**3
"""
preamble = """
import sys, time
"""
test_program = """
import random
import operator
def testCube(n = None):
if n is None:
n = random.randint(2, 20)
print 'Test is: cube(%d)'%n
return str(cube(n))
def main():
f = os.fdopen(3,'w')
test = int(sys.argv[1])
rndlist = map(int,os.getenv('rndlist').split(','))
random.seed(rndlist[0])
if test == 1: f.write(testCube(0))
elif test == 2: f.write(testCube(1))
else: f.write(testCube())
f.close()
main()
sys.exit(0)
"""
]]>
</answer>
</coderesponse>
</text>
</text>
</problem>
<problem>
<script type="loncapa/python">
# from loncapa import *
x1 = 4 # lc_random(2,4,1)
y1 = 5 # lc_random(3,7,1)
x2 = 10 # lc_random(x1+1,9,1)
y2 = 20 # lc_random(y1+1,15,1)
m = (y2-y1)/(x2-x1)
b = y1 - m*x1
answer = "%s*x+%s" % (m,b)
answer = answer.replace('+-','-')
inverted_m = (x2-x1)/(y2-y1)
inverted_b = b
wrongans = "%s*x+%s" % (inverted_m,inverted_b)
wrongans = wrongans.replace('+-','-')
</script>
<text>
<p>Hints can be provided to students, based on the last response given, as well as the history of responses given. Here is an example of a hint produced by a Formula Response problem.</p>
<p>
What is the equation of the line which passess through ($x1,$y1) and
($x2,$y2)?</p>
<p>The correct answer is <tt>$answer</tt>. A common error is to invert the equation for the slope. Enter <tt>
$wrongans</tt> to see a hint.</p>
</text>
<formularesponse samples="x@-5:5#11" id="11" answer="$answer">
<responseparam description="Numerical Tolerance" type="tolerance" default="0.001" name="tol" />
<text>y = <textline size="25" /></text>
<hintgroup>
<formulahint samples="x@-5:5#11" answer="$wrongans" name="inversegrad">
</formulahint>
<hintpart on="inversegrad">
<text>You have inverted the slope in the question.</text>
</hintpart>
</hintgroup>
</formularesponse>
</problem>
<problem>
<text><p>
Two skiers are on frictionless black diamond ski slopes.
Hello</p></text>
<imageresponse max="1" loncapaid="11">
<imageinput src="/static/Physics801/Figures/Skier-conservation of energy.jpg" width="560" height="388" rectangle="(490,11)-(556,98)"/>
<text>Click on the image where the top skier will stop momentarily if the top skier starts from rest.</text>
<imageinput src="/static/Physics801/Figures/Skier-conservation of energy.jpg" width="560" height="388" rectangle="(242,202)-(296,276)"/>
<text>Click on the image where the lower skier will stop momentarily if the lower skier starts from rest.</text>
<imageinput src="/static/Physics801/Figures/Skier-conservation of energy.jpg" width="560" height="388" rectangle="(490,11)-(556,98);(242,202)-(296,276)"/>
<text>Click on either of the two positions as discussed previously.</text>
<imageinput src="/static/Physics801/Figures/Skier-conservation of energy.jpg" width="560" height="388" rectangle="(490,11)-(556,98);(242,202)-(296,276)"/>
<text>Click on either of the two positions as discussed previously.</text>
<imageinput src="/static/Physics801/Figures/Skier-conservation of energy.jpg" width="560" height="388" rectangle="(490,11)-(556,98);(242,202)-(296,276)"/>
<text>Click on either of the two positions as discussed previously.</text>
<hintgroup showoncorrect="no">
<text><p>Use conservation of energy.</p></text>
</hintgroup>
</imageresponse>
</problem>
<problem>
<javascriptresponse>
<generator src="test_problem_generator.js"/>
<grader src="test_problem_grader.js"/>
<display class="TestProblemDisplay" src="test_problem_display.js"/>
<responseparam name="value" value="4"/>
<javascriptinput>
</javascriptinput>
</javascriptresponse>
</problem>
<problem>
<multiplechoiceresponse>
<choicegroup>
<choice correct="false" >
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false" >
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true" >
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false">
<startouttext />This is foil Five.<endouttext />
</choice>
</choicegroup>
</multiplechoiceresponse>
</problem>
<problem>
<multiplechoiceresponse>
<choicegroup>
<choice correct="false" name="foil1">
<startouttext />This is foil One.<endouttext />
</choice>
<choice correct="false" name="foil2">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice correct="true" name="foil3">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice correct="false" name="foil4">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice correct="false" name="foil5">
<startouttext />This is foil Five.<endouttext />
</choice>
</choicegroup>
</multiplechoiceresponse>
</problem>
<problem display_name="S3E3: Deflection of a Proton">
<startouttext/>
<p>Suppose you were to pass a hydroge ion (H+) through an electric field and measure the deflection of the ion. How would its deflection compare to the deflection of an electron passed through the same electric field? </p>
<endouttext/>
<multiplechoiceresponse direction="vertical" randomize="yes">
<choicegroup type="MultipleChoice">
<choice location="random" correct="false" name="1"><text>The ion would deflect identically as both species have the same charge.</text></choice>
<choice location="random" correct="false" name="2"><text>The ion would deflect by an amount identical in magnitude but opposite in direction because the charges are of opposite sign but equal in magnitude.</text></choice>
<choice location="random" correct="false" name="3"><text>The deflection will be in the same direction but smaller in magnitude due to the larger mass of the ion.</text></choice>
<choice location="random" correct="true" name="4"><text>The deflection will be smaller in magnitude due to the increased mass of the ion, as well as in the opposite direction due to the opposite sign of the charge.</text></choice>
</choicegroup>
</multiplechoiceresponse>
</problem>
\ No newline at end of file
<problem display_name="S2E2: Hydrogen Combustion">
<text>
<p>Gaseous hydrogen can be reacted with gaseous oxygen in the presence of a flame to produce water vapor according to the following reaction:</p>
[mathjax] \text{ a } \text{H}_{2 } + \text{ b }\text{O}_{2 } = \text{ c }\text{H}_{2 }\text{O }[/mathjax]
<p>Balance the equation i.e., specify the values of <i> a, b, </i> and <i>c</i>. Use the lowest whole number coefficients.</p>
<p>a =</p>
<numericalresponse answer="2">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline correct_answer="2" math="1" />
</numericalresponse>
<p>b =
<numericalresponse answer="1">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline math="1" />
</numericalresponse> </p>
<p>c =
<numericalresponse answer="2">
<responseparam type="tolerance" default="1%" name="tol" description="Numerical Tolerance" />
<textline math="1" />
</numericalresponse> </p>
</text>
</problem>
<problem>
<text>
<p>
Why do bicycles benefit from having larger wheels when going up a bump as shown in the picture? <br/>
Assume that for both bicycles:<br/>
1.) The tires have equal air pressure.<br/>
2.) The bicycles never leave the contact with the bump.<br/>
3.) The bicycles have the same mass. The bicycle tires (regardless of size) have the same mass.<br/>
</p>
</text>
<optionresponse texlayout="horizontal" max="10" randomize="yes">
<ul>
<li>
<text>
<p>The bicycles with larger wheels have more time to go over the bump. This decreases the magnitude of the force needed to lift the bicycle.</p>
</text>
<optioninput name="Foil1" location="random" options="('True','False')" correct="True">
</optioninput>
</li>
<li>
<text>
<p>The bicycles with larger wheels always have a smaller vertical displacement regardless of speed.</p>
</text>
<optioninput name="Foil2" location="random" options="('True','False')" correct="False">
</optioninput>
</li>
<li>
<text>
<p>The bicycles with larger wheels experience a force backward with less magnitude for the same amount of time.</p>
</text>
<optioninput name="Foil3" location="random" options="('True','False')" correct="False">
</optioninput>
</li>
<li>
<text>
<p>The bicycles with larger wheels experience a force backward with less magnitude for a greater amount of time.</p>
</text>
<optioninput name="Foil4" location="random" options="('True','False')" correct="True">
</optioninput>
</li>
<li>
<text>
<p>The bicycles with larger wheels have more kinetic energy turned into gravitational potential energy.</p>
</text>
<optioninput name="Foil5" location="random" options="('True','False')" correct="False">
</optioninput>
</li>
<li>
<text>
<p>The bicycles with larger wheels have more rotational kinetic energy, so the horizontal velocity of the biker changes less.</p>
</text>
<optioninput name="Foil6" location="random" options="('True','False')" correct="False">
</optioninput>
</li>
</ul>
<hintgroup showoncorrect="no">
<text>
<br/>
<br/>
</text>
</hintgroup>
</optionresponse>
</problem>
<problem >
<text><h2>Example: String Response Problem</h2>
<br/>
</text>
<text>Which US state has Lansing as its capital?</text>
<stringresponse answer="Michigan" type="ci">
<textline size="20" />
<hintgroup>
<stringhint answer="wisconsin" type="cs" name="wisc">
</stringhint>
<stringhint answer="minnesota" type="cs" name="minn">
</stringhint>
<hintpart on="wisc">
<text>The state capital of Wisconsin is Madison.</text>
</hintpart>
<hintpart on="minn">
<text>The state capital of Minnesota is St. Paul.</text>
</hintpart>
<hintpart on="default">
<text>The state you are looking for is also known as the 'Great Lakes State'</text>
</hintpart>
</hintgroup>
</stringresponse>
</problem>
<problem>
<text>
<h2>Example: Symbolic Math Response Problem</h2>
<p>
A symbolic math response problem presents one or more symbolic math
input fields for input. Correctness of input is evaluated based on
the symbolic properties of the expression entered. The student enters
text, but sees a proper symbolic rendition of the entered formula, in
real time, next to the input box.
</p>
<p>This is a correct answer which may be entered below: </p>
<p><tt>cos(theta)*[[1,0],[0,1]] + i*sin(theta)*[[0,1],[1,0]]</tt></p>
<script>
from symmath import *
</script>
<text>Compute [mathjax] U = \exp\left( i \theta \left[ \begin{matrix} 0 &amp; 1 \\ 1 &amp; 0 \end{matrix} \right] \right) [/mathjax]
and give the resulting \(2 \times 2\) matrix. <br/>
Your input should be typed in as a list of lists, eg <tt>[[1,2],[3,4]]</tt>. <br/>
[mathjax]U=[/mathjax] <symbolicresponse cfn="symmath_check" answer="[[cos(theta),I*sin(theta)],[I*sin(theta),cos(theta)]]" options="matrix,imaginaryi" id="filenamedogi0VpEBOWedxsymmathresponse_1" state="unsubmitted">
<textline size="80" math="1" response_id="2" answer_id="1" id="filenamedogi0VpEBOWedxsymmathresponse_2_1"/>
</symbolicresponse>
<br/>
</text>
</text>
</problem>
<problem>
<truefalseresponse max="10" randomize="yes">
<choicegroup>
<choice location="random" correct="true" name="foil1">
<startouttext />This is foil One.<endouttext />
</choice>
<choice location="random" correct="true" name="foil2">
<startouttext />This is foil Two.<endouttext />
</choice>
<choice location="random" correct="false" name="foil3">
<startouttext />This is foil Three.<endouttext />
</choice>
<choice location="random" correct="false" name="foil4">
<startouttext />This is foil Four.<endouttext />
</choice>
<choice location="random" correct="false" name="foil5">
<startouttext />This is foil Five.<endouttext />
</choice>
</choicegroup>
</truefalseresponse>
</problem>
<vertical display_name="Test problems">
<problem url_name="test_files:numericalresponse_demo"/>
<problem url_name="test_files:choiceresponse_checkbox"/>
<problem url_name="test_files:choiceresponse_radio"/>
<problem url_name="test_files:coderesponse"/>
<problem url_name="test_files:coderesponse_externalresponseformat"/>
<problem url_name="test_files:formularesponse_with_hint"/>
<problem url_name="test_files:imageresponse"/>
<problem url_name="test_files:javascriptresponse"/>
<problem url_name="test_files:multi_bare"/>
<problem url_name="test_files:multichoice"/>
<problem url_name="test_files:multiplechoicelresponse_demo"/>
<problem url_name="test_files:numericalresponse_demo"/>
<problem url_name="test_files:optionresponse"/>
<problem url_name="test_files:stringresponse_with_hint"/>
<problem url_name="test_files:symbolicresponse"/>
<problem url_name="test_files:truefalse"/>
<problem url_name="test_files:chemicalequationresponse"/>
<problem url_name="test_files:filesubmission"/>
</vertical>
\ No newline at end of file
This is a very very simple course, useful for debugging self assessment code.
roots/2012_Fall.xml
\ No newline at end of file
<course>
<chapter url_name="Overview">
<selfassessment url_name="SampleQuestion"/>
</chapter>
</course>
{
"course/2012_Fall": {
"graceperiod": "2 days 5 hours 59 minutes 59 seconds",
"start": "2015-07-17T12:00",
"display_name": "Self Assessment Test",
"graded": "true"
},
"chapter/Overview": {
"display_name": "Overview"
},
"selfassessment/SampleQuestion": {
"display_name": "Sample Question",
},
}
<course org="edX" course="sa_test" url_name="2012_Fall"/>
<selfassessment attempts='10'>
<prompt>
What is the meaning of life?
</prompt>
<rubric>
This is a rubric.
</rubric>
<submitmessage>
Thanks for your submission!
</submitmessage>
<hintprompt>
Enter a hint below:
</hintprompt>
</selfassessment>
......@@ -99,7 +99,7 @@ NUMPY_VER="1.6.2"
SCIPY_VER="0.10.1"
BREW_FILE="$BASE/mitx/brew-formulas.txt"
LOG="/var/tmp/install-$(date +%Y%m%d-%H%M%S).log"
APT_PKGS="pkg-config curl git python-virtualenv build-essential python-dev gfortran liblapack-dev libfreetype6-dev libpng12-dev libxml2-dev libxslt-dev yui-compressor coffeescript graphviz graphviz-dev"
APT_PKGS="pkg-config curl git python-virtualenv build-essential python-dev gfortran liblapack-dev libfreetype6-dev libpng12-dev libxml2-dev libxslt-dev yui-compressor nodejs npm graphviz graphviz-dev mysql-server libmysqlclient-dev"
if [[ $EUID -eq 0 ]]; then
error "This script should not be run using sudo or as the root user"
......@@ -186,8 +186,12 @@ case `uname -s` in
case $distro in
maya|lisa|natty|oneiric|precise|quantal)
output "Installing ubuntu requirements"
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get -y update
sudo apt-get -y install $APT_PKGS
# DEBIAN_FRONTEND=noninteractive is required for silent mysql-server installation
sudo DEBIAN_FRONTEND=noninteractive apt-get -y install $APT_PKGS
sudo npm install coffee-script
clone_repos
;;
*)
......
# Notes on using mongodb backed LMS and CMS
These are some random notes for developers, on how things are stored in mongodb, and how to debug mongodb data.
## Databases
Two mongodb databases are used:
- xmodule: stores module definitions and metadata (modulestore)
- xcontent: stores filesystem content, like PDF files
modulestore documents are stored with an _id which has fields like this:
{"_id": {"tag":"i4x","org":"HarvardX","course":"CS50x","category":"chapter","name":"Week_1","revision":null}}
## Document fields
### Problems
Here is an example showing the fields available in problem documents:
{
"_id" : {
"tag" : "i4x",
"org" : "MITx",
"course" : "6.00x",
"category" : "problem",
"name" : "ps03:ps03-Hangman_part_2_The_Game",
"revision" : null
},
"definition" : {
"data" : " ..."
},
"metadata" : {
"display_name" : "Hangman Part 2: The Game",
"attempts" : "30",
"title" : "Hangman, Part 2",
"data_dir" : "6.00x",
"type" : "lecture"
}
}
## Sample interaction with mongodb
1. "mongo"
2. "use xmodule"
3. "show collections" should give "modulestore" and "system.indexes"
4. 'db.modulestore.find( {"_id.org": "MITx"} )' will produce a list of all MITx course documents
5. 'db.modulestore.find( {"_id.org": "MITx", "_id.category": "problem"} )' will produce a list of all problems in MITx courses
Example query for finding all files with "image" in the filename:
- use xcontent
- db.fs.files.find({'filename': /image/ } )
- db.fs.files.find({'filename': /image/ } ).count()
## Debugging the mongodb contents
A convenient tool is http://phpmoadmin.com/ (needs php)
Under ubuntu, do:
- apt-get install php5-fpm php-pear
- pecl install mongo
- edit /etc/php5/fpm/php.ini to add "extension=mongo.so"
- /etc/init.d/php5-fpm restart
and also setup nginx to run php through fastcgi.
## Backing up mongodb
- mogodump (dumps all dbs)
- mongodump --collection modulestore --db xmodule (dumps just xmodule/modulestore)
- mongodump -d xmodule -q '{"_id.org": "MITx"}' (dumps just MITx documents in xmodule)
- mongodump -q '{"_id.org": "MITx"}' (dumps all MITx documents)
## Deleting course content
Use "remove" instead of "find":
- db.modulestore.remove( {"_id.course": "8.01greytak"})
## Finding useful information from the mongodb modulestore
- Organizations
> db.modulestore.distinct( "_id.org")
[ "HarvardX", "MITx", "edX", "edx" ]
- Courses
> db.modulestore.distinct( "_id.course")
[
"CS50x",
"PH207x",
"3.091x",
"6.002x",
"6.00x",
"8.01esg",
"8.01rq_MW",
"8.02teal",
"8.02x",
"edx4edx",
"toy",
"templates"
]
- Find a problem which has the word "quantum" in its definition
db.modulestore.findOne( {"definition.data":/quantum/})n
- Find Location for all problems with the word "quantum" in its definition
db.modulestore.find( {"definition.data":/quantum/}, {'_id':1})
- Number of problems in each course
db.runCommand({
mapreduce: "modulestore",
query: { '_id.category': 'problem' },
map: function(){ emit(this._id.course, {count:1}); },
reduce: function(key, values){
var result = {count:0};
values.forEach(function(value) {
result.count += value.count;
});
return result;
},
out: 'pbyc',
verbose: true
});
produces:
> db.pbyc.find()
{ "_id" : "3.091x", "value" : { "count" : 184 } }
{ "_id" : "6.002x", "value" : { "count" : 176 } }
{ "_id" : "6.00x", "value" : { "count" : 147 } }
{ "_id" : "8.01esg", "value" : { "count" : 184 } }
{ "_id" : "8.01rq_MW", "value" : { "count" : 73 } }
{ "_id" : "8.02teal", "value" : { "count" : 5 } }
{ "_id" : "8.02x", "value" : { "count" : 99 } }
{ "_id" : "PH207x", "value" : { "count" : 25 } }
{ "_id" : "edx4edx", "value" : { "count" : 50 } }
{ "_id" : "templates", "value" : { "count" : 11 } }
......@@ -250,9 +250,13 @@ Values are dictionaries of the form {"metadata-key" : "metadata-value"}.
Supported fields at the course level:
* "start" -- specify the start date for the course. Format-by-example: "2012-09-05T12:00".
* "advertised_start" -- specify what you want displayed as the start date of the course in the course listing and course about pages. This can be useful if you want to let people in early before the formal start. Format-by-example: "2012-09-05T12:00".
* "enrollment_start", "enrollment_end" -- when can students enroll? (if not specified, can enroll anytime). Same format as "start".
* "end" -- specify the end date for the course. Format-by-example: "2012-11-05T12:00".
* "end_of_course_survey_url" -- a url for an end of course survey -- shown after course is over, next to certificate download links.
* "tabs" -- have custom tabs in the courseware. See below for details on config.
* "discussion_blackouts" -- An array of time intervals during which you want to disable a student's ability to create or edit posts in the forum. Moderators, Community TAs, and Admins are unaffected. You might use this during exam periods, but please be aware that the forum is often a very good place to catch mistakes and clarify points to students. The better long term solution would be to have better flagging/moderation mechanisms, but this is the hammer we have today. Format by example: [["2012-10-29T04:00", "2012-11-03T04:00"], ["2012-12-30T04:00", "2013-01-02T04:00"]]
* "show_calculator" (value "Yes" if desired)
* TODO: there are others
### Grading policy file contents
......
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/MITx.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/MITx.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/MITx"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/MITx"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
{% extends "!layout.html" %}
{% block header %}
<img src="{{ pathto("_static/homepage-bg.jpg", 1) }}" alt="Edx logo" width="100%;"/>
{% endblock %}
\ No newline at end of file
*******************************************
Capa module
*******************************************
.. module:: capa
Calc
====
.. automodule:: capa.calc
:members:
:show-inheritance:
Capa_problem
============
.. automodule:: capa.capa_problem
:members:
:show-inheritance:
Checker
=======
.. automodule:: capa.checker
:members:
:show-inheritance:
Correctmap
==========
.. automodule:: capa.correctmap
:members:
:show-inheritance:
Customrender
============
.. automodule:: capa.customrender
:members:
:show-inheritance:
Inputtypes
==========
.. automodule:: capa.inputtypes
:members:
:show-inheritance:
Resposetypes
============
.. automodule:: capa.responsetypes
:members:
:show-inheritance:
*******************************************
CMS module
*******************************************
.. module:: cms
Auth
====
.. automodule:: auth
:members:
:show-inheritance:
Authz
-----
.. automodule:: auth.authz
:members:
:show-inheritance:
Content store
=============
.. .. automodule:: contentstore
.. :members:
.. :show-inheritance:
.. Utils
.. -----
.. .. automodule:: contentstore.untils
.. :members:
.. :show-inheritance:
.. Views
.. -----
.. .. automodule:: contentstore.views
.. :members:
.. :show-inheritance:
.. Management
.. ----------
.. .. automodule:: contentstore.management
.. :members:
.. :show-inheritance:
.. Tests
.. -----
.. .. automodule:: contentstore.tests
.. :members:
.. :show-inheritance:
Github sync
===========
.. automodule:: github_sync
:members:
:show-inheritance:
Exceptions
----------
.. automodule:: github_sync.exceptions
:members:
:show-inheritance:
Views
-----
.. automodule:: github_sync.views
:members:
:show-inheritance:
Management
----------
.. automodule:: github_sync.management
:members:
:show-inheritance:
Tests
-----
.. .. automodule:: github_sync.tests
.. :members:
.. :show-inheritance:
\ No newline at end of file
Common / lib
===============================
Contents:
.. toctree::
:maxdepth: 2
xmodule.rst
capa.rst
\ No newline at end of file
*******************************************
Common
*******************************************
.. module:: common.djangoapps
Student
=======
.. automodule:: student
:members:
:show-inheritance:
Models
------
.. automodule:: student.models
:members:
:show-inheritance:
Views
-----
.. automodule:: student.views
:members:
:show-inheritance:
Admin
-----
.. automodule:: student.admin
:members:
:show-inheritance:
Tests
-----
.. automodule:: student.tests
:members:
:show-inheritance:
Management
----------
.. automodule:: student.management
:members:
:show-inheritance:
Migrations
----------
.. automodule:: student.migrations
:members:
:show-inheritance:
\ No newline at end of file
Django applications
===============================
Contents:
.. toctree::
:maxdepth: 2
lms.rst
cms.rst
djangoapps-common.rst
\ No newline at end of file
.. MITx documentation master file, created by
sphinx-quickstart on Fri Nov 2 15:43:00 2012.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to MITx's documentation!
================================
Contents:
.. toctree::
:maxdepth: 2
overview.rst
common-lib.rst
djangoapps.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
*******************************************
LMS module
*******************************************
.. module:: lms
Branding
========
.. automodule:: branding
:members:
:show-inheritance:
Views
-----
.. automodule:: branding.views
:members:
:show-inheritance:
Certificates
============
.. automodule:: certificates
:members:
:show-inheritance:
Models
------
.. automodule:: certificates.models
:members:
:show-inheritance:
Views
-----
.. automodule:: certificates.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: certificates.tests
:members:
:show-inheritance:
Circuit
=======
.. automodule:: circuit
:members:
:show-inheritance:
Models
------
.. automodule:: circuit.models
:members:
:show-inheritance:
Views
-----
.. automodule:: circuit.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: circuit.tests
:members:
:show-inheritance:
Course_wiki
===========
.. automodule:: course_wiki
:members:
:show-inheritance:
Course Nav
----------
.. .. automodule:: course_wiki.course_nav
.. :members:
.. :show-inheritance:
Views
-----
.. automodule:: course_wiki.views
:members:
:show-inheritance:
Editors
-------
.. automodule:: course_wiki.editors
:members:
:show-inheritance:
Courseware
==========
.. automodule:: courseware
:members:
:show-inheritance:
Access
------
.. automodule:: courseware.access
:members:
:show-inheritance:
Admin
-----
.. automodule:: courseware.admin
:members:
:show-inheritance:
Courses
-------
.. automodule:: courseware.courses
:members:
:show-inheritance:
Grades
------
.. automodule:: courseware.grades
:members:
:show-inheritance:
Models
------
.. automodule:: courseware.models
:members:
:show-inheritance:
Progress
--------
.. automodule:: courseware.progress
:members:
:show-inheritance:
Tabs
----
.. automodule:: courseware.tabs
:members:
:show-inheritance:
Dashboard
=========
.. automodule:: dashboard
:members:
:show-inheritance:
Models
------
.. automodule:: dashboard.models
:members:
:show-inheritance:
Views
-----
.. automodule:: dashboard.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: dashboard.tests
:members:
:show-inheritance:
Django comment client
=====================
.. automodule:: django_comment_client
:members:
:show-inheritance:
Models
------
.. automodule:: django_comment_client.models
:members:
:show-inheritance:
Tests
-----
.. automodule:: django_comment_client.tests
:members:
:show-inheritance:
Heartbeat
=========
.. automodule:: heartbeat
:members:
:show-inheritance:
Instructor
==========
.. automodule:: instructor
:members:
:show-inheritance:
Views
-----
.. automodule:: instructor.views
:members:
:show-inheritance:
Tests
-----
.. .. automodule:: instructor.tests
.. :members:
.. :show-inheritance:
Lisenses
========
.. automodule:: licenses
:members:
:show-inheritance:
Models
------
.. automodule:: licenses.models
:members:
:show-inheritance:
Views
-----
.. automodule:: licenses.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: licenses.tests
:members:
:show-inheritance:
LMS migration
=============
.. automodule:: lms_migration
:members:
:show-inheritance:
Migration
---------
.. automodule:: lms_migration.migrate
:members:
:show-inheritance:
Multicourse
===========
.. automodule:: multicourse
:members:
:show-inheritance:
Psychometrics
=============
.. automodule:: psychometrics
:members:
:show-inheritance:
Models
------
.. automodule:: psychometrics.models
:members:
:show-inheritance:
Admin
-----
.. automodule:: psychometrics.admin
:members:
:show-inheritance:
Psychoanalyze
-------------
.. automodule:: psychometrics.psychoanalyze
:members:
:show-inheritance:
Simple wiki
===========
.. automodule:: simplewiki
:members:
:show-inheritance:
Models
------
.. automodule:: simplewiki.models
:members:
:show-inheritance:
Views
-----
.. automodule:: simplewiki.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: simplewiki.tests
:members:
:show-inheritance:
Static template view
====================
.. automodule:: static_template_view
:members:
:show-inheritance:
Models
------
.. automodule:: static_template_view.models
:members:
:show-inheritance:
Views
-----
.. automodule:: static_template_view.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: static_template_view.tests
:members:
:show-inheritance:
Static book
===========
.. automodule:: staticbook
:members:
:show-inheritance:
Models
------
.. automodule:: staticbook.models
:members:
:show-inheritance:
Views
-----
.. automodule:: staticbook.views
:members:
:show-inheritance:
Tests
-----
.. automodule:: staticbook.tests
:members:
:show-inheritance:
*******************************************
What the pieces are?
*******************************************
What
====
...
How
===
...
Who
===
...
\ No newline at end of file
*******************************************
Xmodule
*******************************************
.. module:: xmodule
Abtest
======
.. automodule:: xmodule.abtest_module
:members:
:show-inheritance:
Back compatibility
==================
.. automodule:: xmodule.backcompat_module
:members:
:show-inheritance:
Capa
====
.. automodule:: xmodule.capa_module
:members:
:show-inheritance:
Course
======
.. automodule:: xmodule.course_module
:members:
:show-inheritance:
Discussion
==========
.. automodule:: xmodule.discussion_module
:members:
:show-inheritance:
Editing
=======
.. automodule:: xmodule.editing_module
:members:
:show-inheritance:
Error
=====
.. automodule:: xmodule.error_module
:members:
:show-inheritance:
Error tracker
=============
.. automodule:: xmodule.errortracker
:members:
:show-inheritance:
Exceptions
==========
.. automodule:: xmodule.exceptions
:members:
:show-inheritance:
Graders
=======
.. automodule:: xmodule.graders
:members:
:show-inheritance:
Hidden
======
.. automodule:: xmodule.hidden_module
:members:
:show-inheritance:
Html checker
============
.. automodule:: xmodule.html_checker
:members:
:show-inheritance:
Html
====
.. automodule:: xmodule.html_module
:members:
:show-inheritance:
Mako
====
.. automodule:: xmodule.mako_module
:members:
:show-inheritance:
Progress
========
.. automodule:: xmodule.progress
:members:
:show-inheritance:
Schematic
=========
.. automodule:: xmodule.schematic_module
:members:
:show-inheritance:
Sequence
========
.. automodule:: xmodule.seq_module
:members:
:show-inheritance:
Stringify
=========
.. automodule:: xmodule.stringify
:members:
:show-inheritance:
Template
========
.. automodule:: xmodule.template_module
:members:
:show-inheritance:
Templates
=========
.. automodule:: xmodule.templates
:members:
:show-inheritance:
Time parse
==========
.. automodule:: xmodule.timeparse
:members:
:show-inheritance:
Vertical
========
.. automodule:: xmodule.vertical_module
:members:
:show-inheritance:
Video
=====
.. automodule:: xmodule.video_module
:members:
:show-inheritance:
X
=
.. automodule:: xmodule.x_module
:members:
:show-inheritance:
Xml
===
.. automodule:: xmodule.xml_module
:members:
:show-inheritance:
# Python libraries to install directly from github
-e git://github.com/MITx/django-staticfiles.git@6d2504e5c8#egg=django-staticfiles
-e git://github.com/MITx/django-pipeline.git#egg=django-pipeline
-e git://github.com/MITx/django-wiki.git@e2e84558#egg=django-wiki
-e git://github.com/dementrock/pystache_custom.git@776973740bdaad83a3b029f96e415a7d1e8bec2f#egg=pystache_custom-dev
#! /bin/bash
set -e
set -x
# Reset the submodule, in case it changed
git submodule foreach 'git reset --hard HEAD'
# Set the IO encoding to UTF-8 so that askbot will start
export PYTHONIOENCODING=UTF-8
rake clobber
rake pep8 || echo "pep8 failed, continuing"
rake pylint || echo "pylint failed, continuing"
#! /bin/bash
set -e
set -x
# Reset the submodule, in case it changed
git submodule foreach 'git reset --hard HEAD'
# Set the IO encoding to UTF-8 so that askbot will start
export PYTHONIOENCODING=UTF-8
GIT_BRANCH=${GIT_BRANCH/HEAD/master}
pip install -q -r pre-requirements.txt
yes w | pip install -q -r requirements.txt
[ ! -d askbot ] || pip install -q -r askbot/askbot_requirements.txt
rake clobber
TESTS_FAILED=0
rake test_cms[false] || TESTS_FAILED=1
rake test_lms[false] || TESTS_FAILED=1
rake test_common/lib/capa || TESTS_FAILED=1
rake test_common/lib/xmodule || TESTS_FAILED=1
rake phantomjs_jasmine_lms || true
rake phantomjs_jasmine_cms || true
rake coverage:xml coverage:html
[ $TESTS_FAILED == '0' ]
rake autodeploy_properties
\ No newline at end of file
#! /bin/bash
set -e
set -x
# Reset the submodule, in case it changed
git submodule foreach 'git reset --hard HEAD'
# Set the IO encoding to UTF-8 so that askbot will start
export PYTHONIOENCODING=UTF-8
GIT_BRANCH=${GIT_BRANCH/HEAD/master}
pip install -q -r pre-requirements.txt
yes w | pip install -q -r requirements.txt
[ ! -d askbot ] || pip install -q -r askbot/askbot_requirements.txt
rake clobber
TESTS_FAILED=0
rake test_lms[false] || TESTS_FAILED=1
rake test_common/lib/capa || TESTS_FAILED=1
rake test_common/lib/xmodule || TESTS_FAILED=1
rake phantomjs_jasmine_lms || true
rake coverage:xml coverage:html
[ $TESTS_FAILED == '0' ]
rake autodeploy_properties
\ No newline at end of file
# .coveragerc for lms
[run]
data_file = reports/lms/.coverage
source = lms
[report]
ignore_errors = True
[html]
directory = reports/lms/cover
[xml]
output = reports/lms/coverage.xml
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment